// PEP-198: the analyst is the only one who talks to the owner — developers' questions go through // it, finished stories nobody waits for come in one evening message, a stuck story is the // factory's business (one line to the owner). mock-intake plays the analyst (role `relay`). import assert from "node:assert/strict"; import { writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, before, describe, test } from "node:test"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { chatMessages, checkRuns, events, questions, sessions, telegramOutbox, users } from "@peppa/db"; import { and, eq, like } from "drizzle-orm"; import { stripAsIs } from "@peppa/shared/i18n"; import { core, db, project, runner, setDefaultOwner, superadmin, teardown } from "./helpers.ts"; const { createAgentServer } = await import("@peppa/mcp/agent"); const { heldForDigest } = core; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); let owner: Awaited>; before(async () => { process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake"); process.env.PEPPA_AGENT_RELAY = "on"; owner = await core.upsertUserFromGitea(db, { id: 19801, login: "mock-owner-19801" }, { access_token: "x" }); await db.update(users).set({ telegramChatId: 19801, telegramUserId: 19801 }).where(eq(users.id, owner.id)); setDefaultOwner(owner.id); }); after(teardown); async function agent(projectKey: string) { const [a, b] = InMemoryTransport.createLinkedPair(); await createAgentServer(db, { defaultKey: projectKey }).connect(a); const client = new Client({ name: "mock-agent", version: "0" }); await client.connect(b); return async (name: string, args: Record = {}) => { const r = await client.callTool({ name, arguments: args }); return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError }; }; } const ownerQuestions = (projectId: number) => db.select().from(questions).where(eq(questions.projectId, projectId)); describe("Вопрос разработчика проходит через Аналитика", () => { test("Scenario: Технический вопрос — до владельца не доходит, агент решает сам", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const call = await agent(tp.key); const r = await call("ask_pm", { task: tp.taskKey, question: "Какую базу данных взять для заказов: SQLite или Postgres?", options: ["SQLite", "Postgres"], default: "SQLite" }); assert.match(r.text, /Not sent to the owner: the analyst sees a technical question/); assert.equal((await ownerQuestions(p.id)).length, 0); // The same through the model: a question without the stack words, the analyst says «technical». writeFileSync(join(tp.dir, "relay.json"), JSON.stringify({ relay: { verdict: "technical" } })); process.env.MOCK_INTAKE_SCENARIO = join(tp.dir, "relay.json"); const r2 = await call("report_blocker", { task: tp.taskKey, what: "Какой сервис распознавания речи вам удобен?", tried: "сравнил два сервиса", product: true, options: ["Первый", "Второй"], default: "Первый" }); delete process.env.MOCK_INTAKE_SCENARIO; assert.match(r2.text, /technical question/); assert.equal((await ownerQuestions(p.id)).length, 0, "the technical choice is not put on the owner (2.3)"); }); test("Scenario: Вопрос о продукте — доходит один раз, словами Аналитика, с вариантами; три одинаковых — один", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const call = await agent(tp.key); const r = await call("ask_pm", { task: tp.taskKey, question: "Показывать ли цены гостям сайта?", options: ["Да", "Нет"], default: "Да" }); assert.match(r.text, /sent to the owner by the analyst/); const [q] = await ownerQuestions(p.id); assert.ok(q); assert.match(stripAsIs(q.text), /^Агент спрашивает: Показывать ли цены гостям сайта\?/, "the analyst's words"); assert.deepEqual(q.options, ["Да", "Нет"]); assert.equal(q.defaultOption, "Да"); assert.equal(q.msgType, "question"); // The same question by meaning, twice more, in other words: nothing new for the owner. const again = await call("ask_pm", { task: tp.taskKey, question: "Показывать ли гостям сайта цены товаров?", options: ["Да", "Нет"], default: "Да" }); assert.match(again.text, /same question \(#\d+\) is already with the owner/); const third = await call("ask_pm", { task: tp.taskKey, question: "Показывать ли цены гостям сайта?", options: ["Нет", "Да"], default: "Нет" }); assert.match(third.text, /already with the owner/); assert.equal((await ownerQuestions(p.id)).length, 1, "one question to the owner"); const decided = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "relay_decided"))); assert.deepEqual(decided.map((e) => (e.payload as { verdict: string }).verdict), ["product", "repeat", "repeat"]); }); test("Telegram: сообщение подписано Аналитиком", async () => { const { renderQuestion } = await import("@peppa/bot/render"); const tp = await project({ turns: [] }); const ref = await core.resolveTask(db, tp.taskKey); const q = await core.askPm(db, ref, { kind: "question", msgType: "question", text: "Показывать цены?", options: ["Да", "Нет"], defaultOption: "Да" }); const r = renderQuestion(q, { taskKey: tp.taskKey, taskTitle: "x", session: null, webUrl: "" }); assert.match(r.text.split("\n")[1]!, /^🔎 Аналитик · ❓ Вопрос$/); assert.doesNotMatch(r.text, /продакт|от фабрики/i); }); }); describe("Готовые задачи сводкой", () => { test("Scenario: Две задачи агента готовы днём — одно сообщение в конце дня, по одной не приходят", async () => { process.env.PEPPA_READY_DIGEST = "on"; process.env.PEPPA_TZ = "UTC"; const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const human = await core.resolveTask(db, tp.taskKey); const a = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки", origin: "acceptance" }); const b = await core.createTask(db, { projectId: p.id, title: "Пустой экран без подсказки", origin: "acceptance" }); for (const r of [human, a, b]) { await core.updateTask(db, await core.resolveTask(db, r.key), { status: "review" }); await core.sendReviewCard(db, await core.resolveTask(db, r.key), "✅ готово к ревью"); } const open = (await core.pendingQuestions(db, p.id)).filter((q) => q.taskId); assert.equal(open.length, 3, "all three wait for «Принять» on the site"); const held = new Map(); for (const q of open) held.set(q.taskId!, await heldForDigest(db, q, "review")); assert.deepEqual([held.get(human.task.id), held.get(a.task.id), held.get(b.task.id)], [false, true, true], "the owner's own story goes at once"); const day = new Date("2026-11-18T11:00:00Z"); // a Wednesday assert.equal(await runner.readyDigestTick(db, { now: day }), 0, "not before the end of the working day"); const evening = new Date("2026-11-18T19:30:00Z"); assert.equal(await runner.readyDigestTick(db, { now: evening }), 1); assert.equal(await runner.readyDigestTick(db, { now: new Date("2026-11-18T21:00:00Z") }), 0, "once a day"); const chat = await core.ensureProjectChat(db, p.id); const said = (await db.select().from(chatMessages).where(eq(chatMessages.chatId, chat.id))).map((m) => stripAsIs(m.text)).filter((t) => t.startsWith("За день готовы")); assert.equal(said.length, 1); assert.match(said[0]!, new RegExp(`За день готовы задачи: 2\\.[\\s\\S]*• ${a.key} «Подписать кнопки»\\n• ${b.key} «Пустой экран без подсказки»`)); assert.doesNotMatch(said[0]!, new RegExp(human.key)); const tg = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `chat:m%:19801`)); assert.equal(tg.filter((r) => /За день готовы/.test(stripAsIs(String(r.params.text)))).length, 1, "one Telegram message"); // A comment makes the owner wait for the story: its «готово» goes at once. await core.addStoryComment(db, await core.resolveTask(db, a.key), owner, "Жду это"); assert.equal(await heldForDigest(db, open.find((q) => q.taskId === a.task.id)!, "review"), false); // A part of a split of the owner's own story is awaited like the story itself. const part = await core.createTask(db, { projectId: p.id, title: "Часть разбивки", origin: "analyst" }); await core.markSplitPart(db, part.task.id, human.task.id); assert.equal(await core.taskAwaited(db, part.task.id), true); delete process.env.PEPPA_READY_DIGEST; }); }); // PEP-209: the stuck story is healed by the platform — stuck-heal.test.ts.