diff --git a/.peppa/memory.md b/.peppa/memory.md index aedf6b99..89116b0c 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -1,46 +1,54 @@ # Память проекта -Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения. +Пишет агент через MCP `remember` (PEP-30). ## Команды -- Экраны без живых данных: `PEPPA_HOME= PEPPA_DB=/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm` (принимает путь SQLite, шапка про Postgres устарела), `next dev -p <порт>` в apps/web с тем же env и `PEPPA_WEB_URL`, `peppa web login-link mock-pm`; страницы — curl с cookie (текст без `')], + ["page.html", Buffer.from("")], + ["fake.txt", Buffer.from("")], + ["run.sh", Buffer.from("#!/bin/sh\nrm -rf /\n")], + ["fake.txt", Buffer.from("#!/bin/sh\nrm -rf /\n")], + ["a.zip", zip(["a.txt"])], + ["app.exe", Buffer.concat([Buffer.from("MZ"), Buffer.alloc(64, 1)])], + ["bin.txt", Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0, 0, 0])], + ["notes.json", Buffer.from("{не json")], + ]; + for (const [name, data] of bad) assert.throws(() => core.sniffAttachment(data, name), /не принят/, name); + await assert.rejects(upload("logo.svg", bad[0]![1]), /не принят.*картинку.*PDF/s); + assert.equal((await db.select().from((await import("@peppa/db")).attachments)).length, 0, "nothing saved"); + }); + + test("Scenario: файл больше 20 МБ — понятная ошибка", async () => { + await assert.rejects(upload("big.png", Buffer.concat([PNG, Buffer.alloc(20 * 1024 * 1024)])), /больше 20 МБ/); + }); +}); + +describe("PEP-159: access", () => { + test("Scenario: посторонний не открывает файл чужого проекта", async () => { + const a = await upload("макет.png", PNG); + const mine = await core.attachmentForUser(db, pm, a.id); + assert.ok(mine && existsSync(mine.path) && mine.path.includes(`/files/${proj.id}/${a.id}/`), "stored under files///"); + assert.equal(await core.attachmentForUser(db, stranger, a.id), null, "outsider: not found"); + await assert.rejects(upload("x.png", PNG, stranger), /Не найдено/, "and cannot upload into the project either"); + }); + + test("Scenario: чужой файл нельзя привязать к своему сообщению", async () => { + const a = await upload("секрет.png", PNG); + await assert.rejects(core.linkAttachments(db, stranger, proj.id, [a.id], { taskId: 1 }), /Файл не найден/); + await assert.rejects(core.linkAttachments(db, pm, proj.id + 999, [a.id], { taskId: 1 }), /Файл не найден/, "nor into another project"); + }); +}); + +describe("PEP-159: chat with the analyst", () => { + test("Scenario: приложенные PDF, картинка и текст доходят до аналитика", async () => { + const files = [await upload("макет.png", PNG), await upload("тз.pdf", PDF), await upload("требования.txt", TXT), await upload("тз.docx", DOCX)]; + const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "Посмотрите файлы", via: "web", attachmentIds: files.map((f) => f.id) }); + const shown = (await core.attachmentsByMessage(db, [message.id])).get(message.id)!; + assert.deepEqual(shown.map((f) => [f.name, f.kind]), [["макет.png", "image"], ["тз.pdf", "pdf"], ["требования.txt", "text"], ["тз.docx", "office"]]); + await runner.analystChatTick(db, { wait: true }); + const c = calls().filter((x) => x.role === "chat").at(-1)!; + assert.deepEqual(c.files!.filter((f) => f.startsWith("file-")).sort(), [`file-${files[0]!.id}.png`, `file-${files[1]!.id}.pdf`], "image and PDF are files in the call's directory"); + assert.match(c.prompt, /«макет.png» \(\d+ B\) — картинка, файл file-\d+\.png/); + assert.match(c.prompt, /«требования.txt»[^\n]* — текстовый файл:\n---\nТребования заказчика:\n- кнопка «Купить» зелёная/, "text files go in as content"); + assert.match(c.prompt, /«тз.docx»[^\n]* документ Office/, "office files by name and type"); + }); + + test("Scenario: сообщение только с файлом получает подпись из имён", async () => { + const f = await upload("логотип.png", PNG); + const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web", attachmentIds: [f.id] }); + assert.equal(message.text, "📎 логотип.png"); + await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web" }), /Пустое сообщение/); + }); + + test("Scenario: больше пяти файлов не принимается", () => { + assert.throws(() => core.parseAttachmentIds([1, 2, 3, 4, 5, 6]), /не больше 5/); + }); +}); + +describe("PEP-159: story comment and the story's agent", () => { + test("Scenario: файл комментария к стори в бэклоге уходит аналитику", async () => { + const ref = await core.createTask(db, { projectId: proj.id, title: "Корзина", description: "Покупатель складывает товары в корзину" }); + const f = await upload("скриншот.png", PNG); + const c = await core.addStoryComment(db, ref, pm, "Вот как должно выглядеть"); + await core.linkAttachments(db, pm, proj.id, [f.id], { taskId: ref.task.id, eventId: c.id }); + await runner.storyRefineTick(db, { wait: true }); + const call = calls().filter((x) => x.role === "refine").at(-1)!; + assert.ok(call.files!.includes(`file-${f.id}.png`)); + assert.match(call.prompt, /«скриншот.png»/); + assert.equal((await core.attachmentsByEvent(db, [c.id])).get(c.id)![0]!.name, "скриншот.png", "shown under the comment"); + }); + + test("Scenario: агент находит файлы в .peppa/attachments/ и в get_task", async () => { + const p = await mockProject({ turns: [[{ mcp: "get_task", args: { task: "1" } }, { say: "ok" }]] }); + const pr = await core.getProject(db, p.key); + const ref = await core.resolveTask(db, p.taskKey); + const a = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "ТЗ клиента.pdf", data: PDF }); + const own = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "лого.png", data: PNG }); + const c = await core.addStoryComment(db, ref, { id: pr.ownerId!, login: "asel" }, "Вот ТЗ от клиента"); + await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [a.id], { taskId: ref.task.id, eventId: c.id }); + await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [own.id], { taskId: ref.task.id }); + const sid = await p.start(); + const dir = join(p.dir, ".peppa/attachments"); + await waitFor("files copied", async () => existsSync(dir) && readdirSync(dir).length >= 3); + assert.deepEqual(readdirSync(dir).sort(), [".gitignore", `${a.id}-ТЗ_клиента.pdf`, `${own.id}-лого.png`].sort()); + assert.equal(readFileSync(join(dir, ".gitignore"), "utf8"), "*\n", "never committed"); + const text = formatTask(await core.getTaskDetails(db, ref)); + assert.match(text, new RegExp(`## Приложенные файлы\\n- \`.peppa/attachments/${a.id}-ТЗ_клиента.pdf\` — «ТЗ клиента.pdf» \\(application/pdf, \\d+ B\\), приложил asel: Вот ТЗ от клиента`)); + assert.match(text, /`.peppa\/attachments\/\d+-лого.png` — «лого.png»/); + await runner.stopSession(db, sid); + }); + + test("Scenario: неотправленные файлы старше суток удаляются", async () => { + const f = await upload("забытый.png", PNG); + const found = (await core.attachmentForUser(db, pm, f.id))!; + assert.equal(await core.pruneAttachments(db, new Date()), 0, "fresh ones stay"); + assert.ok(await core.pruneAttachments(db, new Date(Date.now() + 25 * 3600_000)) >= 1); + assert.equal(existsSync(found.path), false); + assert.equal(await core.attachmentForUser(db, pm, f.id), null); + }); +}); diff --git a/packages/testkit/test/autonomy.test.ts b/packages/testkit/test/autonomy.test.ts index 83015627..ba64e6ac 100644 --- a/packages/testkit/test/autonomy.test.ts +++ b/packages/testkit/test/autonomy.test.ts @@ -29,7 +29,9 @@ describe("autonomous cycle", () => { const sid = await p.start(); const review = await p.waitQuestion(sid, "attention"); assert.match(review.text, /готова к ревью/); - assert.match(review.text, /pr\/7/); + // PEP-152: the address of the result is a technical detail — under «Подробнее». + assert.doesNotMatch(review.text, /pr\/7/); + assert.match((await core.messageDetails(db, [review.id])).get(review.id) ?? "", /pr\/7/); assert.equal(await nudges(sid), 1, "the agent was nudged once instead of pinging the PM"); assert.ok(p.log().some((e) => e.ev === "continue"), "mock continued via the Stop hook"); const qs = await db.select().from(questions).where(eq(questions.sessionId, sid)); @@ -42,17 +44,17 @@ describe("autonomous cycle", () => { assert.equal((await core.getQuestion(db, review.id)).answer, "✅ Принято"); }); - test("after two nudges in a row the PM is called; a human answer resets the counter", async () => { + test("after two nudges in a row the turn ends as progress — the PM is not called (PEP-149); a human message resets the counter", async () => { const p = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "in_progress" } }, { say: "шаг 1" }], [{ say: "шаг 2" }], [{ say: "застрял на шаге 3" }], [{ say: "понял" }]], }); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); - assert.match(q.text, /застрял на шаге 3/); + await p.waitStatus(sid, "idle"); assert.equal(await nudges(sid), runner.MAX_AUTO_NUDGES); - await runner.answerAndDeliver(db, q.id, "делай вариант Б", "telegram"); - assert.equal((await p.session(sid)).autoNudges, 0); - await p.waitLog("answer delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б")); + assert.deepEqual(await p.pending(sid), [], "nobody is asked"); + await runner.sendToSession(db, sid, "делай вариант Б"); + await p.waitLog("message delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б")); + await waitFor("the counter is reset", async () => (await p.session(sid)).autoNudges === 0); await runner.stopSession(db, sid); }); @@ -71,7 +73,7 @@ describe("autonomous cycle", () => { describe("task board", () => { test("moving a card to In progress starts an agent; back to Backlog stops it", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?" } }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?", options: ["Да", "Нет"], default: "Да" } }]] }); let ref = await core.resolveTask(db, p.taskKey); assert.equal(runner.columnOf(ref.task.status), "backlog"); const { started } = await runner.moveTask(db, ref, "in_progress"); diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts index 9d63e985..6f8f7297 100644 --- a/packages/testkit/test/bot.test.ts +++ b/packages/testkit/test/bot.test.ts @@ -79,7 +79,7 @@ describe("pairing", () => { 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 p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду." }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -138,7 +138,9 @@ describe("answering from Telegram", () => { 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"); + await p.waitStatus(sid, "idle"); + // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert. + const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Сделал черновик. Что дальше?"); const m = await messageFor(q.id); assert.match(m.text, /Что дальше/); tg.userSends(PM, "добавь тесты\nи README", m.message_id); @@ -154,7 +156,7 @@ describe("several users", () => { await waitFor("bob paired", async () => (await core.getUser(db, bobUser.id))?.telegramChatId === BOB.chatId); // PM's project: Bob has no access. - const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"] } }], [{ say: "Ок." }]] }); + const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await mine.start(); const q = await mine.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -198,11 +200,11 @@ describe("review", () => { 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 p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"], default: "8080" } }], [{ 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 runner.sendToSession(db, sid, "порт 9000", { person: true }); 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 ?? ""))); @@ -213,7 +215,9 @@ describe("staleness and reliability", () => { 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"); + await p.waitStatus(sid, "idle"); + // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert. + const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Жду указаний."); const m = await messageFor(q.id); const updateId = tg.userSends(PM, "сделай раз", m.message_id); await p.waitLog("delivered once", isPrompt("сделай раз")); @@ -227,7 +231,7 @@ describe("staleness and reliability", () => { 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 p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -259,7 +263,7 @@ describe("staleness and reliability", () => { }); 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 p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?", options: ["Да", "Нет"], default: "Да" } }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); diff --git a/packages/testkit/test/budgets.test.ts b/packages/testkit/test/budgets.test.ts index f77c4a59..3ca60c6c 100644 --- a/packages/testkit/test/budgets.test.ts +++ b/packages/testkit/test/budgets.test.ts @@ -21,7 +21,7 @@ const budgetQuestion = (taskId: number) => async function spentRunner() { const p = await project({ turns: [[{ usage: { input: 1000, output: 500 } }, { say: "Сделал часть." }]] }); const sid = await p.start(); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); await waitFor("usage recorded", async () => core.usageTotals((await core.getSession(db, sid)).usage).total === 1500); return { p, sid, task: await p.task() }; } diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts index 38f8562b..9600e9d4 100644 --- a/packages/testkit/test/chats.test.ts +++ b/packages/testkit/test/chats.test.ts @@ -9,6 +9,7 @@ import { MockTelegram } from "../src/mock-telegram.ts"; import { chatMessages, users } from "@peppa/db"; import { eq } from "drizzle-orm"; import type { Bot } from "@peppa/bot"; +import { stripAsIs } from "@peppa/shared/i18n"; const { createBot } = await import("@peppa/bot"); const { TelegramApi } = await import("@peppa/bot/telegram"); @@ -64,7 +65,8 @@ describe("project chat", () => { const msgs = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) }); const qs = msgs.filter((m) => m.question?.id === q.id); assert.equal(qs.length, 1); - assert.equal(qs[0]!.threadTitle, `${ref.key} · Экспорт в CSV`); + // PEP-139: the title is marked free text — whoever shows it translates it or strips the marks. + assert.equal(stripAsIs(qs[0]!.threadTitle!), `${ref.key} · Экспорт в CSV`); const threads = await core.chatThreads(db, chat.id); assert.equal(threads[0]!.key, threadOf(ref.task.id)); assert.equal(threads[0]!.open, 1); @@ -142,7 +144,7 @@ describe("master chat", () => { const master = await core.ensureMasterChat(db, pm.id); const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/task ${ref.key}`, via: "web" }); - assert.match(r.reply!.text, new RegExp(`${ref.key}: Платежи[\\s\\S]*бэклог`)); + assert.match(stripAsIs(r.reply!.text), new RegExp(`${ref.key}: Платежи[\\s\\S]*бэклог`)); const bad = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: "/deploy всё", via: "web" }); assert.match(bad.reply!.text, /Не знаю такую команду[\s\S]*\/move/); // Bob's master chat is his own. diff --git a/packages/testkit/test/ci-runner-config.test.ts b/packages/testkit/test/ci-runner-config.test.ts new file mode 100644 index 00000000..d30c5e56 --- /dev/null +++ b/packages/testkit/test/ci-runner-config.test.ts @@ -0,0 +1,14 @@ +// PEP-157: with capacity 2 the queue of checks grew to hours at 13 open PRs; the host has 24 cores. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { describe, test } from "node:test"; + +const config = readFileSync(new URL("../../../infra/act-runner/config.yaml", import.meta.url), "utf8"); + +describe("PEP-157: очередь проверок — четыре одновременно", () => { + test("Значение вернули к двум: runner.capacity в конфиге раннера не меньше 4", () => { + const runner = config.slice(config.indexOf("\nrunner:")); + const capacity = Number(/^ {2}capacity:\s*(\d+)\s*$/m.exec(runner)?.[1]); + assert.ok(capacity >= 4, `runner.capacity must be at least 4 in infra/act-runner/config.yaml, got ${capacity}`); + }); +}); diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts index 47ba8e10..9c38b55a 100644 --- a/packages/testkit/test/cjm.test.ts +++ b/packages/testkit/test/cjm.test.ts @@ -53,7 +53,9 @@ describe("Claude: task lifecycle", () => { assert.equal(doneAttempt?.isError, true, "agent must not be able to mark the task done"); const attention = await p.waitQuestion(sid, "attention"); - assert.match(attention.text, /PR открыт/); + // PEP-152: «готово» in the common format; the agent's last reply is under «Подробнее». + assert.match(attention.text, /готова к ревью\nЧто нужно от вас: /); + assert.match((await core.messageDetails(db, [attention.id])).get(attention.id) ?? "", /PR открыт/); await runner.stopSession(db, sid); }); @@ -76,7 +78,7 @@ describe("Claude: task lifecycle", () => { describe("Claude: questions to the PM", () => { test("ask_pm question answered from Telegram is typed into the session", async () => { const p = await project({ - turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]], + turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]], }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); @@ -90,7 +92,9 @@ describe("Claude: questions to the PM", () => { test("multi-line answer arrives as one prompt (bracketed paste)", async () => { const p = await project({ turns: [[{ say: "Что дальше?" }], [{ say: "Понял." }]] }); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); + // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert. + const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Что дальше?"); await runner.answerAndDeliver(db, q.id, "строка один\nстрока два", PM); const e = await p.waitLog("pasted prompt", isPrompt("строка один")); assert.equal(e.prompt, "строка один\nстрока два"); @@ -127,10 +131,10 @@ describe("Claude: questions to the PM", () => { }); test("typing in the terminal answers whatever the session was waiting for", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?" } }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); - await runner.sendToSession(db, sid, "назови peppa-api"); + await runner.sendToSession(db, sid, "назови peppa-api", { person: true }); await waitFor("answered via terminal", async () => (await core.getQuestion(db, q.id)).answeredVia === "terminal"); assert.equal((await core.getQuestion(db, q.id)).answer, "назови peppa-api"); await runner.stopSession(db, sid); @@ -242,7 +246,7 @@ describe("Claude: failures and recovery", () => { test("tmux session killed from outside → failed, PM alerted", async () => { const p = await project({ turns: [[{ say: "Работаю." }]] }); const sid = await p.start(); - await p.waitStatus(sid, "waiting_input"); + await p.waitStatus(sid, "idle"); execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]); await tick(); assert.equal((await p.session(sid)).status, "failed"); @@ -256,7 +260,7 @@ describe("Claude: failures and recovery", () => { const cleared = await p.waitLog("cleared", (e) => e.ev === "clear"); await waitFor("new conversation id stored", async () => (await p.session(sid)).conversationId === cleared.newConversationId); assert.notEqual(before, cleared.newConversationId); - await p.waitStatus(sid, "waiting_input"); + await p.waitStatus(sid, "idle"); await runner.stopSession(db, sid); }); @@ -280,14 +284,14 @@ describe("Codex", () => { const mcpCall = await p.waitLog("codex reaches peppa MCP", (e) => e.ev === "mcp" && e.tool === "get_task"); assert.equal(mcpCall.isError, false); - const alert = await p.waitQuestion(sid, "attention"); - assert.match(alert.text, /какой фреймворк/); + // PEP-149: the end of a turn is a progress record, not a question to the PM. + await p.waitStatus(sid, "idle"); + assert.deepEqual(await p.pending(sid), []); const s = await p.session(sid); assert.equal(s.provider, "codex"); - assert.equal(s.status, "waiting_input"); assert.equal(s.conversationId, start.conversationId); - await runner.answerAndDeliver(db, alert.id, "Fastify", PM); + await runner.sendToSession(db, sid, "Fastify"); await p.waitLog("answer typed in", isPrompt("Fastify")); await runner.stopSession(db, sid); }); @@ -307,9 +311,9 @@ describe("Codex", () => { test("crash → resume uses `codex resume `", async () => { const p = await project({ turns: [[{ say: "Первый ход." }], [{ crash: 2 }]], resumeTurns: [[{ say: "Вернулся." }]] }); const sid = await p.start({ provider: "codex" }); - const alert = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); const thread = (await p.session(sid)).conversationId; - await runner.answerAndDeliver(db, alert.id, "продолжай", PM); + await runner.sendToSession(db, sid, "продолжай"); await p.waitLog("crashed", (e) => e.ev === "exit"); await waitFor("failed", async () => { await tick(); diff --git a/packages/testkit/test/claude-live.test.ts b/packages/testkit/test/claude-live.test.ts index 3cfce8a1..4b2f055d 100644 --- a/packages/testkit/test/claude-live.test.ts +++ b/packages/testkit/test/claude-live.test.ts @@ -9,7 +9,7 @@ import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, describe, test } from "node:test"; import { events } from "@peppa/db"; -import { asc, eq } from "drizzle-orm"; +import { and, asc, eq } from "drizzle-orm"; import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; after(teardown); @@ -177,7 +177,7 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", () await runner.stopSession(db, sid); }); - test("Stop: стори в работе → decision block; после двух — PM", async () => { + test("Stop: стори в работе → decision block; после двух — ход работы, PM не зовём", async () => { const p = await project({ turns: [[{ sleep: 60_000 }]] }); const sid = await p.start(); // The prompt hook resets auto_nudges; let it finish before the Stop hooks are counted. @@ -190,8 +190,13 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", () assert.match(first.reason, new RegExp(p.taskKey)); assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block"); assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null); - const q = await p.waitQuestion(sid, "attention"); - assert.equal(q.text, fixture("stop-after-block").last_assistant_message); + // PEP-149: the last reply becomes a progress record — the PM is not asked. + assert.deepEqual(await p.pending(sid), []); + const [progress] = await db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, "progress"))); + // PEP-152: in the common format — a plain reply is the gist, a technical one is under «Подробнее». + const said = progress!.payload as { text: string; details?: string }; + assert.ok(`${said.text}\n${said.details ?? ""}`.includes(String(fixture("stop-after-block").last_assistant_message).trim())); + assert.ok(said.text.split("\n").length <= core.MAIN_MAX_LINES); await runner.stopSession(db, sid); }); }); diff --git a/packages/testkit/test/deploy.test.ts b/packages/testkit/test/deploy.test.ts index 6e64761f..43dc4759 100644 --- a/packages/testkit/test/deploy.test.ts +++ b/packages/testkit/test/deploy.test.ts @@ -1,6 +1,7 @@ // PEP-57, spec delivery-pipeline: «Деплой по окружениям» и «Проверка здоровья и откат». // The template's .gitea/peppa-deploy.sh runs for real against mock-docker (docker CLI on // PATH) and a mock health endpoint; it reports to Peppa through handleGiteaHook. +import { stripAsIs } from "@peppa/shared/i18n"; import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; @@ -259,7 +260,7 @@ describe("Проверка здоровья и откат", () => { const msg = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.text.includes(bad.slice(0, 7)) && q.text.includes("не прошло проверку"))!; assert.ok(msg, "the PM got a message"); assert.match(msg.text, new RegExp(`возвращена прежняя версия ${good.slice(0, 7)}`)); - assert.match(msg.text, /Причина: проверка \/healthz/); + assert.match(stripAsIs(msg.text), /Причина: проверка \/healthz/); assert.match(msg.text, new RegExp(`Подробности: ${gitea.url}/test/${d.proj.giteaRepo}/actions/runs/5`)); assert.equal((await runner.currentReleases(db, d.proj.id)).prod?.sha, good); }); diff --git a/packages/testkit/test/discussion.test.ts b/packages/testkit/test/discussion.test.ts index f612717f..eafb88eb 100644 --- a/packages/testkit/test/discussion.test.ts +++ b/packages/testkit/test/discussion.test.ts @@ -99,4 +99,24 @@ describe("PEP-106: project discussion", () => { const rest = await core.chatMessagesView(db, chat.id, {}); assert.ok(rest.every((m) => m.kind === "user" && m.threadKey === null && !m.text.startsWith("/")), "events, threads and commands are pruned"); }); + + // PEP-161, spec project-chats: «Чат с аналитиком из раздела „Проекты“». + test("PEP-161: Ссылка на аналитика у своего проекта · Непрочитанный ответ аналитика виден на карточке", async () => { + await core.markDiscussionRead(db, owner.id, chat.id); + const before = (await core.analystLinks(db, owner)).get(project.id); + assert.deepEqual(before, { href: "/chats/MTLK", unread: 0 }); + await core.addChatMessage(db, { chatId: chat.id, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text: "Готово: каталог открыт." }); + assert.deepEqual((await core.analystLinks(db, owner)).get(project.id), { href: "/chats/MTLK", unread: 1 }); + assert.equal((await core.analystLinks(db, member)).get(project.id)?.href, "/chats/MTLK", "a member writes to the analyst too"); + }); + + test("PEP-161: У чужого проекта ссылки нет", async () => { + await core.setPlatformAdmins(db, [stranger.login]); + try { + assert.ok((await core.listOtherProjects(db, stranger.id)).some((p) => p.key === "MTLK"), "the superadmin sees the project among other people's"); + assert.equal((await core.analystLinks(db, stranger)).size, 0); + } finally { + await core.setPlatformAdmins(db, null); + } + }); }); diff --git a/packages/testkit/test/factory-messages-verbatim.test.ts b/packages/testkit/test/factory-messages-verbatim.test.ts new file mode 100644 index 00000000..286c70b1 --- /dev/null +++ b/packages/testkit/test/factory-messages-verbatim.test.ts @@ -0,0 +1,130 @@ +// PEP-140: foreign text put into the factory's own messages — a story title, a project name, +// the reviewer's and the agent's words — reaches the reader as written; the factory's phrases +// around it are translated. Unit checks and the real bot against mock-telegram (English reader). +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, project, runner, setDefaultOwner, teardown, waitFor } from "./helpers.ts"; +import { MockTelegram } from "../src/mock-telegram.ts"; +import { projects, users } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { asIs, localizeText, m, stripAsIs } from "@peppa/shared/i18n"; +import type { Bot } from "@peppa/bot"; + +const { createBot } = await import("@peppa/bot"); +const { TelegramApi } = await import("@peppa/bot/telegram"); + +const TITLE = "Сделано три задачи из пяти"; +const PROJECT = "Сделано три задачи"; +const SAID = "Готово три задачи из пяти."; +const MARKS = /[⁨⁩]/; +const CYR = /[А-Яа-яЁё]/; +const IDLE = "😴 {project}: агенты простаивают, в бэклоге {n}. Взять в работу {key} «{title}»?"; + +describe("чужой текст в шаблонах фабрики", () => { + test("без пометки общий перевод переписывает название — причина стори", () => { + const en = localizeText("en", m(IDLE, { project: PROJECT, n: 2, key: "DEMO-1", title: TITLE })); + assert.ok(!en.includes(`“${TITLE}”`) || !en.startsWith(`😴 ${PROJECT}:`), en); + }); + + test("Scenario: Агенты простаивают — название задачи и проекта дословно", () => { + const en = localizeText("en", m(IDLE, { project: asIs(PROJECT), n: 2, key: "DEMO-1", title: asIs(TITLE) })); + assert.equal(en, `😴 ${PROJECT}: agents are idle, 2 in the backlog. Start working on DEMO-1 “${TITLE}”?`); + }); + + test("Scenario: Название задачи на казахском", () => { + const kk = localizeText("kk", m(IDLE, { project: asIs("Демо"), n: 2, key: "DEMO-1", title: asIs(TITLE) })); + assert.ok(kk.includes("агенттер бос тұр"), kk); + assert.ok(kk.includes(`«${TITLE}»`), kk); + }); + + test("Scenario: Итог ревьюера дословно", () => { + const review = { state: "done", verdict: "ok", summary: `${TITLE}.`, findings: [], sha: "abcdef1234", error: null } as never; + assert.equal(localizeText("en", core.reviewNote(review)), `🔎 Reviewer: ok — ${TITLE}.`); + const changes = { state: "done", verdict: "changes", summary: `${TITLE}.`, findings: [{ file: "a.ts", line: 3, severity: "blocker", text: SAID }], sha: "abcdef1234", error: null } as never; + const en = localizeText("en", core.reviewNote(changes)); + assert.ok(en.endsWith(`— ${TITLE}.\n• a.ts:3 — ${SAID}`), en); + assert.doesNotMatch(en.split("\n")[0]!.replace(`${TITLE}.`, ""), CYR); + // The agent gets the findings without marks. + assert.doesNotMatch(core.formatFindings((changes as { findings: never[] }).findings), MARKS); + assert.equal(stripAsIs(core.reviewNote(review)), `🔎 Ревьюер: ок — ${TITLE}.`); + }); + + test("Scenario: Причина от самой фабрики внутри сообщения переводится", () => { + // The gate's reason is the factory's own phrase from the dictionary — it is not marked. + const en = localizeText("en", m("Принять не удалось: {reason}", { reason: core.GATE_UNKNOWN_REASON })); + assert.match(en, /^Could not accept: could not check/); + assert.doesNotMatch(en, CYR); + }); + + test("страница задачи, сводка и ошибки из продукта — названия дословно", () => { + const need = { title: TITLE } as never; + assert.equal(core.needsLine([need, need]), `${TITLE}, ${TITLE}`); + assert.equal(localizeText("en", core.needsLine([need], asIs)), TITLE); + const digest = core.renderDigest({ projects: [{ key: "DEMO", name: PROJECT, done: [{ key: "DEMO-1", title: TITLE }], inProgress: [], review: [], blocked: [], waiting: 0, stalled: 0, rateLimited: 0, limitResumes: 0 }], totals: { done: 1, inProgress: 0, review: 0, waiting: 0, stuck: 0 } }, { webUrl: "http://peppa.test" }); + const en = localizeText("en", digest); + assert.ok(en.includes(`${PROJECT} (DEMO)`), en); + assert.ok(en.includes(` ${TITLE}`), en); + assert.doesNotMatch(en.replaceAll(TITLE, "").replaceAll(PROJECT, ""), CYR); + }); +}); + +describe("бот: Telegram на английском", () => { + const tg = new MockTelegram(); + const PM = { id: 811, chatId: 811, username: "pm" }; + let bot: Bot; + let pm: Awaited>; + const toPm = () => tg.botMessages(PM.chatId); + + before(async () => { + process.env.PEPPA_SECRET = "mock-secret-for-tests"; + await tg.start(); + pm = await core.upsertUserFromGitea(db, { id: 93, login: "mock-pm" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id)); + pm = (await core.getUser(db, pm.id))!; + await core.setUserLocale(db, pm.id, "en"); + setDefaultOwner(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, changesIntervalMs: 200, log: (x) => process.env.MOCK_DEBUG && console.log(x) }); + await bot.start(); + }); + after(async () => { + setDefaultOwner(null); + await bot?.stop(); + await tg.stop(); + await teardown(); + }); + + test("Scenario: Задача готова к ревью — название и слова агента дословно", async () => { + const p = await project({ turns: [[{ sleep: 1500 }, { say: SAID }]] }); + const ref = await core.resolveTask(db, p.taskKey); + await core.updateTask(db, ref, { title: TITLE }); + const sid = await p.start(); + // The story goes to review while the agent works; its turn ends → «готова к ревью». + await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "review" }); + const q = await p.waitQuestion(sid, "attention"); + assert.match(q.text, /готова к ревью/); + const msg = await waitFor("ready for review in Telegram", async () => toPm().find((x) => x.text.includes("is ready for review"))); + assert.ok(msg.text.includes(`${TITLE}`), msg.text); + assert.ok(msg.text.includes(`✅ Task ${p.taskKey} is ready for review`), msg.text); + // PEP-152: the agent's last reply is a technical detail — not in Telegram, verbatim under «Подробнее». + assert.ok(!msg.text.includes(SAID), msg.text); + assert.ok((msg.text.match(/Where to look: /g) ?? []).length <= 1, msg.text); + assert.ok(localizeText("en", (await core.messageDetails(db, [q.id])).get(q.id) ?? "").includes(SAID)); + assert.doesNotMatch(msg.text.replace(TITLE, ""), CYR, msg.text); + assert.doesNotMatch(msg.text, MARKS); + await runner.stopSession(db, sid).catch(() => {}); + }); + + test("Scenario: Агенты простаивают — в Telegram название задачи и проекта дословно", async () => { + const p = await project({ turns: [[{ say: "ok" }]] }); + const ref = await core.resolveTask(db, p.taskKey); + await core.updateTask(db, ref, { title: TITLE }); + await db.update(projects).set({ name: PROJECT }).where(eq(projects.id, ref.project.id)); + await core.setAutonomy(db, ref.project.id, { level: "assisted", quietFrom: null, quietTo: null }); + await runner.autonomyTick(db, { now: new Date() }); + const msg = await waitFor("idle push in Telegram", async () => toPm().find((x) => x.text.includes("agents are idle"))); + assert.ok(msg.text.includes(`😴 ${PROJECT}: agents are idle, 1 in the backlog. Start working on ${p.taskKey} “${TITLE}”?`), msg.text); + assert.doesNotMatch(msg.text.replaceAll(TITLE, "").replaceAll(PROJECT, ""), CYR, msg.text); + for (const c of tg.calls.filter((x) => x.params.chat_id === PM.chatId)) assert.doesNotMatch(JSON.stringify(c.params), MARKS, "the marks do not reach Telegram"); + }); +}); diff --git a/packages/testkit/test/free-text-verbatim.test.ts b/packages/testkit/test/free-text-verbatim.test.ts new file mode 100644 index 00000000..a1da12c8 --- /dev/null +++ b/packages/testkit/test/free-text-verbatim.test.ts @@ -0,0 +1,165 @@ +// PEP-139: free text of people and agents reaches the reader as written — the translation of +// rendered messages touches only the factory's own phrases. Unit checks of the marks, and the +// real bot against mock-telegram: a linked group and a private chat reading English. +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 { users } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { asIs, localizeRoleMessage, localizeText, m, stripAsIs, translator } from "@peppa/shared/i18n"; +import type { Bot } from "@peppa/bot"; + +const { createBot } = await import("@peppa/bot"); +const { TelegramApi } = await import("@peppa/bot/telegram"); +const { renderAnswered, renderQuestion } = await import("@peppa/bot/render"); + +const FREE = "Сделано три задачи из пяти."; +const MARKS = /[⁨⁩]/; + +describe("пометка свободного текста", () => { + test("общий перевод переписывает непомеченный свободный текст — причина стори", () => { + assert.notEqual(localizeText("en", FREE), FREE); + }); + + test("помеченный текст остаётся дословным, фразы вокруг переводятся", () => { + assert.equal(localizeText("en", asIs(FREE)), FREE); + assert.equal(localizeText("kk", asIs(FREE)), FREE); + assert.equal(localizeText("en", `${m("❓ Вопрос")}\n${asIs(FREE)}`), `❓ Question\n${FREE}`); + assert.equal(localizeText("en", m("Ошибка: {message}", { message: asIs(FREE) })), `Error: ${FREE}`); + // Several lines of free text are not split into lines and translated one by one. + assert.equal(localizeText("en", `${asIs("anna")}${m(" (веб): {text}", { text: asIs(`Проекты\n${FREE}`) })}`), `anna (web): Проекты\n${FREE}`); + }); + + test("русскому читателю и без перевода пометка снимается", () => { + assert.equal(localizeText("ru", `📈 ${asIs(FREE)}`), `📈 ${FREE}`); + assert.equal(stripAsIs(asIs(FREE)), FREE); + assert.equal(localizeRoleMessage("en", `📈 ${asIs(FREE)}`), `📈 ${FREE}`); + assert.equal(translator("en").text(asIs("Проекты")), "Проекты"); + assert.equal(asIs(""), ""); + assert.equal(asIs(null), ""); + }); + + test("обрезанная пометка действует до конца текста, вложенная не ломает", () => { + const cut = `${m("❓ Вопрос")}\n${asIs(FREE).slice(0, -1)}`; + assert.equal(localizeText("en", cut), `❓ Question\n${FREE}`); + assert.equal(localizeText("en", asIs(`до ${asIs(FREE)} после`)), `до ${FREE} после`); + assert.equal(localizeText("en", `${FREE}⁩`), localizeText("en", FREE)); + }); +}); + +describe("вопросы", () => { + const ctx = { taskKey: "DEMO-1", taskTitle: "Готово три задачи из пяти", session: null, webUrl: "http://peppa.test" }; + const q = (over: Record) => ({ id: 7, kind: "question", text: "Какой формат из двух оставить? Готово три задачи из пяти.", options: ["Задачи из списка", "Готово"], sessionId: 3, answer: null, answeredVia: null, ...over }) as never; + + test("Scenario: Вопрос агента с вариантами", () => { + const r = renderQuestion(q({}), ctx); + const en = localizeText("en", r.text); + assert.match(en, /❓ Question/); + assert.ok(en.includes("Какой формат из двух оставить? Готово три задачи из пяти."), en); + assert.ok(en.includes("Готово три задачи из пяти"), en); + assert.deepEqual(r.buttons.map((b) => localizeText("en", b[0]!.text)), ["Задачи из списка", "Готово"]); + // The same button unmarked would be translated. + assert.notEqual(localizeText("en", "Готово"), "Готово"); + }); + + test("Scenario: Вопрос фабрики по-прежнему переводится", () => { + const text = m("⚠️ {key}: изменения затрагивают проверки или обновление продукта — сама задача не закроется, нужно ваше «Принять».", { key: "DEMO-1" }); + const r = renderQuestion(q({ sessionId: null, text, options: null }), { ...ctx, taskTitle: null }); + assert.doesNotMatch(localizeText("en", r.text), /[А-Яа-яЁё]/); + assert.doesNotMatch(r.text, MARKS); + }); + + test("ответ человека под закрытым вопросом — дословно", () => { + const original = renderQuestion(q({}), ctx).text; + const en = localizeText("en", renderAnswered(original, q({ answer: FREE, answeredVia: "telegram" }))); + assert.ok(en.includes(`${FREE}`), en); + assert.doesNotMatch(en.split("\n").at(-1)!.replace(FREE, ""), /[А-Яа-яЁё]/); + }); +}); + +describe("бот: Telegram на английском", () => { + const tg = new MockTelegram(); + const PM = { id: 801, chatId: 801, username: "pm" }; + const BOB = { id: 802, chatId: 802, username: "bob" }; + const GROUP = { id: -100900, title: "DEMO team" }; + let bot: Bot; + let pm: Awaited>; + let bob: typeof pm; + let p: Awaited>; + let chat: Awaited>; + const group = () => tg.botMessages(GROUP.id); + const sentTo = (chatId: number) => tg.calls.filter((c) => c.params.chat_id === chatId); + + before(async () => { + process.env.PEPPA_SECRET = "mock-secret-for-tests"; + await tg.start(); + pm = await core.upsertUserFromGitea(db, { id: 91, login: "mock-pm" }, { access_token: "x" }); + bob = await core.upsertUserFromGitea(db, { id: 92, login: "mock-bob" }, { access_token: "y" }); + await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id)); + await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id)); + pm = (await core.getUser(db, pm.id))!; + bob = (await core.getUser(db, bob.id))!; + // The PM reads English (their private chat and the group they link); Bob reads Russian. + await core.setUserLocale(db, pm.id, "en"); + p = await core.createProject(db, { slug: "demo", key: "DEMO", name: "Демо", giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id }); + await core.addMember(db, p, bob.login, pm.id); + chat = await core.ensureProjectChat(db, p.id); + bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, changesIntervalMs: 200, log: (x) => process.env.MOCK_DEBUG && console.log(x) }); + await bot.start(); + await bot.reconcile(); // first start: mirroring begins from here + tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true })}`); + await waitFor("linked", async () => (await core.getChat(db, chat.id)).tgChatId === GROUP.id); + }); + after(async () => { + await bot?.stop(); + await tg.stop(); + await teardown(); + }); + + test("Scenario: Сообщение человека в Telegram-группе с английским языком", async () => { + await runner.postToChat(db, bob, { chatId: chat.id, threadKey: null, text: FREE, via: "web" }); + const msg = await waitFor("mirrored", async () => group().find((x) => x.text.includes("mock-bob"))); + assert.equal(msg.text, `mock-bob (web): ${FREE}`); + }); + + test("Scenario: Заметка агента о прогрессе", async () => { + const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: p.id, title: "Готово три задачи из пяти" })).key); + const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id }); + await core.reportProgress(db, ref, FREE, s.id); + const msg = await waitFor("progress mirrored", async () => group().find((x) => x.text.includes("📈"))); + assert.ok(msg.text.endsWith(`📈 ${FREE}`), msg.text); + // The story title in the thread line is the person's own words too. + assert.ok(msg.text.includes("DEMO-1 · Готово три задачи из пяти"), msg.text); + assert.doesNotMatch(msg.text, MARKS); + }); + + test("Scenario: Вопрос агента с вариантами; русский читатель не видит служебных пометок", async () => { + const ref = await core.resolveTask(db, "DEMO-1"); + const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id }); + const text = "Какой формат из двух оставить? Готово три задачи из пяти."; + await core.askPm(db, ref, { kind: "question", text, options: ["Задачи из списка", "Готово"], sessionId: s.id }); + const en = await waitFor("question to the PM", async () => tg.botMessages(PM.chatId).find((x) => x.text.includes("Какой формат"))); + assert.match(en.text, /❓ Question/); + assert.ok(en.text.includes(text), en.text); + assert.deepEqual(en.reply_markup?.inline_keyboard.flat().map((b) => b.text), ["Задачи из списка", "Готово"]); + const ru = await waitFor("question to Bob", async () => tg.botMessages(BOB.chatId).find((x) => x.text.includes("Какой формат"))); + assert.match(ru.text, /❓ Вопрос/); + assert.ok(ru.text.includes(text)); + for (const c of [...sentTo(PM.chatId), ...sentTo(BOB.chatId), ...sentTo(GROUP.id)]) assert.doesNotMatch(JSON.stringify(c.params), MARKS, "the marks do not reach Telegram"); + }); + + test("Scenario: Сообщение ИИ-роли в группе", async () => { + await runner.sayInDiscussion(db, p, chat.id, `${FREE}\n\n${m("Завёл в бэклог:")}\n• DEMO-2 «Экспорт в PDF»`); + const msg = await waitFor("role message mirrored", async () => group().find((x) => x.text.includes("Added to the backlog:"))); + assert.equal(msg.text, `Analyst (web): ${FREE}\n\nAdded to the backlog:\n• DEMO-2 «Экспорт в PDF»`); + }); + + test("Scenario: Вопрос фабрики по-прежнему переводится", async () => { + const ref = await core.resolveTask(db, "DEMO-1"); + await core.askPm(db, ref, { kind: "question", text: m("⚠️ {key}: изменения затрагивают проверки или обновление продукта — сама задача не закроется, нужно ваше «Принять».", { key: ref.key }) }); + const msg = await waitFor("factory question", async () => tg.botMessages(PM.chatId).find((x) => x.text.includes("⚠️ DEMO-1"))); + assert.doesNotMatch(msg.text.replace("Готово три задачи из пяти", ""), /[А-Яа-яЁё]/, msg.text); + }); +}); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index e500b1d5..f86496bb 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -31,6 +31,8 @@ Object.assign(process.env, { // PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with // accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on. PEPPA_PRODUCT_LINK: "off", + // PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe. + PEPPA_WEB_PROBE: "off", }); mkdirSync(process.env.PEPPA_HOME!, { recursive: true }); diff --git a/packages/testkit/test/i18n-role-messages.test.ts b/packages/testkit/test/i18n-role-messages.test.ts new file mode 100644 index 00000000..e85a9ed8 --- /dev/null +++ b/packages/testkit/test/i18n-role-messages.test.ts @@ -0,0 +1,142 @@ +// PEP-138: the fixed phrases of the AI roles' messages in the project's discussion (analyst, +// product agent, the «чтобы заработало по-настоящему» list) reach the reader in their language. +// Tests are named after the scenarios of the `interface-language` spec. +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, 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 { sql } from "drizzle-orm"; +import { localizeRoleMessage, localizeText } from "@peppa/shared/i18n"; +import { core, db, runner, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +process.env.PEPPA_WEB_URL = "http://peppa.test"; +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-role-messages-")); +const scenario = join(TMP, "scenario.json"); +const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s)); +const tick = () => runner.analystChatTick(db, { wait: true }); +/** Russian letters that are not Kazakh-only: a rough «no Russian fixed phrase is left» for en. */ +const RU = /[А-Яа-яЁё]/; + +type User = Awaited>; +let pm: User; +let project: Awaited>; +let chat: Awaited>; +const post = (text: string) => runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text, via: "web" }); +const last = async () => (await core.discussionMessages(db, chat.id)).at(-1)!; +const lastTelegram = async () => { + const out = await db.all<{ params: string }>(sql`select params from telegram_outbox where dedupe_key like 'chat:m%' order by id desc limit 1`); + return JSON.parse(out[0]!.params) as { text: string; peppa_localized?: boolean }; +}; +/** What the web shows for an AI role's message (`t.role`). */ +const web = localizeRoleMessage; + +before(async () => { + process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake"); + process.env.MOCK_INTAKE_SCENARIO = scenario; + setScenario({}); + pm = await core.upsertUserFromGitea(db, { id: 1381, login: "asel" }, { access_token: "x" }); + db.run(sql`update users set telegram_chat_id = 9138 where id = ${pm.id}`); + const ws = join(TMP, "ws"); + mkdirSync(join(ws, ".peppa"), { recursive: true }); + project = await core.createProject(db, { slug: "mock-roles", key: "DEMO", name: "Демо", giteaOwner: "x", workspacePath: ws, ownerId: pm.id }); + chat = await core.ensureProjectChat(db, project.id); +}); +after(teardown); + +const need = { id: "n1", title: "Ключ Claude API", why: "без него ответы — вымышленные примеры", how: "console.anthropic.com → API Keys", secret: "ANTHROPIC_API_KEY", source: "agent" as const, story: null, doneAt: null }; + +describe("PEP-138: AI roles' messages in the reader's language", () => { + test("Scenario Outline: Аналитик завёл задачу", async () => { + setScenario({ chat: { reply: "Готово.", create: [{ title: "Экспорт в PDF", description: "Кнопка «Скачать PDF»." }] } }); + await post("Заведи экспорт в PDF"); + await tick(); + const m = await last(); + assert.equal(m.authorKind, "agent"); + assert.equal(m.text, "Готово.\n\nЗавёл в бэклог:\n• DEMO-1 «Экспорт в PDF»"); + assert.equal(web("en", m.text), "Готово.\n\nAdded to the backlog:\n• DEMO-1 «Экспорт в PDF»"); + assert.equal(web("kk", m.text), "Готово.\n\nБэклогқа қостым:\n• DEMO-1 «Экспорт в PDF»"); + assert.equal(web("ru", m.text), m.text); + assert.equal(web("en", m.authorLogin), "Analyst"); + // Telegram, Russian reader: as before. + assert.match((await lastTelegram()).text, /Демо<\/b> · Аналитик:\nГотово\.\n\nЗавёл в бэклог:\n• DEMO-1[^]*Ответить: http:\/\/peppa\.test\/chats\/DEMO/); + // Telegram, English reader: written in English when queued and marked, so the bot does not translate it again. + await core.setUserLocale(db, pm.id, "en"); + await post("И ещё раз"); + await tick(); + const tg = await lastTelegram(); + assert.equal(tg.peppa_localized, true); + assert.match(tg.text, /Демо<\/b> · Analyst:\nГотово\.\n\nAdded to the backlog:\n• DEMO-2[^]*Reply: http:\/\/peppa\.test\/chats\/DEMO/); + setScenario({}); + }); + + test("Scenario: Сообщение продакта после приёмки на английском", async () => { + const text = core.productReviewMessage( + { summary: "Продукт показывает список стажировок.", howto: ["Откройте адрес.", "Нажмите «Найти»."], notReal: ["Ответы — вымышленные примеры."], needs: [], stories: [] }, + { env: "staging", url: "https://demo-staging.telecom.quest", openNeeds: [{ ...need, open: true }], filed: ["DEMO-9 «Убрать служебное поле»"], webUrl: "http://peppa.test", projectKey: "DEMO" }, + ); + await runner.sayInDiscussion(db, project, chat.id, text, core.PRODUCT_AGENT_NAME); + const en = web("en", (await last()).text).split("\n"); + assert.equal(en[0], "Looked at the review version: https://demo-staging.telecom.quest"); + for (const line of ["How to use it:", "Not real yet:", "To make it work for real, we need from you:", " Where to get it: console.anthropic.com → API Keys", "Paste it or tick «Done» in the «Your product» card: http://peppa.test/p/DEMO", "Added improvements to the backlog:"]) assert.ok(en.includes(line), `${line}\n— in —\n${en.join("\n")}`); + assert.ok(en.includes("Продукт показывает список стажировок."), "the model's own text is left as written"); + assert.match((await lastTelegram()).text, /Демо<\/b> · Product:\nLooked at the review version:[^]*\nПродукт показывает список стажировок\./); + assert.equal(web("en", core.productReviewMessage({ summary: "Ок.", howto: [], notReal: [], needs: [], stories: [] }, { env: "prod", url: "https://demo-prod.telecom.quest", openNeeds: [], filed: [], webUrl: "", projectKey: "DEMO" })), "Looked at the live version: https://demo-prod.telecom.quest\n\nОк."); + }); + + test("Scenario: Список нужного от владельца на казахском", () => { + const ru = ["Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:", "", core.needsText([need, { ...need, id: "n2", title: "Аккаунт Stripe", why: "", how: "", secret: null }], "http://peppa.test", "DEMO")].join("\n"); + const kk = web("kk", ru); + assert.doesNotMatch(kk, /Где взять|Куда вставить|Когда сделаете|Ключи хранятся зашифрованными|нужно от вас|Карточка/); + assert.match(kk, /^Өнім демо-режимде емес, шын жұмыс істеуі үшін сізден керек:/); + assert.match(kk, /1\. Ключ Claude API — без него ответы — вымышленные примеры\n {3}Қайдан алуға болады: console\.anthropic\.com → API Keys\n {3}Қайда қою керек:/); + assert.match(kk, /2\. Аккаунт Stripe\n {3}Орындаған соң/); + assert.match(kk, /«Сіздің өніміңіз» карточкасы: http:\/\/peppa\.test\/p\/DEMO/); + const en = web("en", ru); + assert.match(en, /Where to paste it: project page → «Your product» card/); + assert.match(en, /Keys are stored encrypted; Peppa FACTORY will pass them to the product and restart it\./); + }); + + test("Scenario: Заметка о демо-режиме в «готово к ревью»", async () => { + await core.declareNeeds(db, project.id, [{ title: "Ключ Claude API", secret: "ANTHROPIC_API_KEY" }], { source: "agent" }); + const note = await core.demoNote(db, project.id, "DEMO", "http://peppa.test"); + assert.equal(localizeText("en", note), "⚠️ The product is still running in demo mode. We need from you: Ключ Claude API\nYou can paste it in the «Your product» card: http://peppa.test/p/DEMO"); + assert.match(localizeText("kk", note), /^⚠️ Өнім әзірге демо-режимде жұмыс істеп тұр\. Сізден керек: Ключ Claude API\n«Сіздің өніміңіз» карточкасына қоюға болады:/); + }); + + test("Scenario: Аналитик не смог ответить — английский", async () => { + setScenario({ fail: true }); + await post("Ты тут?"); + await tick(); + const fail = await last(); + assert.equal(fail.authorKind, "system"); + assert.equal(localizeText("en", fail.text), "The analyst could not answer right now. Please write again a little later."); + assert.doesNotMatch(localizeText("kk", fail.text), /не смог/); + setScenario({ garbage: true }); + await post("А теперь?"); + await tick(); + assert.doesNotMatch(localizeText("en", (await last()).text), RU); + setScenario({}); + const noSub = "Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз."; + assert.match(localizeText("en", noSub), /^The analyst answers on the project's subscription, and it is not connected\./); + assert.doesNotMatch(localizeText("en", noSub), RU); + }); + + test("Scenario: Свободный текст не переводится", async () => { + setScenario({ chat: { reply: "Сделано три задачи из пяти.", create: [] } }); + await post("Что сделано?"); + await tick(); + const m = await last(); + assert.equal(m.text, "Сделано три задачи из пяти."); + assert.equal(web("en", m.text), "Сделано три задачи из пяти."); + assert.equal(web("kk", m.text), "Сделано три задачи из пяти."); + // Telegram for an English reader: the model's words are not rewritten either. + const tg = await lastTelegram(); + assert.equal(tg.peppa_localized, true); + assert.match(tg.text, /Analyst:\nСделано три задачи из пяти\.\n\nReply:/); + setScenario({}); + }); +}); diff --git a/packages/testkit/test/i18n.test.ts b/packages/testkit/test/i18n.test.ts index 62d6dfb3..ea32747c 100644 --- a/packages/testkit/test/i18n.test.ts +++ b/packages/testkit/test/i18n.test.ts @@ -117,6 +117,16 @@ describe("язык интерфейса", () => { assert.doesNotMatch(en, /[А-Яа-я]/, `untranslated: ${en}`); }); + test("Scenario: Свободный текст не переводится — бот не трогает уже переведённое сообщение (PEP-138)", async () => { + // Anna reads English (previous test). A role's message is queued in her language with the + // model's own Russian words inside: the bot sends it as it is and strips the private mark. + const text = "💬 Демо · Analyst:\nСделано три задачи из пяти.\n\nReply: http://peppa.test/chats/DEMO"; + await core.enqueueTelegram(db, { dedupeKey: "pep138:localized", method: "sendMessage", params: { chat_id: ANNA.chatId, text, parse_mode: "HTML", [core.LOCALIZED_PARAM]: true } }); + await waitFor("sent", async () => tg.botMessages(ANNA.chatId).some((m) => m.text.includes("Analyst"))); + assert.equal(tg.botMessages(ANNA.chatId).at(-1)!.text, text); + assert.equal(core.LOCALIZED_PARAM in tg.calls.at(-1)!.params, false, "the mark does not reach Telegram"); + }); + const check = (args: string[]) => run("node", ["scripts/i18n-check.ts", ...args], { cwd: root }).then( (x) => ({ code: 0, out: x.stdout }), diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts index 1d4e23e6..6705073a 100644 --- a/packages/testkit/test/limits.test.ts +++ b/packages/testkit/test/limits.test.ts @@ -19,6 +19,11 @@ describe("Время сброса лимита", () => { ["resets at 3:10 AM", "2026-11-13T03:10:00"], ["resets in 2h 15m", "2026-11-13T00:55:00"], ["try again at 23:30", "2026-11-12T23:30:00"], + // PEP-166: Claude Code's newer banner — the time was not read, a 30-minute probe made the + // subscription look free again while it stayed limited until the evening. + ["⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel", "2026-11-13T18:00:00"], + ["continuing automatically at 9:30 AM", "2026-11-13T09:30:00"], + ["continuing work on the task", null], ["limit reached", null], ] as const) { test(`Форматы времени сброса: «${text}»`, () => { @@ -27,6 +32,15 @@ describe("Время сброса лимита", () => { }); } + test("PEP-166: баннер лимита из истории возобновлённого разговора — не новый лимит", () => { + const old = "⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel"; + const resumed = `> продолжай\n${old}\n⏺ Продолжаю работу над задачей…`; + assert.equal(runner.freshLimitLine(resumed, 1), null, "the old account's banner was there when the generation started"); + assert.equal(runner.freshLimitLine(`${resumed}\n⏺ Usage limit reached · resets 9pm`, 1), "⏺ Usage limit reached · resets 9pm", "a new banner after it counts"); + assert.equal(runner.freshLimitLine("⏺ Работаю…", 0), null); + assert.equal(runner.freshLimitLine(old, 0), old, "a generation that started clean sees its first banner"); + }); + test("Время сброса указано", async () => { const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Продолжаю после лимита." }]] }); const sid = await p.start(); @@ -90,9 +104,9 @@ describe("Защита от зацикливания", () => { test("Предел достигнут", async () => { const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] }); const sid = await p.start(); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); await core.updateSession(db, sid, { limitResumes: runner.MAX_LIMIT_RESUMES_PER_DAY, limitResumesDay: new Date().toLocaleDateString("sv-SE") }); - await runner.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "дальше", "web"); + await runner.sendToSession(db, sid, "дальше"); await p.waitStatus(sid, "rate_limited"); const s = await sess(sid); assert.equal(s.resumeAt, null, "no more auto-resumes today"); @@ -114,6 +128,28 @@ describe("Защита от зацикливания", () => { }); }); +describe("Новая фраза Claude (PEP-166)", () => { + // Scenario: Новая фраза Claude — подписка в лимите до вечера + test("Новая фраза Claude — подписка в лимите до вечера", async () => { + const p = await project({ turns: [] }); + const sub = await core.createSubscription(db, { provider: "claude", name: "Claude — mock-asel", authKind: "oauth" }); + await core.updateSubscription(db, sub.id, { status: "active" }); + const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id, subscriptionId: sub.id })).id; + const now = at("2026-11-16T13:34:00"); + const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached · continuing automatically at 6pm", now); + const s = await sess(sid); + assert.equal(s.status, "rate_limited"); + assert.equal(s.resumeAt?.getTime(), at("2026-11-16T18:01:00").getTime(), "continues at the reset time + grace"); + assert.equal(s.limitProbeMin, null, "no 30-minute probe"); + assert.match(text ?? "", /продолжит в 18:01 сам/); + const limited = await core.getSubscription(db, sub.id); + assert.equal(limited.status, "limited"); + assert.equal(limited.limitedUntil?.getTime(), at("2026-11-16T18:00:00").getTime(), "limited until 18:00"); + assert.equal(core.isUsable(limited, at("2026-11-16T14:04:00")), false, "still limited half an hour later"); + assert.equal(core.isUsable(limited, at("2026-11-16T18:00:00")), true); + }); +}); + describe("Отключение", () => { test("Выключено", async () => { const p = await project({ turns: [] }); @@ -145,3 +181,10 @@ describe("Codex", () => { await runner.stopSession(db, sid); }); }); + +describe("PEP-171: запуск Codex без удалённого флага", () => { + test("по умолчанию — без подтверждений и песочницы, флага --full-auto нет", () => { + assert.equal(runner.CODEX_DEFAULT_MODE, "--sandbox danger-full-access --ask-for-approval never"); + assert.ok(!runner.CODEX_DEFAULT_MODE.includes("--full-auto")); + }); +}); diff --git a/packages/testkit/test/monitor.test.ts b/packages/testkit/test/monitor.test.ts index 8f72d6ed..6aea0ef0 100644 --- a/packages/testkit/test/monitor.test.ts +++ b/packages/testkit/test/monitor.test.ts @@ -2,7 +2,7 @@ // (controlled clock, mock-telegram, the real bot), `peppa status`. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdtempSync } from "node:fs"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -55,7 +55,7 @@ before(async () => { await core.setAllowedLogins(db, [ADMIN.login, OTHER.login]); }); beforeEach(async () => { - db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`); + db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key like 'monitor.port:%' or key = 'platform.admins'`); await db.delete(telegramOutbox); await core.setPlatformAdmins(db, [ADMIN.login]); await pair(ADMIN.login, ADMIN.chatId, 9001); @@ -117,6 +117,82 @@ describe("Health-эндпоинт", () => { }); }); +describe("PEP-168: веб жив по heartbeat, но порт закрыт", () => { + let open = false; + const probe = async () => open; + const checkPort = (m: number) => core.checkServices(db, { self: "watchdog", now: at(m), log, probe }); + + test("Порт закрыт несколько проверок подряд — алерт, в status «порт не отвечает», потом «снова на связи»", async () => { + open = false; + for (const m of [0, 1]) { + await beatAt("web", m); + await checkPort(m); + } + assert.deepEqual(await queued(ADMIN.chatId), [], "две проверки — ещё не отказ"); + await beatAt("web", 2); + await checkPort(2); + const msgs = await queued(ADMIN.chatId); + assert.equal(msgs.length, 1); + assert.match(msgs[0]!, /веб не отвечает: процесс жив .* порт закрыт/); + // heartbeat is fresh, yet the state says so + const s = (await core.serviceStatus(db, { now: at(2), probe })).find((x) => x.service === "web")!; + assert.equal(s.portDown, true); + assert.equal(core.describeState(s), "процесс жив, порт не отвечает"); + // the same outage is not repeated by the next checks + await beatAt("web", 3); + await checkPort(3); + assert.equal((await queued(ADMIN.chatId)).length, 1); + // the port is back + open = true; + await beatAt("web", 4); + await checkPort(4); + const after = await queued(ADMIN.chatId); + assert.equal(after.length, 2); + assert.match(after[1]!, /веб снова на связи/); + }); + + test("Устойчивый отказ порта — вачдог перезапускает веб (с пределом)", async () => { + const bin = join(mkdtempSync(join(tmpdir(), "peppa-launchctl-")), "mock-launchctl"); + const calls = join(mkdtempSync(join(tmpdir(), "peppa-launchctl-log-")), "calls.txt"); + writeFileSync(bin, `#!/bin/sh\necho "$@" >> "${calls}"\n`, { mode: 0o755 }); + process.env.PEPPA_LAUNCHCTL_BIN = bin; + process.env.PEPPA_WEB_RESTART_AFTER = "4"; + process.env.PEPPA_WEB_RESTART_MAX = "1"; + try { + open = false; + for (const m of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) { + await beatAt("web", m); + await checkPort(m); + await runner.webRestartTick(db, { now: at(m), log }); + } + const lines = readFileSync(calls, "utf8").trim().split("\n"); + assert.equal(lines.length, 1, "в час не больше одного перезапуска"); + assert.match(lines[0]!, /^kickstart -k gui\/\d+\/quest\.telecom\.peppa\.web$/); + } finally { + delete process.env.PEPPA_LAUNCHCTL_BIN; + delete process.env.PEPPA_WEB_RESTART_AFTER; + delete process.env.PEPPA_WEB_RESTART_MAX; + } + }); + + test("Порт открыт — тишина; одиночный сбой не считается", async () => { + open = true; + await beatAt("web", 0); + await checkPort(0); + open = false; + await checkPort(1); + open = true; + await checkPort(2); + open = false; + await checkPort(3); + await checkPort(4); + assert.deepEqual(await queued(ADMIN.chatId), []); + open = true; + const s = (await core.serviceStatus(db, { now: at(5), probe })).find((x) => x.service === "web")!; + assert.equal(s.portDown, undefined); + }); +}); + describe("Алерт админу о молчащем сервисе", () => { test("Бот молчит", async () => { await beatAt("bot", 0); diff --git a/packages/testkit/test/no-repeats.test.ts b/packages/testkit/test/no-repeats.test.ts index f5cec6e5..d5e4e014 100644 --- a/packages/testkit/test/no-repeats.test.ts +++ b/packages/testkit/test/no-repeats.test.ts @@ -96,10 +96,10 @@ describe("Одно состояние — одно сообщение", () => { assert.equal(inThread.length, 1); assert.equal(inThread[0]!.repeats, 8); assert.ok(inThread[0]!.updatedAt); - // Telegram: still one message, with the last text and the «Продолжай» button back. + // 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; + 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); diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 70f94d04..61e178a8 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -94,7 +94,7 @@ async function mcpAs(user: typeof owner) { describe("PM tools over MCP", () => { test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] }); const proj = await core.getProject(db, p.key); await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); diff --git a/packages/testkit/test/platform-dashboard.test.ts b/packages/testkit/test/platform-dashboard.test.ts new file mode 100644 index 00000000..afc91c5c --- /dev/null +++ b/packages/testkit/test/platform-dashboard.test.ts @@ -0,0 +1,46 @@ +// PEP-167: the superadmin's dashboard — totals, a row per user and per project, what needs attention. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { tasks } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { core, db, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; +after(teardown); + +let ownerId = 0; +let loneId = 0; +before(async () => { + const owner = await core.upsertUserFromGitea(db, { id: 167, login: "mock-dash-owner" }, { access_token: "x" }); + const lone = await core.upsertUserFromGitea(db, { id: 168, login: "mock-dash-lone" }, { access_token: "x" }); + ownerId = owner.id; + loneId = lone.id; + const p = await core.createProject(db, { slug: "mock-dash", key: "MDASH", name: "Dash", ownerId: owner.id, giteaOwner: "mock", workspacePath: "/tmp/mock-dash" }); + const a = await core.createTask(db, { projectId: p.id, title: "Готовая" }); + const b = await core.createTask(db, { projectId: p.id, title: "На приёмке" }); + await core.createTask(db, { projectId: p.id, title: "В бэклоге" }); + await db.update(tasks).set({ status: "done" }).where(eq(tasks.id, a.task.id)); + // «Принять» waits for two days. + await db.update(tasks).set({ status: "review", updatedAt: new Date(Date.now() - 48 * 3600_000) }).where(eq(tasks.id, b.task.id)); +}); + +describe("PEP-167: дашборд суперадмина", () => { + test("итоги, строка пользователя и проекта", async () => { + const d = await core.platformDashboard(db); + const p = d.projects.find((x) => x.key === "MDASH")!; + assert.deepEqual({ done: p.done, review: p.review, backlog: p.backlog, total: p.total, owner: p.ownerLogin }, { done: 1, review: 1, backlog: 1, total: 3, owner: "mock-dash-owner" }); + const u = d.users.find((x) => x.id === ownerId)!; + assert.deepEqual(u.projects, ["MDASH"]); + assert.equal(u.done, 1); + assert.ok(d.totals.total >= 3 && d.totals.users >= 2); + }); + + test("«Требует внимания»: «Принять» ждёт дольше суток; пользователь без проекта — через час", async () => { + const d = await core.platformDashboard(db); + assert.ok(d.attention.some((a) => a.kind === "review" && a.text.includes("MDASH"))); + assert.ok(!d.attention.some((a) => a.kind === "no_project" && a.who === "mock-dash-lone"), "just signed up — not yet"); + const later = await core.platformDashboard(db, new Date(Date.now() + 2 * 3600_000)); + assert.ok(later.attention.some((a) => a.kind === "no_project" && a.who === "mock-dash-lone")); + void loneId; + }); +}); diff --git a/packages/testkit/test/product-acceptance.test.ts b/packages/testkit/test/product-acceptance.test.ts index 640c06ed..d13c77cb 100644 --- a/packages/testkit/test/product-acceptance.test.ts +++ b/packages/testkit/test/product-acceptance.test.ts @@ -1,6 +1,7 @@ // PEP-112: the product works for a person, not in demo mode — the «чтобы заработало // по-настоящему» list, project secrets in deploys, the restart after a secret changes, and the // product agent that accepts each deploy (mock-intake, role "accept"). +import { stripAsIs } from "@peppa/shared/i18n"; import assert from "node:assert/strict"; import { createHmac } from "node:crypto"; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs"; @@ -76,7 +77,7 @@ describe("PEP-112: список «чтобы заработало по-наст const { added } = await core.declareNeeds(db, p.id, [{ title: "Ключ Claude API", why: "без него ответы — примеры", how: "console.anthropic.com → API keys", secret: "ANTHROPIC_API_KEY" }], { source: "agent", story: "FRT-3" }); assert.equal(added.length, 1); assert.equal((await core.openNeeds(db, p.id)).length, 1); - assert.match(await core.demoNote(db, p.id, p.key), /демо-режиме. Нужно от вас: Ключ Claude API/); + assert.match(stripAsIs(await core.demoNote(db, p.id, p.key)), /демо-режиме. Нужно от вас: Ключ Claude API/); await core.setProjectSecret(db, pm.id, p.id, "ANTHROPIC_API_KEY", "sk-ant-mock-1"); assert.equal((await core.openNeeds(db, p.id)).length, 0); assert.equal(await core.demoNote(db, p.id, p.key), ""); @@ -229,7 +230,7 @@ describe("PEP-112: смена секрета перезапускает прод const qs = await core.pendingQuestions(db, p.id); assert.equal(qs.length, 1); assert.match(qs[0]!.text, /версия для проверки перезапущена с новыми настройками/); - assert.match(qs[0]!.text, /Ещё работает в демо-режиме, нужно: Ключ почты/); + assert.match(stripAsIs(qs[0]!.text), /Ещё работает в демо-режиме, нужно: Ключ почты/); assert.ok(!qs.some((q) => q.options?.includes(runner.PROD_OPTION))); }); }); diff --git a/packages/testkit/test/product-help.test.ts b/packages/testkit/test/product-help.test.ts index d5f121c4..b113bd50 100644 --- a/packages/testkit/test/product-help.test.ts +++ b/packages/testkit/test/product-help.test.ts @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs"; import { describe, test } from "node:test"; import { HELP_LANGS, PRODUCT_HELP, type ProductHelpText } from "@peppa/core"; -const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])]; +const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.messages.title, ...t.messages.items, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])]; /** «Нельзя» column of docs/glossary.md. */ function forbidden(): string[] { diff --git a/packages/testkit/test/reviewer.test.ts b/packages/testkit/test/reviewer.test.ts index 7d9cd837..eb7a50d6 100644 --- a/packages/testkit/test/reviewer.test.ts +++ b/packages/testkit/test/reviewer.test.ts @@ -1,6 +1,7 @@ // 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"; @@ -81,6 +82,8 @@ async function reviewTask(turns: Action[][], settings?: Parameters (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); @@ -119,7 +122,7 @@ describe("Агент-ревьюер до ревью PM", () => { return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); - assert.match(q!.text, /Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть/); + 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)); @@ -127,7 +130,7 @@ describe("Агент-ревьюер до ревью PM", () => { assert.equal(calls().length, 1); const d = await core.getTaskDetails(db, await t.ref()); assert.equal(d.review?.verdict, "ok"); - assert.equal(core.reviewLabel(d.review!), "Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть"); + assert.equal(stripAsIs(core.reviewLabel(d.review!)), "Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть"); await stopAll(t); }); @@ -145,7 +148,7 @@ describe("Агент-ревьюер до ревью PM", () => { return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); - assert.match(q!.text, /лимит итераций исчерпан[\s\S]*src\/divide\.ts — замечание 2/); + 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); }); @@ -159,7 +162,7 @@ describe("Агент-ревьюер до ревью PM", () => { return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); - assert.match(q!.text, /Ревьюер не отработал: ревьюер завершился с кодом 1/); + assert.match(await cardDetails(q!), /Ревьюер не отработал: ревьюер завершился с кодом 1/); assert.equal((await core.latestReview(db, (await t.ref()).task.id))?.state, "error"); await stopAll(t); }); @@ -201,13 +204,13 @@ describe("reviewer details", () => { assert.equal(done.error, "ревьюер ответил не по формату"); // No runner: the PM gets "ready for review" directly. assert.equal((await t.ref()).task.status, "review"); - assert.match((await readyQuestions(t))[0]!.text, /Ревьюер не отработал: ревьюер ответил не по формату/); + 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", note: "🔎 Ревьюер: ок — ок" }); + 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 () => { diff --git a/packages/testkit/test/rotation.test.ts b/packages/testkit/test/rotation.test.ts index 020a0e4a..cd6bed08 100644 --- a/packages/testkit/test/rotation.test.ts +++ b/packages/testkit/test/rotation.test.ts @@ -7,6 +7,8 @@ import { events } from "@peppa/db"; import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; +// PEP-170: early switching (at the warning threshold) is off by default; this file covers it too. +process.env.PEPPA_ROTATE_EARLY = "on"; type User = Awaited>; let pm: User; @@ -166,9 +168,9 @@ describe("Предохранители", () => { const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 3600, credential: "caplimA" } }]] }); await poolFor(p.key, [a.id, b.id]); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); for (let i = 0; i < runner.maxRotationsPerHour(); i++) await core.logSessionEvent(db, await sess(sid), runner.SWITCH_EVENT, { reason: "limit" }); - await runner.answerAndDeliver(db, q.id, "дальше", "web"); + await runner.sendToSession(db, sid, "дальше"); await p.waitStatus(sid, "rate_limited"); assert.equal((await sess(sid)).rotateReason, null); assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/); diff --git a/packages/testkit/test/sandbox-hosts.test.ts b/packages/testkit/test/sandbox-hosts.test.ts index 89c307af..97e55944 100644 --- a/packages/testkit/test/sandbox-hosts.test.ts +++ b/packages/testkit/test/sandbox-hosts.test.ts @@ -142,7 +142,7 @@ describe("PEP-17: агент в контейнере", () => { const p = await project({ turns: [[{ say: "ok" }]] }); const before = runs().length; const sid = await p.start(); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); const s = await core.getSession(db, sid); assert.equal(s.container, null); assert.equal(s.host, null); @@ -193,7 +193,7 @@ describe("PEP-17: агент в контейнере", () => { await new Promise((r) => setTimeout(r, 1200)); // longer than one relay wait await runner.answerAndDeliver(db, q.id, "allow", "web"); await p.waitLog("permission allowed by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "allow"); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); // Stop hook through the relay with the transcript: tokens counted as for a local agent. assert.equal(core.usageTotals((await core.getSession(db, sid)).usage).total, 1500); assert.ok((await evs(sid, "turn_end")).length >= 1); @@ -300,7 +300,7 @@ describe("PEP-40: хосты раннеров", () => { const log = join(remoteWs, ".peppa", "mock-log.jsonl"); await waitFor("mcp from the host", async () => existsSync(log) && readFileSync(log, "utf8").includes('"tool":"report_progress","args":{"task":"')); assert.match(readFileSync(log, "utf8"), /"tool":"report_progress".*"isError":false/); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); // PEP-9 over SSH: the frame comes from the host's pane. const frame = await new Promise((resolve, reject) => { diff --git a/packages/testkit/test/service-text.test.ts b/packages/testkit/test/service-text.test.ts new file mode 100644 index 00000000..816ca019 --- /dev/null +++ b/packages/testkit/test/service-text.test.ts @@ -0,0 +1,233 @@ +// PEP-154: service text never reaches the person. Blocks like , command +// output, shell prompts, stack traces and absolute paths are cut out of messages and answers; +// an exception inside Peppa goes to the superadmins and the error tracker, not to the owner. +// Tests are named after the spec scenarios. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +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 } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { projects, questions, sessions, telegramOutbox, users } from "@peppa/db"; +import { and, eq, isNull, sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); +const { renderQuestion, renderAnswered } = await import("@peppa/bot/render"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../.."); +const bugsink = await new MockBugsink().start(); +process.env.BUGSINK_URL = bugsink.url; + +const NOTIFICATION = "\nb7f3\n/private/tmp/claude-501/tasks/b7f3.output\ncompleted\nBackground command finished\n"; +const TERMINAL_REPLY = [ + "Проверки не прошли, нужен ваш ответ.", + "", + "$ pnpm test", + "```", + "FAIL src/app.test.ts", + " ● оплата › считает сумму", + "```", + "TypeError: total is not a function", + " at sum (/Users/telecom/Dev/pay/src/app.ts:12:5)", + " at async run (node:internal/process/task_queues:95:5)", + "Файл: /Users/telecom/Dev/pay/src/app.ts", + "\x1b[31mЧто выбрать: чинить сейчас или отложить?\x1b[0m", +].join("\n"); + +let owner: Awaited>; +let admin: Awaited>; +let seq = 0; + +/** A story at work with its agent's session (no tmux: messages are raised as the hook does). */ +async function story() { + const key = `F${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: owner.id }); + const created = await core.createTask(db, { projectId: p.id, title: "Оплата картой" }); + await core.updateTask(db, await core.resolveTask(db, created.key), { status: "in_progress" }); + const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning(); + return { + project: p, + key: created.key, + taskId: created.task.id, + sessionId: s!.id, + session: () => core.getSession(db, s!.id), + ref: () => core.resolveTask(db, created.key), + asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id), + thread: async () => { + await core.syncChats(db); + return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); + }, + }; +} + +/** Runs the real peppa-hook like Claude Code does: payload on stdin. */ +function hook(event: string, payload: unknown, sessionId: number): Promise { + return new Promise((done) => { + const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: "0" }, stdio: ["pipe", "ignore", "inherit"] }); + p.on("close", (code) => { + assert.equal(code, 0); + done(); + }); + p.stdin.end(JSON.stringify(payload)); + }); +} + +const outboxTo = async (chatId: number) => + (await db.select().from(telegramOutbox).where(sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`).orderBy(telegramOutbox.id)).map((r) => String(r.params.text)); +const openOf = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt))); + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 541, login: "mock-owner" }, { access_token: "x" }); + admin = await core.upsertUserFromGitea(db, { id: 542, login: "mock-admin" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 5410, telegramUserId: 5410 }).where(eq(users.id, owner.id)); + await db.update(users).set({ telegramChatId: 5420, telegramUserId: 5420 }).where(eq(users.id, admin.id)); + await core.setPlatformAdmins(db, [admin.login]); +}); +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-154: фильтр служебного текста", () => { + test("userText: блоки, ANSI, вывод команд, приглашение оболочки, трассировка и пути убираются; адреса остаются", () => { + const out = core.userText(TERMINAL_REPLY); + assert.equal(out, "Проверки не прошли, нужен ваш ответ.\n\nЧто выбрать: чинить сейчас или отложить?"); + assert.equal(core.userText(out), out, "idempotent"); + assert.equal(core.userText(NOTIFICATION), ""); + assert.equal(core.userText("Готово. не для людей Результат: https://git.example.com/pay/pulls/7"), "Готово. Результат: https://git.example.com/pay/pulls/7"); + assert.equal(core.userText("Поправил `packages/core/src/chats.ts` и C:\\Users\\pm\\app.ts, проверил."), "Поправил и, проверил."); + // A person's own words are not rewritten: only what is certainly service text. + assert.equal(core.stripServiceBlocks("Синий, как в /Users/me/макет.png"), "Синий, как в /Users/me/макет.png"); + assert.equal(core.isServiceInput(NOTIFICATION), true); + assert.equal(core.isServiceInput("Синий"), false); + }); + + test("Реплика агента с выводом терминала и путём", async () => { + const st = await story(); + // Two automatic nudges first (the story is at work), then the reply reaches the story thread. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + const thread = await st.thread(); + const said = thread.find((m) => m.text.includes("Проверки не прошли, нужен ваш ответ.")); + assert.ok(said, "the owner sees the reply"); + assert.match(said.text, /чинить сейчас или отложить/); + for (const m of thread) for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!m.text.includes(bad), `no «${bad}» in the thread`); + // The same reply as a question to the person: stored, sent to Telegram — all without it. + const q = await core.askPm(db, await st.ref(), { kind: "question", text: TERMINAL_REPLY, sessionId: st.sessionId }); + for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!q.text.includes(bad), `no «${bad}» in the message`); + const tg = renderQuestion(q, { taskKey: st.key, taskTitle: "Оплата картой", taskStatus: "in_progress", session: await st.session(), webUrl: "http://peppa.test" }); + assert.match(tg.text, /Проверки не прошли, нужен ваш ответ\./); + assert.ok(!tg.text.includes("/Users/") && !tg.text.includes("tmux attach"), "Telegram: no path, no terminal command"); + assert.ok(renderQuestion(q, { taskKey: st.key, taskTitle: null, session: await st.session(), webUrl: "http://peppa.test", engineer: true }).text.includes("tmux attach"), "«Инженер» keeps the terminal command"); + }); + + test("Исходный текст для инженера", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Нужен ваш ответ. Файл /Users/telecom/Dev/pay/src/app.ts не открывается."); + assert.ok(!q.text.includes("/Users/")); + assert.match((await core.questionDetails(db, q.id)) ?? "", /\/Users\/telecom\/Dev\/pay\/src\/app\.ts/); + const clean = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"] }); + assert.equal(await core.questionDetails(db, clean.id), null, "nothing was cut — nothing to keep"); + // A permission request keeps its command: that is what the person allows. + const perm = await core.raiseSessionQuestion(db, await st.session(), "permission", "Разрешить Bash: rm /Users/telecom/Dev/pay/tmp.txt", ["allow", "deny"]); + assert.match(perm.text, /\/Users\/telecom/); + }); + + test("От реплики ничего не осталось", async () => { + const st = await story(); + await assert.rejects(core.askPm(db, await st.ref(), { kind: "question", text: "только служебное" }), /служебный текст/); + assert.equal((await st.asked()).length, 0); + // The end of a turn with nothing for a person leaves nothing in the story thread. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: NOTIFICATION }, st.sessionId); + assert.equal((await st.asked()).length, 0); + assert.ok(!(await st.thread()).some((m) => /task-notification|private\/tmp|Background command/.test(m.text))); + assert.equal(await core.addChatMessage(db, { chatId: (await core.ensureProjectChat(db, st.project.id)).id, kind: "event", authorKind: "agent", text: NOTIFICATION, dedupeKey: `mock:${st.key}` }), null); + }); +}); + +describe("PEP-154: ответом вопроса считается только ввод человека", () => { + test("Служебное уведомление в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: NOTIFICATION }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredAt, null, "the question stays open"); + assert.equal(after.answer, null); + const thread = await st.thread(); + assert.ok(!thread.some((m) => m.text.includes("task-notification") || (m.question?.answer ?? "").includes("task-notification")), "not in the chat: neither text nor answer"); + // Even if such a block came glued to a person's words, only the words are the answer. + const answered = await core.answerQuestion(db, q.id, `Синий\n${NOTIFICATION}`, "terminal"); + assert.equal(answered.answer, "Синий"); + assert.ok(!renderAnswered("Вопрос", answered).includes("task-notification")); + await assert.rejects(core.answerQuestion(db, (await core.askPm(db, await st.ref(), { kind: "question", text: "А размер?", sessionId: st.sessionId })).id, NOTIFICATION, "web")); + }); + + test("Человек печатает в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answer, "Синий"); + assert.equal(after.answeredVia, "terminal"); + }); + + test("Peppa сама пишет агенту", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Агент закончил ход и ждёт вашего ответа."); + const report = "Проверки PR красные: test\n$ pnpm test\nFAIL src/app.test.ts"; + await core.logSessionEvent(db, await st.session(), "input_sent", { text: report }); + await hook("prompt", { prompt: report }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredVia, "system", "closed as stale, not answered"); + assert.ok(!(after.answer ?? "").includes("FAIL")); + // A person's message that Peppa only carried to the terminal is still that person's answer. + const q2 = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await core.logSessionEvent(db, await st.session(), "input_sent", { text: "Синий", person: true }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + assert.equal((await core.getQuestion(db, q2.id)).answer, "Синий"); + }); +}); + +describe("PEP-154: ошибки платформы не идут владельцу проекта", () => { + const NO_QUIET = { quietFrom: null, quietTo: null }; + const autonomy = (now = new Date()) => runner.autonomyTick(db, { now, log: () => {} }); + + test("Диспетчер упал с исключением; та же ошибка повторяется", async () => { + // The platform project is connected to the error tracker (mock). + const platform = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = platform.key; + core.resetErrorReporting(); + const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); + await runner.connectErrorTracking(db, await core.getProject(db, platform.key), client, "http://peppa.test"); + + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + await db.update(projects).set({ ownerId: owner.id }).where(eq(projects.id, p.id)); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + // The start blows up inside Peppa: the sessions table is gone for one tick. + const now = new Date(); + const ingested = bugsink.ingested.length; + db.run(sql`ALTER TABLE runner_tasks RENAME TO runner_tasks_x`); + try { + await autonomy(now); + assert.equal((await openOf(p.id)).length, 0, "the owner gets no message"); + assert.equal((await outboxTo(5410)).length, 0, "nothing for the owner in Telegram"); + const alerts = (await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")); + assert.equal(alerts.length, 1, "the superadmin gets one message"); + assert.ok(bugsink.ingested.length > ingested, "the error tracker has the exception"); + // Ten minutes later the same error: no second message. + await autonomy(new Date(now.getTime() + 10 * 60_000)); + assert.equal((await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")).length, 1); + assert.equal((await openOf(p.id)).length, 0); + } finally { + db.run(sql`ALTER TABLE runner_tasks_x RENAME TO runner_tasks`); + } + }); + + test("Понятный отказ", async () => { + assert.equal(await core.platformFailure(db, new core.PeppaError("Подписка не выбрана — выберите её в настройках проекта."), { service: "watchdog", where: "dispatch PAY-7" }), "Подписка не выбрана — выберите её в настройках проекта."); + assert.equal(await core.platformFailure(db, new Error("SQLITE_ERROR: no such column: x"), { service: "watchdog", where: "dispatch PAY-7" }), null); + }); +}); diff --git a/packages/testkit/test/story-product.test.ts b/packages/testkit/test/story-product.test.ts index 94ff8221..f5223334 100644 --- a/packages/testkit/test/story-product.test.ts +++ b/packages/testkit/test/story-product.test.ts @@ -1,5 +1,6 @@ // PEP-120: the story page in «Продакт» mode — plain words, «шаг N из M», what is needed, // what comes next, «Принять» / «Поправить». Tests are named after the spec scenarios. +import { stripAsIs } from "@peppa/shared/i18n"; import assert from "node:assert/strict"; import { after, describe, test } from "node:test"; import type { StoryProductInput } from "@peppa/core"; @@ -75,7 +76,7 @@ describe("PEP-120: story page in «Продакт» mode", () => { assert.ok(v.now && v.next, JSON.stringify(s)); assert.doesNotMatch(text, FORBIDDEN, JSON.stringify(s)); } - assert.match(view({ status: "backlog", agentWorking: false, waitsFor: ["Оплата картой"] }).now, /«Оплата картой»/); + assert.match(stripAsIs(view({ status: "backlog", agentWorking: false, waitsFor: ["Оплата картой"] }).now), /«Оплата картой»/); }); }); diff --git a/packages/testkit/test/subscription-failover.test.ts b/packages/testkit/test/subscription-failover.test.ts index 759bb40b..12cfae7a 100644 --- a/packages/testkit/test/subscription-failover.test.ts +++ b/packages/testkit/test/subscription-failover.test.ts @@ -39,6 +39,42 @@ const outboxTexts = async (prefix: string) => .map((r) => String((JSON.parse(String((r as { params: string }).params)) as { text: string }).text)); const typeEvents = async (type: string) => (await db.select().from(events)).filter((e) => e.type === type); +describe("Простая картина подписок (PEP-170)", () => { + test("Агент на одной подписке — свободная помечена «следующая»; переключение видно в наборе", async () => { + const [a, b] = [await claudeSub("Next A", "nextA"), await claudeSub("Next B", "nextB")]; + const p = await project({ turns: [[{ work: 4000 }, { say: "Готово." }]] }); + const pool = await poolFor(p.key, [a.id, b.id]); + const sid = await p.start(); + const on = (await sess(sid)).subscriptionId; + const o = (await core.poolOverview(db, pool.id))!; + const at = o.subscriptions.find((x) => x.id === on)!; + const free = o.subscriptions.find((x) => x.id !== on)!; + assert.equal(at.activeSessions, 1); + assert.equal(at.next, false); + assert.equal(free.next, true, "the free subscription is where agents go next"); + const projectId = (await core.getProject(db, p.key)).id; + await core.logEvent(db, { projectId, sessionId: sid, type: runner.SWITCH_EVENT, payload: { fromId: at.id, fromName: at.name, toId: free.id, toName: free.name, reason: "limit" } }); + const [sw] = (await core.poolOverview(db, pool.id))!.switches; + assert.deepEqual({ from: sw!.fromName, to: sw!.toName, reason: sw!.reason, session: sw!.sessionId }, { from: at.name, to: free.name, reason: "limit", session: sid }); + await runner.stopSession(db, sid); + }); + + test("Одна подписка — «следующей» нет", async () => { + const a = await claudeSub("Solo A", "soloA"); + const p = await project({ turns: [] }); + const pool = await poolFor(p.key, [a.id]); + assert.equal((await core.poolOverview(db, pool.id))!.subscriptions.some((x) => x.next), false); + }); + + test("Заранее по порогу не переключает по умолчанию (PEPPA_ROTATE_EARLY не задан)", () => { + delete process.env.PEPPA_ROTATE_EARLY; + assert.equal(runner.earlyRotationEnabled(), false); + process.env.PEPPA_ROTATE_EARLY = "on"; + assert.equal(runner.earlyRotationEnabled(), true); + delete process.env.PEPPA_ROTATE_EARLY; + }); +}); + describe("Переезд на подписку другого провайдера", () => { test("Claude упёрся в лимит, в пуле есть ChatGPT: новый запуск Codex без resume, PM получает «переехал»", async () => { const a = await claudeSub("Cross A", "xlimA"); diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts index 28bd64eb..801a5969 100644 --- a/packages/testkit/test/subscriptions.test.ts +++ b/packages/testkit/test/subscriptions.test.ts @@ -1,6 +1,7 @@ // PEP-67: agent subscriptions (Claude Code / Codex / OpenCode), pools and the subscription a // runner starts on. Sign-in and trial runs go through the mock CLIs (mock-claude, mock-codex, // mock-opencode) with the real contracts: setup-token, device auth, --with-api-key, -p/exec/run. +import { stripAsIs } from "@peppa/shared/i18n"; import assert from "node:assert/strict"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -277,7 +278,7 @@ describe("PEP-76: владелец выбирает подписку проек assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested", "asking again changes nothing"); const asks = (await core.pendingQuestions(db, platform.id)).filter((q) => q.text.includes("просит подписку Peppa FACTORY")); assert.equal(asks.length, 1, "one request, to the superadmin (platform project → Home and Telegram)"); - assert.match(asks[0]!.text, new RegExp(`${owner.login} просит подписку Peppa FACTORY для проекта «P76» \\(MPSUB\\)`)); + assert.match(stripAsIs(asks[0]!.text), new RegExp(`${owner.login} просит подписку Peppa FACTORY для проекта «P76» \\(MPSUB\\)`)); assert.deepEqual(asks[0]!.options, [runner.SHARED_APPROVE, runner.SHARED_DENY]); assert.equal((await runner.sharedRequest(db, p.id))!.login, owner.login); @@ -384,3 +385,18 @@ describe("PEP-76: владелец выбирает подписку проек assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "and nobody is pinged about it"); }); }); + +describe("PEP-164: ещё одна подписка прямо в пул", () => { + test("суперадмин добавляет Claude в пул одной кнопкой: подписка в пуле и ждёт входа по ссылке", async () => { + const first = await claudeSub("Claude — пул ротации", "pep164a"); + const pool = await core.createPool(db, { name: "Пул ротации PEP-164", subscriptionIds: [first.id] }); + const added = await runner.addPoolSubscription(db, { poolId: pool.id, provider: "claude", createdBy: asel.id }); + assert.equal(added.status, "pending", "waits for the sign-in"); + assert.match(added.name, /^Claude 2 — Пул ротации PEP-164$/); + const members = (await core.poolSubscriptions(db, pool.id)).map((s) => s.id); + assert.deepEqual(members, [first.id, added.id], "already a member of the pool, the first one stays"); + const login = await runner.pendingLogin(db, added.id); + assert.ok(login?.url, "the sign-in link is ready"); + await runner.cancelLogin(db, added.id); + }); +}); diff --git a/packages/testkit/test/usage.test.ts b/packages/testkit/test/usage.test.ts index 2c9a4ffe..8bade025 100644 --- a/packages/testkit/test/usage.test.ts +++ b/packages/testkit/test/usage.test.ts @@ -56,7 +56,7 @@ describe("Расход сессии из statusLine и transcript", () => { const p = await project({ turns: [[{ usage: { input: 1200, output: 300, costUsd: 0.42, context: { used: 50000, size: 200000 }, fiveHour: 42, sevenDay: 18 } }, { say: "Готово." }]] }); const sid = await p.start(); await p.waitLog("statusline", (e) => e.ev === "statusline"); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); const s = await core.getSession(db, sid); const t = core.usageTotals(s.usage); assert.equal(t.total, 1500); diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index 763f7b40..e3111fb7 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -9,8 +9,9 @@ # ~/.peppa/release-queue has requests (the PM's button) # Prod runs from the release directory: ~/peppa/current/scripts/install-launchd.sh, so every # path below (and PEPPA_ROOT for hooks and git config) is ~/peppa/current, not a release. -# Pre-launch (everything is dev): PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot -# from the working copy — no release agent, so nothing replaces what this checkout serves. +# Pre-launch (PEP-165): scripts/install-launchd.sh watchdog web bot from the working copy — web in +# `start` mode (build first: `next build` in apps/web), no release agent. Never `next dev` on the live +# site: its rebuilds made every open tab reload in a loop (16.11). # Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [release] (default: all) # Remove: launchctl bootout gui/$(id -u)/