180 lines
11 KiB
TypeScript
180 lines
11 KiB
TypeScript
// PEP-115: a comment on a backlog story nobody works on goes to the analyst — it reworks the
|
||
// description and criteria and answers in the story's discussion (mock-intake, role "refine").
|
||
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-story-refine-"));
|
||
const scenario = join(TMP, "scenario.json");
|
||
const calls = () => {
|
||
try {
|
||
return readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; title: string; prompt: string });
|
||
} catch {
|
||
return [];
|
||
}
|
||
};
|
||
const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s));
|
||
const tick = (now?: Date) => runner.storyRefineTick(db, { wait: true, now });
|
||
const story = async (key: string) => (await core.resolveTask(db, key)).task;
|
||
const notes = async (taskId: number) => (await core.storyComments(db, taskId)).filter((c) => c.role === "analyst").map((c) => c.text);
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let pm: User;
|
||
let project: Awaited<ReturnType<typeof core.createProject>>;
|
||
const FORMULATED = "Покупатель складывает товары в корзину.\n\n## Критерии приёмки\n- Товар можно добавить в корзину\n\n## Исходный запрос\nКорзина\n\nХочу складывать товары";
|
||
|
||
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: 1151, 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-refine", key: "SHOP", name: "Магазин", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
|
||
});
|
||
after(teardown);
|
||
|
||
describe("PEP-115: комментарий к стори в бэклоге уточняет постановку", () => {
|
||
test("Scenario: Комментарий меняет постановку", async () => {
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Корзина", description: FORMULATED });
|
||
await core.addStoryComment(db, ref, pm, "Старое пожелание: показывать сумму");
|
||
await core.setRefineCursor(db, ref.task.id, (await core.storyComments(db, ref.task.id)).at(-1)!.id);
|
||
await core.addStoryComment(db, ref, pm, "Ещё нужна кнопка «Очистить корзину»");
|
||
await tick();
|
||
|
||
const t = await story(ref.key);
|
||
assert.match(t.description!, /## Критерии приёмки\n[\s\S]*- Учтено: Ещё нужна кнопка «Очистить корзину»/);
|
||
assert.match(t.description!, /## Исходный запрос\nКорзина\n\nХочу складывать товары$/, "the PM's own words stay");
|
||
assert.equal(t.description!.split("## Исходный запрос").length, 2, "one original request section");
|
||
const said = await notes(ref.task.id);
|
||
assert.equal(said.length, 1);
|
||
assert.match(said[0]!, /Добавил критерий: Ещё нужна кнопка «Очистить корзину»/);
|
||
assert.match(said[0]!, /Критерии приёмки теперь:\n• Результат виден пользователю/);
|
||
|
||
const c = calls().at(-1)!;
|
||
assert.equal(c.role, "refine");
|
||
assert.match(c.prompt, /Текущая постановка:\nПокупатель складывает товары в корзину/);
|
||
assert.match(c.prompt, /Интерфейс на русском/, "the project's context");
|
||
assert.match(c.prompt, /## Обсуждение стори раньше\nasel: Старое пожелание: показывать сумму/);
|
||
assert.match(c.prompt, /## Новые комментарии продакта\nasel: Ещё нужна кнопка «Очистить корзину»\n/);
|
||
|
||
// Answered once: another tick does not call the model again.
|
||
const n = calls().length;
|
||
await tick();
|
||
assert.equal(calls().length, n);
|
||
assert.equal((await notes(ref.task.id)).length, 1);
|
||
});
|
||
|
||
test("Scenario: Пока аналитик не ответил", async () => {
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Поиск" });
|
||
assert.equal(await core.refinePending(db, ref.task), false);
|
||
assert.ok((await runner.readyBacklog(db, project.id)).some((t) => t.id === ref.task.id));
|
||
await core.addStoryComment(db, ref, pm, "Нужна кнопка «Очистить»");
|
||
assert.equal(await core.refinePending(db, ref.task), true, "«Аналитик уточняет постановку…»");
|
||
assert.ok(!(await runner.readyBacklog(db, project.id)).some((t) => t.id === ref.task.id), "the dispatcher waits for the analyst");
|
||
await tick();
|
||
assert.equal(await core.refinePending(db, ref.task), false);
|
||
assert.ok((await runner.readyBacklog(db, project.id)).some((t) => t.id === ref.task.id));
|
||
// A story without a formulated description: what was written becomes the original request.
|
||
assert.match((await story(ref.key)).description!, /## Исходный запрос\nПоиск$/);
|
||
});
|
||
|
||
test("Scenario: Стори в работе", async () => {
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Оплата", description: "Оплата картой" });
|
||
await core.updateTask(db, ref, { status: "in_progress" });
|
||
const n = calls().length;
|
||
await core.addStoryComment(db, ref, pm, "Кнопку сделать зелёной");
|
||
assert.equal(await core.refinePending(db, await story(ref.key)), false);
|
||
await tick();
|
||
assert.equal(calls().length, n, "the analyst is not called");
|
||
assert.equal((await story(ref.key)).description, "Оплата картой");
|
||
assert.deepEqual(await notes(ref.task.id), []);
|
||
const details = await core.getTaskDetails(db, await core.resolveTask(db, ref.key));
|
||
assert.deepEqual(details.comments.map((c) => c.text), ["Кнопку сделать зелёной"], "the agent reads it in get_task");
|
||
});
|
||
|
||
test("Scenario: Стори взяли в работу, пока аналитик думал", async () => {
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Доставка", description: "Доставка курьером" });
|
||
await core.addStoryComment(db, ref, pm, "Добавить самовывоз");
|
||
setScenario({ slowMs: 1500 });
|
||
const n = calls().length;
|
||
const running = tick();
|
||
while (calls().length === n) await new Promise((r) => setTimeout(r, 50));
|
||
await core.updateTask(db, ref, { status: "in_progress" });
|
||
await running;
|
||
setScenario({});
|
||
assert.equal((await story(ref.key)).description, "Доставка курьером");
|
||
assert.deepEqual(await notes(ref.task.id), []);
|
||
const details = await core.getTaskDetails(db, await core.resolveTask(db, ref.key));
|
||
assert.deepEqual(details.comments.map((c) => c.text), ["Добавить самовывоз"]);
|
||
});
|
||
|
||
test("Scenario: Аналитик не смог ответить", async () => {
|
||
for (const broken of [{ fail: true }, { garbage: true }]) {
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Отзывы", description: "Отзывы покупателей" });
|
||
setScenario(broken);
|
||
await core.addStoryComment(db, ref, pm, "Нужна кнопка «Очистить»");
|
||
await tick();
|
||
const n = calls().length;
|
||
await tick();
|
||
setScenario({});
|
||
assert.equal(calls().length, n, "no retries for the same comment");
|
||
assert.equal((await story(ref.key)).description, "Отзывы покупателей");
|
||
const said = await notes(ref.task.id);
|
||
assert.equal(said.length, 1);
|
||
assert.match(said[0]!, /Не смог уточнить постановку[\s\S]*комментарий увидит агент/);
|
||
}
|
||
});
|
||
|
||
test("Scenario: Старый комментарий; выключатель PEPPA_STORY_REFINE=off", async () => {
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Акции", description: "Страница акций" });
|
||
await core.addStoryComment(db, ref, pm, "Добавить таймер");
|
||
const n = calls().length;
|
||
const later = new Date(Date.now() + 2 * 3600_000);
|
||
assert.equal(await core.refinePending(db, ref.task, later), false);
|
||
await tick(later);
|
||
assert.equal(calls().length, n);
|
||
assert.equal((await story(ref.key)).description, "Страница акций");
|
||
|
||
process.env.PEPPA_STORY_REFINE = "off";
|
||
await tick();
|
||
assert.equal(await core.refinePending(db, ref.task), false);
|
||
delete process.env.PEPPA_STORY_REFINE;
|
||
assert.equal(calls().length, n);
|
||
});
|
||
|
||
test("роли PEP-84 ещё формулируют стори — уточнение ждёт их", async () => {
|
||
await core.setIntakeSettings(db, project.id, { enabled: true }, new Date(Date.now() - 1000));
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Избранное" });
|
||
await core.addStoryComment(db, ref, pm, "И делиться списком");
|
||
const n = calls().length;
|
||
await tick();
|
||
assert.equal(calls().length, n, "held while the roles work");
|
||
await runner.intakeTick(db, { wait: true });
|
||
await tick();
|
||
assert.equal(calls().at(-1)!.role, "refine");
|
||
assert.match((await story(ref.key)).description!, /Учтено: И делиться списком[\s\S]*## Исходный запрос\nИзбранное$/);
|
||
await core.setIntakeSettings(db, project.id, { enabled: false });
|
||
});
|
||
|
||
test("Scenario Outline: Подпись по состоянию стори; ответ в треде стори", async () => {
|
||
const { commentHint } = await import("../../../apps/web/lib/comment-hint.ts");
|
||
assert.equal(commentHint("in_progress", true), "Агент работает — увидит комментарий сразу.");
|
||
assert.equal(commentHint("backlog", false), "Агент ещё не начал — аналитик уточнит постановку и ответит здесь.");
|
||
assert.equal(commentHint("in_progress", false), "Агент сейчас не работает — увидит комментарий, когда вернётся к задаче.");
|
||
|
||
const ref = await core.createTask(db, { projectId: project.id, title: "Купоны" });
|
||
const chat = await core.ensureProjectChat(db, project.id);
|
||
const r = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: `task:${ref.task.id}`, text: "Купон на первую покупку", via: "web" });
|
||
assert.match(JSON.stringify(r), /аналитик уточнит постановку/);
|
||
});
|
||
});
|