peppa/packages/testkit/test/analyst-chat.test.ts
2026-11-15 15:30:54 +05:00

139 lines
8.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-110: the analyst answers in the project's chat on the project's subscription — questions
// about the project, help with a new story, filing stories on request (mock-intake, role "chat").
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, 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 { 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-analyst-chat-"));
const scenario = join(TMP, "scenario.json");
const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; prompt: string });
const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s));
const tick = () => runner.analystChatTick(db, { wait: true });
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
let project: Awaited<ReturnType<typeof core.createProject>>;
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
const post = (text: string) => runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text, via: "web" });
const talk = async () => (await core.discussionMessages(db, chat.id)).map((m) => [m.authorKind, m.authorLogin, m.text] as const);
before(async () => {
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
process.env.MOCK_INTAKE_SCENARIO = scenario;
setScenario({});
// An allowlisted owner: the machine's login stands in for a subscription in tests.
pm = await core.upsertUserFromGitea(db, { id: 1101, login: "asel" }, { access_token: "x" });
const ws = join(TMP, "ws");
mkdirSync(join(ws, ".peppa"), { recursive: true });
writeFileSync(join(ws, "AGENTS.md"), "# AGENTS.md\n\n- Интерфейс на русском\n");
project = await core.createProject(db, { slug: "mock-achat", key: "MACH", name: "Стажировки", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
await core.createTask(db, { projectId: project.id, title: "Поиск стажировок" });
chat = await core.ensureProjectChat(db, project.id);
});
after(teardown);
describe("PEP-110: analyst in the project chat", () => {
test("a question is answered in the same chat, with the project's context and the conversation", async () => {
await post("Где я могу увидеть предложения по стажировкам?");
assert.equal(await core.analystPending(db, chat.id), true, "«печатает…» until answered");
await tick();
assert.equal(await core.analystPending(db, chat.id), false);
const t = await talk();
assert.deepEqual(t.at(-1), ["agent", "Аналитик", "Ответ на: Где я могу увидеть предложения по стажировкам?"]);
const c = calls().at(-1)!;
assert.equal(c.role, "chat");
assert.match(c.prompt, /Интерфейс на русском/, "AGENTS.md");
assert.match(c.prompt, /MACH-1 «Поиск стажировок» — в бэклоге/, "stories and their state in plain words");
assert.match(c.prompt, /Доска проекта[^\n]*http:\/\/peppa\.test\/p\/MACH/, "where to look");
assert.match(c.prompt, /asel: Где я могу увидеть предложения по стажировкам\?/, "the conversation");
assert.match(c.prompt, /никогда о технике/, "no technical questions to the PM");
});
test("answered once: another tick does not call the model again", async () => {
const n = calls().length;
await tick();
assert.equal(calls().length, n);
});
test("stories are filed only when the person asks; they skip the intake roles", async () => {
setScenario({ chat: { reply: "Предлагаю стори «Страница отзывов». Заводить?", create: [] } });
await post("Хочу страницу с отзывами клиентов");
await tick();
assert.equal((await core.listTasks(db, { projectId: project.id })).length, 1, "nothing filed without a yes");
setScenario({});
await post("Да, заведи");
await tick();
const stories = await core.listTasks(db, { projectId: project.id });
const filed = stories.find((s) => s.title === "Страница отзывов")!;
assert.ok(filed, "the story is in the backlog");
assert.match(filed.description!, /Отзывы видны на странице/);
assert.equal((await core.getIntakeState(db, filed.id))!.stage, "done", "already formulated — intake skips it");
assert.match((await talk()).at(-1)![2], /Завёл в бэклог:\n• MACH-2 «Страница отзывов»/);
assert.match(calls().at(-1)!.prompt, /Аналитик: Предлагаю стори «Страница отзывов»\. Заводить\?\nasel: Да, заведи/, "its own earlier words are in the history");
});
test("the answer reaches the person's Telegram (their own bot) — and can be muted", async () => {
db.run(sql`update users set telegram_chat_id = 9110 where id = ${pm.id}`);
await post("Что сейчас в работе?");
await tick();
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`);
const p = JSON.parse(out[0]!.params) as { chat_id: number; text: string };
assert.equal(p.chat_id, 9110);
assert.match(p.text, /Стажировки<\/b> · Аналитик:\nОтвет на: Что сейчас в работе\?/);
assert.match(p.text, /http:\/\/peppa\.test\/chats\/MACH/);
});
test("model failure or a broken answer: one honest note, no retries", async () => {
setScenario({ fail: true });
await post("Ты тут?");
await tick();
assert.match((await talk()).at(-1)![2], /Аналитик сейчас не смог ответить/);
const n = calls().length;
await tick();
assert.equal(calls().length, n, "not retried");
setScenario({ garbage: true });
await post("А теперь?");
await tick();
assert.match((await talk()).at(-1)![2], /не по форме/);
setScenario({});
});
test("no subscription: the analyst says to connect one; commands and story threads are not its business", async () => {
const stranger = await core.registerEgovUser(db, { iin: "900101300019", name: "НОВЫЙ ПРОДАКТ" });
const p2 = await core.createProject(db, { slug: "mock-achat-2", key: "MACB", name: "Без подписки", giteaOwner: "x", workspacePath: join(TMP, "ws2"), ownerId: stranger.id });
const c2 = await core.ensureProjectChat(db, p2.id);
await runner.postToChat(db, stranger, { chatId: c2.id, threadKey: null, text: "Привет", via: "web" });
await tick();
assert.match((await core.discussionMessages(db, c2.id)).at(-1)!.text, /подписке проекта, а она не подключена/);
const n = calls().length;
await post("/status");
await tick();
assert.equal(calls().length, n, "a command is not a question to the analyst");
});
test("a message that waited over an hour is not answered late", async () => {
await post("Старый вопрос");
const n = calls().length;
await runner.analystChatTick(db, { wait: true, now: new Date(Date.now() + 61 * 60_000) });
assert.equal(calls().length, n, "no model call");
assert.equal(await core.analystPending(db, chat.id), false, "and no «печатает…» forever");
});
test("PEPPA_ANALYST_CHAT=off switches the analyst off", async () => {
process.env.PEPPA_ANALYST_CHAT = "off";
const n = calls().length;
await post("Есть кто?");
await tick();
assert.equal(calls().length, n);
delete process.env.PEPPA_ANALYST_CHAT;
});
});