// PEP-84: «продакт» and «аналитик» refine a new story before the dispatcher takes it (mock-intake). 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 { core, db, runner, teardown } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-intake-")); const scenario = join(TMP, "scenario.json"); const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; title: string; answered: boolean; answer: string | null; hasContext: boolean; prompt: string }); const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s)); type User = Awaited>; let pm: User; let seq = 0; before(async () => { process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake"); process.env.MOCK_INTAKE_SCENARIO = scenario; setScenario({}); pm = await core.upsertUserFromGitea(db, { id: 8401, login: "mock-pm-8401" }, { access_token: "x" }); }); after(teardown); async function intakeProject() { const n = ++seq; const ws = join(TMP, `ws${n}`); mkdirSync(join(ws, ".peppa"), { recursive: true }); writeFileSync(join(ws, "AGENTS.md"), "# AGENTS.md\n\n## Соглашения\n- Интерфейс на русском\n"); writeFileSync(join(ws, ".peppa/memory.md"), "# Память проекта\n\n## Решения\n- Оплата только картой\n"); const p = await core.createProject(db, { slug: `mock-intake-${n}`, key: `MIN${String.fromCharCode(64 + n)}`, name: `Intake ${n}`, giteaOwner: "x", workspacePath: ws, ownerId: pm.id }); await core.setIntakeSettings(db, p.id, { enabled: true }); return p; } const tick = (now?: Date) => runner.intakeTick(db, { wait: true, now }); const story = async (key: string) => (await core.resolveTask(db, key)).task; describe("Продакт и аналитик", () => { test("Scenario: стори проходит продакта и аналитика; развилку аналитик решает сам, продакта не спрашивает и не ждёт (PEP-94)", async () => { const p = await intakeProject(); const done = await core.createTask(db, { projectId: p.id, title: "Каталог товаров" }); await core.setIntakeState(db, done.task.id, { stage: "done", original: { title: "", description: "" }, attempts: 0 }); const ref = await core.createTask(db, { projectId: p.id, title: "Корзина", description: "Хочу чтобы можно было складывать товары" }); assert.deepEqual([...(await core.intakePendingTasks(db, p.id)).entries()], [[ref.task.id, "new"]]); assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [done.task.id], "the dispatcher does not see a story the roles hold"); await tick(); const state = (await core.getIntakeState(db, ref.task.id))!; assert.equal(state.stage, "done", "no waiting for the PM"); const mine = calls().filter((c) => c.title === "Корзина"); assert.deepEqual(mine.map((c) => c.role), ["product", "analyst"]); assert.ok(mine.every((c) => c.hasContext), "the roles get the project's context"); assert.match(mine[0]!.prompt, /Интерфейс на русском/, "AGENTS.md"); assert.match(mine[0]!.prompt, /Оплата только картой/, "memory"); assert.match(mine[0]!.prompt, /\[backlog\] Каталог товаров/, "other stories"); assert.match(mine[0]!.prompt, /Не хвали/, "no flattery"); assert.match(mine[1]!.prompt, /Вопросов продакту не задавай/, "the analyst asks nothing"); const t = await story(ref.key); assert.match(t.description!, /## Критерии приёмки\n- Результат виден пользователю/); assert.match(t.description!, /## Исходный запрос\nКорзина\n\nХочу чтобы можно было складывать товары/, "the PM's words are kept"); const comments = await core.storyComments(db, ref.task.id); assert.deepEqual(comments.map((c) => c.role), ["product", "analyst"]); assert.equal(comments[0]!.login, "Продакт"); // A question the model still sent became its default, decided right away. assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "nothing goes to the PM"); assert.match(t.description!, /## Допущения[\s\S]*Нужна ли мобильная версия\? — Да, страница открывается с телефона/); assert.match(comments[1]!.text, /напишите в комментариях к задаче/); assert.deepEqual((await runner.readyBacklog(db, p.id)).map((x) => x.id).sort(), [done.task.id, ref.task.id].sort(), "the dispatcher may take it at once"); }); test("a story left waiting by the old flow finishes by defaults at its deadline", async () => { const p = await intakeProject(); const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" }); const q = await core.askPm(db, ref, { kind: "question", text: "старый вопрос аналитика" }); const t0 = new Date("2026-11-16T10:00:00"); await core.setIntakeState(db, ref.task.id, { stage: "waiting", original: { title: "Оплата", description: "" }, analyst: { description: "Оплата заказа", criteria: ["Можно оплатить"], outOfScope: [], assumptions: [], questions: [{ q: "Нужна ли рассрочка?", default: "Нет" }], comment: "" }, questionId: q.id, deadline: t0.getTime() + 60_000, attempts: 0, }); await tick(new Date(t0.getTime() + 2 * 60_000)); assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done"); assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the question is closed"); assert.match((await story(ref.key)).description!, /Нужна ли рассрочка\? — Нет/); }); test("Scenario: продакт делит запрос на стори и переименовывает; без вопросов стори сразу готова", async () => { const p = await intakeProject(); setScenario({ product: { goal: "Продавать онлайн", comment: "Это три задачи. Доставку откладываю.", title: "Каталог: список товаров", split: [{ title: "Тележка", description: "Сложить товары" }, { title: "Оплата картой", description: "Оплатить заказ" }] }, analyst: { questions: [] }, }); const ref = await core.createTask(db, { projectId: p.id, title: "Сделай интернет-магазин" }); await tick(); const all = await core.listTasks(db, { projectId: p.id }); assert.deepEqual(all.map((t) => t.title).sort(), ["Каталог: список товаров", "Оплата картой", "Тележка"]); assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done"); assert.match((await core.storyComments(db, ref.task.id))[0]!.text, /Разделил на задачи: эта и MIN\w-2, MIN\w-3/); // The split stories skip the product manager: the analyst takes them on the next tick. await tick(); for (const t of all) assert.equal((await core.getIntakeState(db, t.id))!.stage, "done"); assert.equal(calls().filter((c) => c.role === "product" && ["Тележка", "Оплата картой"].includes(c.title)).length, 0); assert.equal((await core.pendingQuestions(db, p.id)).length, 0); setScenario({}); }); test("роли не держат стори: сбой модели, ручной запуск, выключенное уточнение, старый бэклог", async () => { const p = await intakeProject(); setScenario({ garbage: true }); const broken = await core.createTask(db, { projectId: p.id, title: "Сломанная" }); await tick(); assert.equal((await core.getIntakeState(db, broken.task.id))!.stage, "product", "one failure — try again"); await tick(); const gaveUp = (await core.getIntakeState(db, broken.task.id))!; assert.equal(gaveUp.stage, "done"); assert.match(gaveUp.note!, /не по формату/); assert.equal((await story(broken.key)).description ?? "", "", "the story goes on as written"); assert.match((await core.storyComments(db, broken.task.id)).at(-1)!.text, /задача идёт в работу как написана/); setScenario({}); // Roles never hold a story waiting for the PM; taking it to work afterwards changes nothing. const manual = await core.createTask(db, { projectId: p.id, title: "Ручная" }); await tick(); assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "done"); await runner.releaseIntake(db, manual.task.id); assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "done"); assert.equal((await core.pendingQuestions(db, p.id)).length, 0); // Off by default; turning it on leaves the old backlog alone. const off = await core.createProject(db, { slug: "mock-intake-off", key: "MINOFF", name: "Off", giteaOwner: "x", workspacePath: join(TMP, "off"), ownerId: pm.id }); const old = await core.createTask(db, { projectId: off.id, title: "Старая" }); assert.equal((await core.getIntakeSettings(db, off.id)).enabled, false); await core.setIntakeSettings(db, off.id, { enabled: true }, new Date(Date.now() + 1000)); const n = calls().length; await tick(); assert.equal(calls().length, n); assert.equal(await core.getIntakeState(db, old.task.id), null); }); });