// 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); }); });