PEP-198: тесты — пересылка через Аналитика, сводка, застрявшие
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9569380143
commit
a0cda002c7
@ -109,7 +109,7 @@ export async function relayAgentQuestion(db: Db, ref: TaskRef, q: AgentQuestion,
|
||||
|
||||
const ask = (db: Db, project: Project, prompt: string) =>
|
||||
claudePrint(db, project, {
|
||||
bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
|
||||
bin: process.env.PEPPA_INTENT_BIN ?? process.env.PEPPA_INTAKE_BIN ?? "claude",
|
||||
model: process.env.PEPPA_RELAY_MODEL ?? process.env.PEPPA_INTENT_MODEL ?? "haiku",
|
||||
timeoutMs: Number(process.env.PEPPA_INTENT_TIMEOUT_MS ?? 30_000),
|
||||
who: "аналитик",
|
||||
|
||||
@ -42,6 +42,11 @@ Object.assign(process.env, {
|
||||
PEPPA_NET_WATCH: "off",
|
||||
// PEP-153: the message classifier never reaches a real CLI from a test.
|
||||
PEPPA_INTENT_BIN: join(ROOT, "packages/testkit/bin/mock-intake"),
|
||||
// PEP-198: agents' questions go straight to the owner in other suites; one-analyst.test.ts turns
|
||||
// the analyst's relay on. The evening digest and the stuck-story check — only there too.
|
||||
PEPPA_AGENT_RELAY: "off",
|
||||
PEPPA_READY_DIGEST: "off",
|
||||
PEPPA_STUCK_TASKS: "off",
|
||||
});
|
||||
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });
|
||||
|
||||
|
||||
165
packages/testkit/test/one-analyst.test.ts
Normal file
165
packages/testkit/test/one-analyst.test.ts
Normal file
@ -0,0 +1,165 @@
|
||||
// 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<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
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<string, unknown> = {}) => {
|
||||
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<number, boolean>();
|
||||
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);
|
||||
delete process.env.PEPPA_READY_DIGEST;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Застрявшая задача", () => {
|
||||
test("Scenario: Агент свободен 2 часа, проверки пройдены — суперадмину и одна строка владельцу", async () => {
|
||||
process.env.PEPPA_STUCK_TASKS = "on";
|
||||
const admin = await superadmin();
|
||||
const tp = await project({ turns: [] });
|
||||
writeFileSync(join(tp.dir, ".peppa/project.json"), JSON.stringify({ slug: tp.key.toLowerCase(), key: tp.key, name: tp.key, peppaUrl: "http://test", checks: { test: "pnpm test" } }));
|
||||
const p = await core.getProject(db, tp.key);
|
||||
const ref = await core.resolveTask(db, tp.taskKey);
|
||||
await core.updateTask(db, ref, { status: "in_progress" });
|
||||
const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id });
|
||||
const now = new Date();
|
||||
await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(now.getTime() - 2 * 3_600_000) }).where(eq(sessions.id, s.id));
|
||||
await db.insert(checkRuns).values({ projectId: p.id, taskId: ref.task.id, sha: "abc1234", check: "test", state: "success" });
|
||||
|
||||
assert.equal(await runner.stuckTaskTick(db, { now }), 1);
|
||||
assert.equal(await runner.stuckTaskTick(db, { now: new Date(now.getTime() + 600_000) }), 0, "once per episode");
|
||||
assert.equal((await admin()).filter((t) => t.includes(tp.taskKey) && /свободен 2 ч/.test(t)).length, 1, "the superadmin is told");
|
||||
const chat = await core.ensureProjectChat(db, p.id);
|
||||
const lines = (await db.select().from(chatMessages).where(eq(chatMessages.chatId, chat.id))).map((m) => stripAsIs(m.text)).filter((t) => t.includes("задерживается на нашей стороне"));
|
||||
assert.deepEqual(lines, [`Задача ${tp.taskKey} задерживается на нашей стороне. От вас ничего не нужно — мы уже разбираемся.`]);
|
||||
assert.ok(await core.taskDelayed(db, ref.task.id), "the owner sees «задержка на нашей стороне» on the story");
|
||||
|
||||
// A fresh agent (or checks not green) is not stuck.
|
||||
const tp2 = await project({ turns: [] });
|
||||
const p2 = await core.getProject(db, tp2.key);
|
||||
const ref2 = await core.resolveTask(db, tp2.taskKey);
|
||||
await core.updateTask(db, ref2, { status: "in_progress" });
|
||||
const s2 = await core.createSession(db, { projectId: p2.id, taskId: ref2.task.id });
|
||||
await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(now.getTime() - 20 * 60_000) }).where(eq(sessions.id, s2.id));
|
||||
assert.equal(await runner.stuckTaskTick(db, { now }), 0);
|
||||
await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(now.getTime() - 3 * 3_600_000) }).where(and(eq(sessions.id, s2.id)));
|
||||
assert.equal(await runner.stuckTaskTick(db, { now }), 0, "no green checks — not «stuck» but in work");
|
||||
delete process.env.PEPPA_STUCK_TASKS;
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user