peppa/packages/testkit/test/intake.test.ts
2026-11-17 21:17:44 +05:00

244 lines
19 KiB
TypeScript
Raw 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-84 / PEP-198: the analyst formulates 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<ReturnType<typeof core.upsertUserFromGitea>>;
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("PEP-198: один Аналитик на входе задачи", () => {
test("Scenario: Новая задача — один вызов модели, критерии, решения на виду, владельцу ничего не задаётся", async () => {
const p = await intakeProject();
const done = await core.createTask(db, { projectId: p.id, title: "Каталог товаров", description: "Список товаров с фото и ценой" });
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 analyst holds");
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), ["intake"], "exactly one model call on intake");
assert.ok(mine[0]!.hasContext, "the analyst gets 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 with what they are about (6.1)");
assert.match(mine[0]!.prompt, /Не хвали/, "no flattery");
assert.match(mine[0]!.prompt, /Вопросов владельцу не задавай/, "the analyst asks nothing");
assert.doesNotMatch(mine[0]!.prompt, /продакт-менеджер/i);
const t = await story(ref.key);
assert.match(t.description!, /## Критерии приёмки\n- Результат виден пользователю/);
assert.match(t.description!, /## Допущения\n- Страница открывается с телефона/, "«Допущения» from the decisions");
assert.match(t.description!, /## Исходный запрос\nКорзина\n\nХочу чтобы можно было складывать товары/, "the PM's words are kept");
const decisions = await core.getDecisions(db, ref.task.id);
assert.deepEqual(decisions.map((d) => [d.text, d.status]), [["Страница открывается с телефона", "default"]]);
const comments = await core.storyComments(db, ref.task.id);
assert.deepEqual(comments.map((c) => [c.role, c.login]), [["analyst", "Аналитик"]], "one voice");
assert.match(comments[0]!.text, new RegExp(`^Задача ${ref.key} готова к работе\\. Фабрика решила за вас 1 пунктов — проверьте\\.`));
assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "nothing goes to the PM");
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 (5.4)");
});
test("Scenario: Задача на старой стадии — product, finalize и waiting доводятся без потерь", async () => {
const p = await intakeProject();
// «product»: the old first role never ran — one call finishes it.
const a = await core.createTask(db, { projectId: p.id, title: "Старая корзина" });
await core.setIntakeState(db, a.task.id, { stage: "product", original: { title: "Старая корзина", description: "складывать товары" }, attempts: 0 });
// «analyst» after the old product role: its goal goes into the prompt.
const b = await core.createTask(db, { projectId: p.id, title: "Тележка" });
await core.setIntakeState(db, b.task.id, { stage: "analyst", original: { title: "Тележка", description: "" }, product: { goal: "Покупатель копит товары", comment: "Доставку откладываю", title: "Тележка", split: [] }, attempts: 0 });
// «finalize»: the PM answered the old questions — the answer is kept.
const c = await core.createTask(db, { projectId: p.id, title: "Оплата" });
await core.setIntakeState(db, c.task.id, { stage: "finalize", original: { title: "Оплата", description: "" }, analyst: { description: "Оплата заказа", criteria: ["Можно оплатить"], outOfScope: [], assumptions: [], questions: [{ q: "Рассрочка?", default: "Нет" }], comment: "" }, answer: "Рассрочка нужна", attempts: 0 });
// «waiting»: goes by its defaults at the deadline, no model call.
const d = await core.createTask(db, { projectId: p.id, title: "Доставка" });
const q = await core.askPm(db, d, { kind: "question", text: "старый вопрос аналитика" });
const t0 = new Date("2026-11-16T10:00:00");
await core.setIntakeState(db, d.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));
for (const r of [a, b, c, d]) assert.equal((await core.getIntakeState(db, r.task.id))!.stage, "done", r.key);
assert.match((await story(a.key)).description!, /## Исходный запрос\nСтарая корзина\n\nскладывать товары/);
const byTitle = (t: string) => calls().filter((x) => x.title === t);
assert.equal(byTitle("Старая корзина").length, 1);
assert.match(byTitle("Тележка")[0]!.prompt, /Цель: Покупатель копит товары/);
assert.match(byTitle("Оплата")[0]!.prompt, /Владелец ответил на прежние вопросы:\nРассрочка нужна/);
assert.equal(byTitle("Доставка").length, 0);
assert.match((await story(d.key)).description!, /Самовывоз\? — Нет/);
assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the old question is closed");
});
test("Scenario: Разбивка на три части — в бэклоге с пометкой и зависимостью, ждут приёмки первой; «Не делить» возвращает их", async () => {
const p = await intakeProject();
setScenario({ intake: { title: "Каталог: список товаров", deferred: ["Доставка"], split: [{ title: "Тележка покупателя", description: "Сложить товары" }, { title: "Оплата заказа картой", description: "Оплатить заказ" }], decisions: ["Цены в тенге"] } });
const ref = await core.createTask(db, { projectId: p.id, title: "Сделай интернет-магазин" });
await tick();
setScenario({});
const all = await core.listTasks(db, { projectId: p.id });
assert.deepEqual(all.map((t) => t.title).sort(), ["Каталог: список товаров", "Оплата заказа картой", "Тележка покупателя"]);
const parts = all.filter((t) => t.id !== ref.task.id);
for (const t of parts) {
assert.match(t.description!, new RegExp(`Из разбивки ${ref.key}`));
assert.equal(t.origin, "analyst");
assert.equal((await core.getIntakeState(db, t.id))!.stage, "done", "a part does not go through intake again");
assert.deepEqual((await core.blockersOf(db, await core.resolveTask(db, t.key))).map((b) => b.key), [ref.key]);
}
const note = (await core.storyComments(db, ref.task.id))[0]!.text;
assert.match(note, /Фабрика решила за вас 2 пунктов/);
assert.match(note, new RegExp(`Разделила на 3 задач: ${ref.key}, ${parts.map((t) => t.key).join(", ")}`));
assert.equal(calls().filter((c) => c.role === "intake" && ["Тележка покупателя", "Оплата заказа картой"].includes(c.title)).length, 0);
// The dispatcher takes the first one only; review is not enough, accepted is.
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [ref.task.id]);
await core.updateTask(db, ref, { status: "review" });
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [], "the first one is in review — parts still wait");
await core.updateTask(db, await core.resolveTask(db, ref.key), { status: "backlog" });
// «Не делить»: the parts go to the archive and come back into the first story.
const split = (await core.getDecisions(db, ref.task.id)).find((d) => d.kind === "split")!;
assert.equal(split.status, "default");
assert.equal(await runner.undoSplit(db, await core.resolveTask(db, ref.key), split.id, pm), "unsplit");
for (const t of parts) assert.ok((await core.resolveTask(db, t.key)).task.archivedAt, `${t.key} archived`);
const desc = (await story(ref.key)).description!;
assert.match(desc, /## Тоже входит в задачу\n- Тележка покупателя: Сложить товары\n- Оплата заказа картой: Оплатить заказ\n- Доставка/);
assert.equal((await core.getDecisions(db, ref.task.id)).find((d) => d.kind === "split")!.status, "changed");
});
test("Scenario: Повтор существующей задачи в разбивке не заводится", async () => {
const p = await intakeProject();
await core.createTask(db, { projectId: p.id, title: "Страница отзывов", origin: "human" }).then((r) => core.setIntakeState(db, r.task.id, { stage: "done", original: { title: "", description: "" }, attempts: 0 }));
setScenario({ intake: { split: [{ title: "Страница отзывов", description: "Отзывы клиентов" }] } });
const ref = await core.createTask(db, { projectId: p.id, title: "Отзывы и рейтинг" });
await tick();
setScenario({});
assert.equal((await core.listTasks(db, { projectId: p.id })).filter((t) => t.title === "Страница отзывов").length, 1);
assert.match((await core.storyComments(db, ref.task.id))[0]!.text, /Не завела повторно — такие задачи уже есть:\n• «Страница отзывов» — MIN\w-1/);
assert.equal((await core.getDecisions(db, ref.task.id)).filter((d) => d.kind === "split").length, 0);
});
test("Scenario: Две неудачи модели — задача идёт как написана, владельцу одно сообщение с причиной", 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, "analyst", "one failure — try again");
assert.equal((await core.storyComments(db, broken.task.id)).length, 0, "nothing said after the first failure");
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");
const said = await core.storyComments(db, broken.task.id);
assert.equal(said.length, 1, "one message");
assert.equal(said[0]!.text, "Аналитик не смог разобрать задачу: ответ разбора пришёл не по форме. Задача идёт в работу как написана.");
await tick();
assert.equal((await core.storyComments(db, broken.task.id)).length, 1, "not repeated");
setScenario({});
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");
// 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);
});
});
describe("PEP-198: решения на виду — «Подходит» и «Нужно иначе»", () => {
async function decided(status: "backlog" | "in_progress" | "review") {
const p = await intakeProject();
setScenario({ intake: { decisions: ["Оплата картой"] } });
const ref = await core.createTask(db, { projectId: p.id, title: `Оплата ${status}` });
await tick();
setScenario({});
if (status !== "backlog") await core.updateTask(db, await core.resolveTask(db, ref.key), { status });
const d = (await core.getDecisions(db, ref.task.id))[0]!;
return { p, ref: await core.resolveTask(db, ref.key), d };
}
test("Scenario: «Подходит» — только статус, ничего не запускается", async () => {
const { p, ref, d } = await decided("backlog");
const before = { desc: (await story(ref.key)).description, comments: (await core.storyComments(db, ref.task.id)).length };
assert.equal(await runner.confirmTaskDecision(db, ref, d.id, pm), "confirmed");
const after = (await core.getDecisions(db, ref.task.id))[0]!;
assert.equal(after.status, "confirmed");
assert.equal(after.by, pm.login);
assert.equal((await story(ref.key)).description, before.desc);
assert.equal((await core.storyComments(db, ref.task.id)).length, before.comments, "no comment, no refine");
assert.equal((await core.pendingRefinements(db, { projectId: p.id })).size, 0);
assert.equal((await core.listSessions(db, { active: true, taskId: ref.task.id })).length, 0);
});
test("Scenario: «Нужно иначе» в бэклоге — Аналитик пересобирает постановку", async () => {
const { p, ref, d } = await decided("backlog");
assert.equal(await runner.changeTaskDecision(db, ref, d.id, "Только наличные", pm), "refine");
const after = (await core.getDecisions(db, ref.task.id))[0]!;
assert.deepEqual([after.status, after.text, after.was], ["changed", "Только наличные", "Оплата картой"]);
assert.match((await story(ref.key)).description!, /## Допущения\n- Только наличные \(решение владельца; было: Оплата картой\)/);
assert.ok((await core.pendingRefinements(db, { projectId: p.id })).has(ref.task.id), "the analyst's refine picks it up");
assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /было — Оплата картой, нужно — Только наличные/);
});
test("Scenario: «Нужно иначе» в работе — агент получает «было — …, нужно — …»", async () => {
const { ref, d } = await decided("in_progress");
assert.equal(await runner.changeTaskDecision(db, ref, d.id, "Только наличные", pm), "agent");
assert.equal((await core.getDecisions(db, ref.task.id))[0]!.status, "changed");
assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /было — Оплата картой, нужно — Только наличные/, "the agent reads it in get_task");
assert.equal((await core.resolveTask(db, ref.key)).task.status, "in_progress");
});
test("Scenario: «Нужно иначе» на ревью — как «Поправить»", async () => {
const { ref, d } = await decided("review");
const q = await core.askPm(db, ref, { kind: "attention", text: "✅ готово к ревью" });
assert.equal(await runner.changeTaskDecision(db, ref, d.id, "Только наличные", pm), "fix");
const now = await core.resolveTask(db, ref.key);
assert.equal(now.task.status, "in_progress");
assert.ok((await core.getQuestion(db, q.id)).answeredAt);
const [live] = await core.listSessions(db, { active: true, taskId: now.task.id });
if (live) await runner.stopSession(db, live.id);
});
});