// 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: стори проходит продакта и аналитика; вопрос с вариантом по умолчанию; ответ PM учитывается", 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(); let state = (await core.getIntakeState(db, ref.task.id))!; assert.equal(state.stage, "waiting"); 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"); let 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, "Продакт"); const [q] = await core.pendingQuestions(db, p.id); assert.equal(q!.id, state.questionId); assert.match(q!.text, /Нужна ли мобильная версия\?\n\s+По умолчанию: Да, страница открывается с телефона/); // PEP-87: the question closes itself at the deadline, so the watchdog does not nag about it. const cfg = await runner.getWatchdogSettings(db); assert.equal(await runner.remindTick(db, { now: new Date(Date.now() + 3 * 3600_000), cfg, log: () => {} }), 0); assert.equal((await core.getQuestion(db, q!.id)).reminders, 0); // The PM answers: the analyst finishes with the answer and asks nothing more. await runner.answerAndDeliver(db, q!.id, "Мобильная не нужна, только ноутбук", "web"); assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "finalize"); await tick(); state = (await core.getIntakeState(db, ref.task.id))!; assert.equal(state.stage, "done"); const last = calls().at(-1)!; assert.equal(last.answered, true); assert.equal(last.answer, "Мобильная не нужна, только ноутбук"); assert.equal((await core.pendingQuestions(db, p.id)).length, 0); assert.deepEqual((await runner.readyBacklog(db, p.id)).map((x) => x.id).sort(), [done.task.id, ref.task.id].sort(), "now the dispatcher may take it"); t = await story(ref.key); assert.match(t.description!, /## Критерии приёмки/); }); test("Scenario: PM молчит — после срока аналитик идёт по вариантам по умолчанию и не ждёт", async () => { const p = await intakeProject(); await core.setIntakeSettings(db, p.id, { waitMin: 30 }); await core.setAutonomy(db, p.id, { quietFrom: null, quietTo: null }); const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" }); const t0 = new Date("2026-11-16T10:00:00"); await tick(t0); const waiting = (await core.getIntakeState(db, ref.task.id))!; assert.equal(waiting.stage, "waiting"); assert.equal(waiting.deadline, t0.getTime() + 30 * 60_000); await tick(new Date(t0.getTime() + 29 * 60_000)); assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "waiting", "still waiting before the deadline"); const before = calls().length; await tick(new Date(t0.getTime() + 31 * 60_000)); assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done"); assert.equal(calls().length, before, "no extra model call for the defaults"); assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the question is closed"); assert.match((await story(ref.key)).description!, /## Допущения[\s\S]*Нужна ли мобильная версия\? — Да, страница открывается с телефона \(ответа не было/); assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /Ответа не было — иду по вариантам по умолчанию/); // Night: the deadline moves to the morning of the project's quiet hours. await core.setAutonomy(db, p.id, { quietFrom: 22, quietTo: 9 }); const night = await core.createTask(db, { projectId: p.id, title: "Ночная" }); await tick(new Date("2026-11-16T23:50:00")); assert.equal(new Date((await core.getIntakeState(db, night.task.id))!.deadline!).toISOString(), new Date("2026-11-17T09:00:00").toISOString()); }); 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({}); // The PM takes the story to work while the analyst waits: the question is closed. const manual = await core.createTask(db, { projectId: p.id, title: "Ручная" }); await tick(); assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "waiting"); 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); }); });