peppa/packages/testkit/test/board-planner.test.ts
2026-11-15 18:11:28 +05:00

260 lines
16 KiB
TypeScript

// PEP-34 (board order = priority, archive, epic progress) and PEP-42 (story dependencies,
// dispatcher waits for predecessors, epic planner on mock-planner).
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, describe, test } from "node:test";
import { core, db, project, runner, teardown } from "./helpers.ts";
after(teardown);
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const keysOf = async (projectId: number, status?: "backlog") => (await core.listTasks(db, { projectId, statuses: status ? [status] : undefined })).map((t) => t.key);
const refOf = (key: string) => core.resolveTask(db, key);
const projectOf = async () => {
const tp = await project({ turns: [] });
return { tp, p: await core.getProject(db, tp.key) };
};
describe("board order (PEP-34)", () => {
test("new stories go to the bottom; reorder top/bottom/before/after; order survives work and back", async () => {
const { tp, p } = await projectOf();
const b = await core.createTask(db, { projectId: p.id, title: "вторая" });
const c = await core.createTask(db, { projectId: p.id, title: "третья" });
const a = tp.taskKey;
assert.deepEqual(await keysOf(p.id), [a, b.key, c.key]);
await runner.reorderBoardTask(db, await refOf(c.key), { to: "before", other: await refOf(a) });
assert.deepEqual(await keysOf(p.id), [c.key, a, b.key]);
await runner.reorderBoardTask(db, await refOf(c.key), { to: "after", other: await refOf(a) });
assert.deepEqual(await keysOf(p.id), [a, c.key, b.key]);
await runner.reorderBoardTask(db, await refOf(b.key), { to: "top" });
assert.deepEqual(await keysOf(p.id), [b.key, a, c.key]);
await runner.reorderBoardTask(db, await refOf(b.key), { to: "bottom" });
assert.deepEqual(await keysOf(p.id), [a, c.key, b.key]);
// "top" is within the column: a story in review doesn't count for the backlog.
await core.updateTask(db, await refOf(a), { status: "review" });
await runner.reorderBoardTask(db, await refOf(b.key), { to: "top" });
assert.deepEqual(await keysOf(p.id, "backlog"), [b.key, c.key]);
await core.updateTask(db, await refOf(a), { status: "backlog" });
assert.deepEqual(await keysOf(p.id), [b.key, a, c.key], "a keeps its project-wide place; b, raised in the backlog, is above it");
});
test("tiny gaps renumber the project without losing the order", async () => {
const { tp, p } = await projectOf();
const b = await core.createTask(db, { projectId: p.id, title: "b" });
const c = await core.createTask(db, { projectId: p.id, title: "c" });
// Squeeze c between a and b many times: the midpoint halves the gap every time.
for (let i = 0; i < 30; i++) {
await runner.reorderBoardTask(db, await refOf(c.key), { to: "after", other: await refOf(tp.taskKey) });
await runner.reorderBoardTask(db, await refOf(b.key), { to: "after", other: await refOf(tp.taskKey) });
}
assert.deepEqual(await keysOf(p.id), [tp.taskKey, b.key, c.key]);
const positions = (await core.listTasks(db, { projectId: p.id })).map((t) => t.position);
assert.ok(positions[1]! - positions[0]! > 1e-7, `positions stay apart: ${positions}`);
});
test("other projects are refused", async () => {
const one = await projectOf();
const two = await projectOf();
await assert.rejects(runner.reorderBoardTask(db, await refOf(one.tp.taskKey), { to: "before", other: await refOf(two.tp.taskKey) }), /разных проектов/);
});
test("archive hides a story from the board, the dispatcher and epic progress; restore puts it at the bottom", async () => {
const { tp, p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Оплата");
const s1 = await core.createTask(db, { projectId: p.id, title: "s1", goalId: epic.id });
const s2 = await core.createTask(db, { projectId: p.id, title: "s2", goalId: epic.id });
const s3 = await core.createTask(db, { projectId: p.id, title: "s3", goalId: epic.id });
await core.updateTask(db, s1, { status: "done" });
assert.deepEqual((await core.epicProgress(db, p.id)).get(epic.id), { done: 1, total: 3 });
await runner.archiveTask(db, await refOf(s3.key), true);
assert.deepEqual(await keysOf(p.id), [tp.taskKey, s1.key, s2.key]);
assert.deepEqual((await core.epicProgress(db, p.id)).get(epic.id), { done: 1, total: 2 });
assert.equal(core.progressLabel((await core.epicProgress(db, p.id)).get(epic.id)), "1/2");
assert.ok((await refOf(s3.key)).task.archivedAt, "the story page still resolves");
assert.deepEqual((await core.listTasks(db, { projectId: p.id, includeArchived: true })).length, 4);
await assert.rejects(runner.reorderBoardTask(db, await refOf(s3.key), { to: "top" }), /в архиве/);
await runner.reorderBoardTask(db, await refOf(s2.key), { to: "top" });
await runner.archiveTask(db, await refOf(s3.key), false);
assert.equal((await keysOf(p.id)).at(-1), s3.key);
});
test("archiving a story at work stops its agent and returns it to the backlog", async () => {
const tp = await project({ turns: [[{ say: "работаю" }]] });
const sid = await tp.start();
await core.updateTask(db, await refOf(tp.taskKey), { status: "in_progress" });
const r = await runner.archiveTask(db, await refOf(tp.taskKey), true);
assert.equal(r.stopped, 1);
assert.equal((await tp.task()).status, "backlog");
assert.equal((await core.getSession(db, sid)).status, "done");
});
});
describe("dependencies (PEP-42)", () => {
test("blocked until predecessors are in review/done; no self, cycles or other projects; set replaces atomically", async () => {
const { tp, p } = await projectOf();
const a = await refOf(tp.taskKey);
const b = await core.createTask(db, { projectId: p.id, title: "b" });
const c = await core.createTask(db, { projectId: p.id, title: "c" });
await core.addDependency(db, c, b);
await core.addDependency(db, b, a);
assert.deepEqual([...(await core.blockedTaskIds(db, p.id))].sort(), [b.task.id, c.task.id].sort());
assert.equal(core.blockedLabel(await core.blockersOf(db, c)), `ждёт ${b.key}`);
assert.deepEqual((await core.dependentsOf(db, a)).map((d) => d.key), [b.key]);
await assert.rejects(core.addDependency(db, a, c), /Цикл/);
await assert.rejects(core.addDependency(db, a, a), /самой себя/);
const other = await projectOf();
await assert.rejects(core.addDependency(db, a, await refOf(other.tp.taskKey)), /другого проекта/);
// setDependencies: one bad key → nothing changes.
await assert.rejects(core.setDependencies(db, a, [c.key]), /Цикл/);
assert.deepEqual(await core.blockersOf(db, a), []);
await assert.rejects(core.setDependencies(db, c, [a.key, c.key]), /самой себя/);
assert.deepEqual((await core.blockersOf(db, c)).map((x) => x.key), [b.key], "previous list restored");
assert.deepEqual((await core.setDependencies(db, c, [String(a.task.number)])).map((x) => x.key), [a.key], "bare numbers are this project's stories");
await core.updateTask(db, a, { status: "review" });
assert.deepEqual([...(await core.blockedTaskIds(db, p.id))], [], "review unblocks b and c");
const details = await core.getTaskDetails(db, await refOf(c.key));
assert.deepEqual(details.blockers.map((x) => [x.key, x.open]), [[a.key, false]]);
});
test("an archived predecessor doesn't block", async () => {
const { tp, p } = await projectOf();
const b = await core.createTask(db, { projectId: p.id, title: "b" });
await core.addDependency(db, b, await refOf(tp.taskKey));
assert.equal((await core.blockedTaskIds(db, p.id)).has(b.task.id), true);
await runner.archiveTask(db, await refOf(tp.taskKey), true);
assert.equal((await core.blockedTaskIds(db, p.id)).has(b.task.id), false);
});
test("auto dispatcher takes the top unblocked story; a raised story goes first", async () => {
const { tp, p } = await projectOf();
const second = await core.createTask(db, { projectId: p.id, title: "предшественник" });
const third = await core.createTask(db, { projectId: p.id, title: "поднятая" });
// The first story waits for the second.
await core.addDependency(db, await refOf(tp.taskKey), second);
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.key), [second.key, third.key]);
await runner.reorderBoardTask(db, third, { to: "top" });
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.key), [third.key, second.key]);
await core.setAutonomy(db, p.id, { level: "auto", quietFrom: null, quietTo: null, wipLimit: 2 });
await runner.autonomyTick(db, { now: new Date() });
const active = (await core.listSessions(db, { active: true })).filter((s) => s.projectId === p.id);
assert.deepEqual(active.map((s) => s.taskKey).sort(), [second.key, third.key].sort(), "WIP 2: the blocked first story waits");
assert.equal((await tp.task()).status, "backlog");
for (const s of active) await runner.stopSession(db, s.id);
});
});
describe("epic planner (PEP-42)", () => {
const dir = mkdtempSync(join(tmpdir(), "peppa-planner-"));
const scenario = join(dir, "scenario.json");
process.env.PEPPA_PLANNER_BIN = join(ROOT, "packages/testkit/bin/mock-planner");
process.env.MOCK_PLANNER_SCENARIO = scenario;
const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { args: string[]; epic: string; wishes: string | null; existing: string });
test("plan → draft → edit → apply: stories in the epic, plan order, dependencies", async () => {
writeFileSync(scenario, "{}");
const { tp, p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Оплата картой", "Платёжная форма и вебхуки");
await core.updateTask(db, await refOf(tp.taskKey), { goalId: epic.id });
const r = await runner.planEpic(db, p, epic.id, { wishes: "без Stripe", by: "pm" });
assert.ok(r.ok, !r.ok ? r.error : "");
assert.equal(r.draft.stories.length, 3);
assert.deepEqual(r.draft.stories.map((s) => s.dependsOn), [[], [1], [2]]);
const call = calls().at(-1)!;
assert.equal(call.epic, "Оплата картой");
assert.equal(call.wishes, "без Stripe");
assert.match(call.existing, new RegExp(tp.taskKey), "existing stories of the epic go into the prompt");
assert.ok(call.args.includes("--model") && call.args.includes("sonnet"));
assert.deepEqual((await runner.getPlanDraft(db, epic.id))?.stories.length, 3);
// The PM drops the middle story and makes the last one wait for the first and an existing story.
const edited = [r.draft.stories[0]!, { ...r.draft.stories[2]!, dependsOn: [1, tp.taskKey] }];
const created = await runner.applyPlan(db, p, epic.id, edited);
assert.equal(created.length, 2);
assert.deepEqual((await keysOf(p.id)).slice(-2), created.map((c) => c.key), "bottom of the board, plan order");
assert.ok(created.every((c) => c.task.goalId === epic.id));
assert.deepEqual((await core.blockersOf(db, created[1]!)).map((b) => b.key), [tp.taskKey, created[0]!.key]);
assert.equal(await runner.getPlanDraft(db, epic.id), null, "the draft is gone after approval");
});
test("bad plans are refused before anything is created", async () => {
const { p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Эпик");
const before = (await keysOf(p.id)).length;
const s = (title: string, dependsOn: Array<number | string> = []) => ({ title, description: "", dependsOn });
await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", [2]), s("вторая", [1])]), /цикл/);
await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", [5])]), /нет задачи №5/);
await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", ["ZZ-1"])]), /ZZ-1/);
await assert.rejects(runner.applyPlan(db, p, epic.id, []), /нет задач/);
assert.equal((await keysOf(p.id)).length, before);
});
test("prose around the JSON is fine; garbage and a failing CLI create nothing", async () => {
const { p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Отчёты");
writeFileSync(scenario, JSON.stringify({ prose: true, stories: [{ title: "Отчёт по продажам", description: "{фигурные} скобки", depends_on: [] }] }));
const ok = await runner.planEpic(db, p, epic.id, { by: "pm" });
assert.ok(ok.ok);
assert.equal(ok.draft.stories[0]!.description, "{фигурные} скобки");
writeFileSync(scenario, JSON.stringify({ garbage: true }));
const bad = await runner.planEpic(db, p, epic.id, { by: "pm" });
assert.ok(!bad.ok);
assert.match(bad.error, /не по формату/);
writeFileSync(scenario, JSON.stringify({ fail: true }));
const failed = await runner.planEpic(db, p, epic.id, { by: "pm" });
assert.ok(!failed.ok);
assert.match(failed.error, /кодом 1/);
});
test("parser: depends_on as strings, caps, empty titles", () => {
const text = JSON.stringify({ stories: [{ title: "ok story", depends_on: ["2", "pep-7"] }, { title: "" }, ...Array.from({ length: 20 }, (_, i) => ({ title: `s${i} story` }))] });
const plan = runner.parsePlannerOutput(text)!;
assert.equal(plan.length, runner.PLAN_MAX_STORIES - 1, "cut to the cap, the empty title dropped");
assert.deepEqual(plan[0]!.dependsOn, [2, "PEP-7"]);
assert.equal(runner.parsePlannerOutput("нет плана"), null);
assert.deepEqual(runner.parseDepsInput("1, pep-3 ;2"), [1, "PEP-3", 2]);
});
});
describe("command palette (PEP-52)", () => {
test("only the user's projects; archived stories left out; backlog stories can start", async () => {
const pm = await core.createLocalUser(db, { login: "mock-palette-pm", password: "mock-Passw0rd-123" });
const stranger = await core.createLocalUser(db, { login: "mock-palette-x", password: "mock-Passw0rd-123" });
const mine = await core.createProject(db, { slug: "pal", key: "PAL", name: "Платежи", giteaOwner: "test", workspacePath: mkdtempSync(join(tmpdir(), "pal-")), ownerId: pm.id });
const other = await core.createProject(db, { slug: "ops", key: "OPS", name: "Опс", giteaOwner: "test", workspacePath: mkdtempSync(join(tmpdir(), "ops-")), ownerId: stranger.id });
const form = await core.createTask(db, { projectId: mine.id, title: "Форма оплаты" });
const gone = await core.createTask(db, { projectId: mine.id, title: "Ненужная" });
await core.createTask(db, { projectId: other.id, title: "Секретная" });
await runner.archiveTask(db, gone, true);
await core.askPm(db, form, { kind: "question", text: "Какой провайдер?" });
const items = await core.paletteItems(db, pm.id);
assert.ok(items.some((i) => i.kind === "project" && i.key === "PAL"));
assert.ok(!items.some((i) => i.key.startsWith("OPS") || i.title.includes("Секретная") || i.title === "Опс"), "no foreign project");
assert.ok(!items.some((i) => i.key === gone.key), "archived story hidden");
const story = items.find((i) => i.key === form.key)!;
assert.equal(story.canStart, true);
assert.equal(story.href, `/t/${form.key}`);
const q = items.find((i) => i.kind === "question")!;
assert.match(q.href, new RegExp(`^/t/${form.key}#q-\\d+$`));
assert.ok((await core.paletteItems(db, stranger.id)).every((i) => !i.key.startsWith("PAL")));
// Ranking: exact key first, then title word starts; every word must match.
assert.equal(core.matchPalette(items, form.key.toLowerCase())[0]!.key, form.key);
assert.equal(core.matchPalette(items, "форма")[0]!.key, form.key);
assert.equal(core.matchPalette(items, "форма ненужная").length, 0);
assert.equal(core.matchPalette(items, "раннеры")[0]!.href, "/runners");
});
});