// PEP-156: who speaks. What the factory or an agent did is signed «FORGE», an agent's own // words — with its nickname (chat, the card of the question, Telegram), the AI roles — «Аналитик» // and «Продакт-агент»; a person's login stands only under their own words; the roles say «вы». // Tests are named after the spec scenarios (openspec/specs/project-chats). import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; 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, setDefaultOwner, teardown, waitFor } from "./helpers.ts"; import { MockTelegram } from "../src/mock-telegram.ts"; import { agents, chatMessages, sessions, 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"); process.env.PEPPA_SECRET = "mock-secret-for-tests"; const MOCK_INTAKE = join(dirname(fileURLToPath(import.meta.url)), "../bin/mock-intake"); const tg = await new MockTelegram().start(); const PM = { id: 951, chatId: 951, username: "pm" }; let bot: Bot; let pm: Awaited>; let seq = 0; const asPm = (fn: () => T) => core.runAsActor({ kind: "user", userId: pm.id, channel: "web" }, fn); /** A story with (optionally) a runner whose agent has this nickname — no tmux. */ async function story(nickname?: string) { const key = `W${String.fromCharCode(65 + seq++)}`; const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id }); const created = await core.createTask(db, { projectId: p.id, title: "Кнопка оплаты" }); const ref = () => core.resolveTask(db, created.key); const runnerOf = async (name: string) => { const [a] = await db.insert(agents).values({ name: `${name} ${key}` }).returning(); const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}-${a!.id}`, status: "running", agentId: a!.id }).returning(); return { id: s!.id, name: a!.name }; }; const live = nickname ? await runnerOf(nickname) : null; return { project: p, taskId: created.task.id, ref, runnerOf, agent: live?.name ?? null, session: () => core.getSession(db, live!.id), thread: async () => { await core.syncChats(db); return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); }, }; } before(async () => { pm = await core.upsertUserFromGitea(db, { id: 95, login: "mock-pm" }, { access_token: "x" }); await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id)); 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 }); await bot.start(); }); after(async () => { await bot?.stop(); await tg.stop(); setDefaultOwner(null); await teardown(); }); describe("Кто говорит в переписке", () => { test("Пользователь берёт задачу в работу", async () => { const tp = await project({ turns: [[{ say: "работаю" }]] }); const ref = await core.resolveTask(db, tp.taskKey); const { started } = await asPm(() => runner.moveTask(db, ref, "in_progress")); assert.ok(started, "the agent started"); const nickname = (await core.getSession(db, started)).agentName; assert.ok(nickname, "the runner has a nickname"); await core.syncChats(db); const chat = await core.ensureProjectChat(db, ref.project.id); const msgs = await core.chatMessagesView(db, chat.id, { threadKey: `task:${ref.task.id}` }); const took = msgs.filter((m) => /взял задачу в работу/.test(m.text)); assert.equal(took.length, 1, "one line about taking the story"); assert.equal(took[0]!.text, `▶️ Агент ${nickname} взял задачу в работу`); assert.equal(took[0]!.authorKind, "system", "signed «FORGE»"); assert.equal(took[0]!.authorLogin, null); assert.equal(took[0]!.authorUserId, null); assert.ok(!msgs.some((m) => m.kind === "event" && (m.authorKind === "user" || m.authorLogin === pm.login)), "no event is signed with the user's login"); assert.ok(!msgs.some((m) => /начал работу/.test(m.text)), "«взял задачу» is said once, not followed by «начал работу»"); // The journal keeps the real author. const journal = await core.listJournal(db, { taskId: ref.task.id }); const moved = journal.find((j) => j.type === "task_updated"); assert.equal(moved?.actorKind, "user"); assert.equal(moved?.actorLogin, pm.login); await runner.stopSession(db, started); }); test("Агент ещё не запустился", async () => { const t = await story(); await asPm(async () => core.updateTask(db, await t.ref(), { status: "in_progress" })); assert.ok(!(await t.thread()).some((m) => /взял задачу/.test(m.text)), "nobody took the story yet"); // The agent starts: now it is said, with the nickname, by the factory. const s = await t.runnerOf("Шустрик"); await core.logEvent(db, { projectId: t.project.id, taskId: t.taskId, sessionId: s.id, type: "started" }); let msgs = await t.thread(); assert.deepEqual(msgs.filter((m) => m.kind === "event").map((m) => [m.text, m.authorKind, m.authorLogin]), [[`▶️ Агент ${s.name} взял задачу в работу`, "system", null]]); // A later start of the same agent is «начал работу». await core.logEvent(db, { projectId: t.project.id, taskId: t.taskId, sessionId: s.id, type: "started" }); msgs = await t.thread(); assert.equal(msgs.at(-1)!.text, `▶️ Агент ${s.name} начал работу`); assert.equal(msgs.at(-1)!.authorKind, "system"); }); test("Сообщение агента подписано кличкой", async () => { const t = await story("Шустрик"); const q = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Зелёный", "Синий"], sessionId: (await t.session()).id }); const turn = await core.raiseSessionQuestion(db, await t.session(), "attention", "Сделал кнопку, жду ваш ответ про цвет.", undefined, false, { topic: "turn" }); await core.logEvent(db, { projectId: t.project.id, taskId: t.taskId, sessionId: (await t.session()).id, type: "progress", payload: { text: "Кнопка на странице, осталась оплата" } }); const msgs = await t.thread(); for (const m of msgs) { assert.equal(m.authorKind, "agent", m.text); assert.equal(m.authorLogin, t.agent, m.text); } assert.equal(msgs.length, 3); // The card of the question («Ждут вашего ответа») shows the same author. assert.deepEqual(await core.questionAuthor(db, q), { kind: "agent", name: t.agent }); assert.deepEqual(await core.questionAuthor(db, turn), { kind: "agent", name: t.agent }); // Telegram: «🤖 Шустрик: …». const sent = await waitFor("the question in Telegram", async () => tg.botMessages(PM.chatId).find((m) => String(m.text).includes("Какой цвет кнопки?"))); assert.ok(String(sent.text).includes(`🤖 ${t.agent}: Какой цвет кнопки?`), String(sent.text)); const said = await waitFor("the agent's words in Telegram", async () => tg.botMessages(PM.chatId).find((m) => String(m.text).includes("жду ваш ответ про цвет"))); assert.ok(String(said.text).includes(`🤖 ${t.agent}: Сделал кнопку`), String(said.text)); }); test("Сообщение фабрики не подписано агентом", async () => { const t = await story("Беркут"); const q = await core.raiseSessionQuestion(db, await t.session(), "attention", "Задача готова — посмотрите результат и примите."); const [m] = await t.thread(); assert.equal(m!.authorKind, "system"); assert.equal(m!.authorLogin, null); assert.deepEqual(await core.questionAuthor(db, q), { kind: "system" }); const sent = await waitFor("the factory's message in Telegram", async () => tg.botMessages(PM.chatId).find((x) => String(x.text).includes("посмотрите результат и примите"))); assert.ok(!String(sent.text).includes("🤖"), String(sent.text)); }); test("Собственные слова пользователя", async () => { const t = await story(); await asPm(async () => core.addStoryComment(db, await t.ref(), pm, "Сделайте кнопку зелёной")); const [m] = await t.thread(); assert.equal(m!.kind, "user"); assert.equal(m!.authorKind, "user"); assert.equal(m!.authorLogin, pm.login); assert.equal(m!.text, "Сделайте кнопку зелёной"); }); test("Старые сообщения", async () => { const t = await story("Пиксель"); const chat = await core.ensureProjectChat(db, t.project.id); // As the projection wrote it before PEP-156: the factory's line under the user's login. const old = await core.addChatMessage(db, { chatId: chat.id, threadKey: `task:${t.taskId}`, taskId: t.taskId, kind: "event", authorKind: "user", authorUserId: pm.id, authorLogin: pm.login, text: "▶️ Агент взял задачу в работу", dedupeKey: `event:old-${t.taskId}` }); await core.logEvent(db, { projectId: t.project.id, taskId: t.taskId, sessionId: (await t.session()).id, type: "progress", payload: { text: "Иду дальше" } }); await t.thread(); const [row] = await db.select().from(chatMessages).where(eq(chatMessages.id, old!.id)); assert.equal(row!.authorKind, "user"); assert.equal(row!.authorLogin, pm.login); assert.equal(row!.text, "▶️ Агент взял задачу в работу"); }); test("Роли подписаны «Аналитик» и «Агент приёмки»", async () => { const t = await story(); await core.addIntakeNote(db, { id: t.taskId, projectId: t.project.id }, "acceptance", "Цель: принять оплату картой."); await core.addIntakeNote(db, { id: t.taskId, projectId: t.project.id }, "analyst", "Критерии приёмки готовы."); const msgs = await t.thread(); assert.deepEqual(msgs.map((m) => [m.authorKind, m.authorLogin, stripAsIs(m.text)]), [ ["agent", "Агент приёмки", "Цель: принять оплату картой."], ["agent", "Аналитик", "Критерии приёмки готовы."], ]); assert.ok(core.isRoleName("Аналитик") && core.isRoleName("Агент приёмки") && core.isRoleName("Продакт")); assert.ok(!core.isRoleName("Шустрик")); // In the story's discussion the role is named the same way. const comments = await core.storyComments(db, t.taskId); assert.deepEqual(comments.map((c) => c.login), ["Агент приёмки", "Аналитик"]); // Telegram group mirror and the like sign a role as an agent: «🤖 Аналитик». assert.equal(core.agentSignature("Аналитик"), "🤖 Аналитик"); }); }); /** One answer of mock-intake to a prompt: the texts a person would read. */ async function mockAnswer(prompt: string, scenario?: object): Promise { const env = { ...process.env } as Record; delete env.MOCK_INTAKE_SCENARIO; if (scenario) { const file = join(mkdtempSync(join(tmpdir(), "mock-who-speaks-")), "scenario.json"); writeFileSync(file, JSON.stringify(scenario)); env.MOCK_INTAKE_SCENARIO = file; } const out = await new Promise((resolve, reject) => { const child = execFile(MOCK_INTAKE, ["-p", "--output-format", "json"], { env: env as NodeJS.ProcessEnv }, (err, stdout) => (err ? reject(err) : resolve(stdout))); child.stdin!.end(prompt); }); const texts: string[] = []; const walk = (v: unknown): void => { if (typeof v === "string") texts.push(v); else if (Array.isArray(v)) v.forEach(walk); else if (v && typeof v === "object") Object.values(v).forEach(walk); }; walk(JSON.parse((JSON.parse(out) as { result: string }).result)); return texts; } describe("Роли обращаются на «вы»", () => { const storyText = { title: "Кнопка оплаты", description: "Хочу, чтобы клиент платил картой" }; const prompts = (): Record => ({ intake: core.intakePrompt("Проект: PAY", storyText), refine: core.refinePrompt("Проект: PAY", storyText, [], [{ id: 1, login: "anna", text: "Добавьте оплату по счёту" }]), chat: core.analystChatPrompt("Проект: PAY", [{ who: "anna", text: "Что сейчас в работе?" }]), accept: core.productReviewPrompt({ projectName: "PAY", envLabel: "версия для проверки", url: "https://pay.test", stories: [], pages: [{ path: "/", text: "Оплата" }], screenshots: [], needs: [], secretNames: [], openStories: [] }), }); test("Ответ на «вы»", async () => { for (const [role, prompt] of Object.entries(prompts())) { assert.ok(prompt.includes(core.ADDRESS_RULE), `the ${role} prompt demands «вы»`); for (const text of await mockAnswer(prompt)) assert.equal(core.informalAddress(text), null, `${role}: ${text}`); } assert.equal(core.informalAddress("Сейчас в работе PAY-7. Посмотрите её на доске."), null); // Not an address: other words with the same letters, and someone else's words in quotes. assert.equal(core.informalAddress("Обработаны тысячи заказов за сутки, твёрдо и чисты."), null); assert.equal(core.informalAddress("В комментарии было «а ты где?» — учёл его в критериях."), null); }); test("Ответ на «ты»", async () => { assert.equal(core.informalAddress("Посмотри доску, там твоя задача"), "твоя"); assert.equal(core.informalAddress("Ты можешь открыть доску"), "Ты"); assert.equal(core.informalAddress("Напишу тебе, когда будет готово."), "тебе"); // A mock answer that says «ты» does not pass. const rude = await mockAnswer(prompts().chat!, { chat: { reply: "Сейчас в работе PAY-7. Глянь на доске, там твоя задача.", create: [] } }); assert.deepEqual(rude.map((t) => core.informalAddress(t)).filter(Boolean), ["твоя"]); const rudeProduct = await mockAnswer(prompts().intake!, { intake: { goal: "Принять оплату", comment: "Ты просишь слишком много, режу до оплаты картой.", title: "Оплата картой", split: [] } }); assert.deepEqual(rudeProduct.map((t) => core.informalAddress(t)).filter(Boolean), ["Ты"]); }); });