peppa/packages/testkit/test/proposals-only.test.ts

182 lines
12 KiB
TypeScript
Raw Permalink 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-295: one rule for every story not from a person — it is created in «Предложено» and goes to
// work only after «Делать» of the owner or a member; the only exception is the owner's explicit
// choice per project; the limit of 5 a day is shared by every path. Paths covered here: the
// developing agent (MCP), the acceptance agent (a breakage too), errors of the product, the split of
// the analyst, the system story about the link; the reviewer and the feedback agent file nothing —
// reviewer.test.ts / feedback.test.ts; the policies of errors end to end — incidents.test.ts.
import assert from "node:assert/strict";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, describe, test } from "node:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { events, tasks } from "@peppa/db";
import { and, eq } from "drizzle-orm";
import { core, db, project, runner, teardown } from "./helpers.ts";
// No model for the repeat check: a failing call means «not a repeat».
process.env.PEPPA_INTAKE_BIN = "/nonexistent/mock-intake";
const { createAgentServer } = await import("@peppa/mcp/agent");
after(teardown);
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
async function agent(projectKey: string) {
const [a, b] = InMemoryTransport.createLinkedPair();
await createAgentServer(db, { defaultKey: projectKey }).connect(a);
const client = new Client({ name: "mock-agent", version: "0" });
await client.connect(b);
return async (name: string, args: Record<string, unknown> = {}) => {
const r = await client.callTool({ name, arguments: args });
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
};
}
async function fresh() {
const tp = await project({ turns: [] });
const p = await core.getProject(db, tp.key);
// «Сам берёт»: the dispatcher would take anything ready — the rule must hold anyway.
await core.setAutonomy(db, p.id, { pick: "auto" });
return { tp, p };
}
const byTitle = async (projectId: number, title: string) => (await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.title, title))))[0]!;
const ready = async (projectId: number) => (await runner.readyBacklog(db, projectId)).map((t) => t.id);
describe("PEP-295: задача не от человека — только через «Предложено»", () => {
test("Scenario Outline: каждое происхождение не от человека создаётся в «Предложено»; задача человека — нет", async () => {
const { p } = await fresh();
for (const origin of ["agent", "acceptance", "incident", "analyst"] as const) {
// Even when a caller asks for the backlog, the rule wins.
const ref = await core.createTask(db, { projectId: p.id, title: `от ${origin}`, origin, proposed: false });
assert.equal(ref.task.proposed, true, `${origin}: «Предложено»`);
assert.ok(!(await ready(p.id)).includes(ref.task.id), `${origin}: the dispatcher does not see it`);
}
const mine = await core.createTask(db, { projectId: p.id, title: "от человека" });
assert.equal(mine.task.proposed, false);
});
test("Scenario: решение человека — задача сразу в бэклоге и не тратит предел", async () => {
const { p } = await fresh();
const ref = await core.createTask(db, { projectId: p.id, title: "Ошибка: решил человек", origin: "incident", severity: "breakage", decidedByPerson: true });
assert.equal(ref.task.proposed, false);
});
test("Scenario: исключение владельца — только для своего происхождения и только в своём проекте", async () => {
const { p } = await fresh();
const { p: other } = await fresh();
assert.deepEqual(await core.getDirectOrigins(db, p.id), [], "no exceptions by default");
await core.setDirectOrigins(db, p.id, ["incident"]);
assert.equal((await core.createTask(db, { projectId: p.id, title: "ошибка напрямую", origin: "incident", severity: "breakage" })).task.proposed, false);
assert.equal((await core.createTask(db, { projectId: p.id, title: "находка приёмки", origin: "acceptance", severity: "breakage" })).task.proposed, true, "other origins still wait");
assert.equal((await core.createTask(db, { projectId: other.id, title: "ошибка в другом проекте", origin: "incident" })).task.proposed, true, "other projects still wait");
await assert.rejects(core.setDirectOrigins(db, p.id, ["human"]), /Неизвестное происхождение/);
await core.setDirectOrigins(db, p.id, []);
assert.equal((await core.createTask(db, { projectId: p.id, title: "ошибка снова ждёт", origin: "incident" })).task.proposed, true);
const log = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "direct_origins_changed")));
assert.equal(log.length, 2, "the owner's choice is in the journal");
});
test("Scenario: агент разработки через MCP — в «Предложено»", async () => {
const { tp, p } = await fresh();
const call = await agent(tp.key);
assert.equal((await call("create_task", { title: "Экспорт в CSV" })).isError, false);
const t = await byTitle(p.id, "Экспорт в CSV");
assert.deepEqual([t.origin, t.proposed], ["agent", true]);
assert.ok(!(await ready(p.id)).includes(t.id));
});
test("Scenario: поломка от агента приёмки — в «Предложено» с пометкой, «Делать» отдаёт её в бэклог", async () => {
const { p } = await fresh();
const filed = await runner.fileStories(db, p, [{ title: "Кнопка оплаты не работает", description: "Оплата падает.", severity: "breakage" }], { envLabel: "staging", url: "", ignoreFinish: true });
const t = await byTitle(p.id, "Кнопка оплаты не работает");
assert.deepEqual([t.origin, t.severity, t.proposed, t.status], ["acceptance", "breakage", true, "backlog"]);
assert.equal(filed.created[0]!.proposed, true);
assert.ok(!(await ready(p.id)).includes(t.id));
const buttons = runner.proposalButtons(filed.created, "ru").flat().map((b) => b.callback_data);
assert.ok(buttons.includes(`p:${t.id}:do`), "the owner gets «Делать» for a breakage too");
await core.approveProposal(db, t.id);
assert.ok((await ready(p.id)).includes(t.id));
});
test("Scenario: системная задача о ссылке — в «Предложено»; без места в пределе не заводится", async () => {
const { p } = await fresh();
const done = await core.createTask(db, { projectId: p.id, title: "Каталог" });
await core.updateTask(db, done, { status: "done" });
// The limit is used up: the system story waits for the next tick.
for (let i = 0; i < 5; i++) await core.createTask(db, { projectId: p.id, title: `предложение ${i}`, origin: "agent" });
assert.equal(await runner.ensureProductLinkTask(db, p), null);
// A day later there is room again.
const key = await runner.ensureProductLinkTask(db, p, { now: new Date(Date.now() + 86_400_000 + 1000) });
assert.ok(key);
const t = (await core.resolveTask(db, key)).task;
assert.equal(t.title, core.PRODUCT_LINK_TITLE);
assert.equal(t.proposed, true);
assert.ok(!(await ready(p.id)).includes(t.id));
});
test("Scenario: части разбивки — в «Предложено»; «Подходит» у разбивки отдаёт их в бэклог", async () => {
const { tp, p } = await fresh();
const main = await core.resolveTask(db, tp.taskKey);
const part = await core.createTask(db, { projectId: p.id, title: "Часть 2", origin: "analyst" });
await core.markSplitPart(db, part.task.id, main.task.id);
assert.equal(part.task.proposed, true);
const [d] = await core.setDecisions(db, main.task.id, [], { text: "Разделила на 2 задачи", parts: [part.task.id], deferred: [] });
assert.equal(d!.kind, "split");
await runner.confirmTaskDecision(db, main, d!.id, { login: "mock-pm" });
assert.equal((await core.resolveTask(db, part.key)).task.proposed, false, "«Подходит» is the owner's «Делать»");
});
test("Scenario: предел 5 в сутки — общий для всех путей", async () => {
const { tp, p } = await fresh();
await core.createTask(db, { projectId: p.id, title: "ошибка", origin: "incident" });
await core.createTask(db, { projectId: p.id, title: "часть", origin: "analyst" });
await core.createTask(db, { projectId: p.id, title: "находка", origin: "acceptance" });
await core.createTask(db, { projectId: p.id, title: "ссылка", origin: "acceptance", severity: "breakage" });
await core.createTask(db, { projectId: p.id, title: "задача человека" });
assert.deepEqual(await core.proposalRoom(db, p.id), { room: 1, limit: 5, used: 4 });
const call = await agent(tp.key);
assert.equal((await call("create_task", { title: "пятая" })).isError, false);
const sixth = await call("create_task", { title: "шестая" });
assert.equal(sixth.isError, true, "the developing agent is refused when other paths used the limit");
});
test("Каждый вызов createTask в коде — известный путь (новый путь создания задачи не обойдёт правило незаметно)", () => {
// Path → how the rule holds there. A new call site fails this test until it is classified here.
const KNOWN: Record<string, string> = {
"packages/core/src/feedback.ts": "human — решение суперадмина по обращению",
"packages/core/src/incidents.ts": "incident — «Предложено», кроме решения человека и исключения владельца",
"packages/mcp/src/manager.ts": "human — человек через свой ИИ-клиент",
"packages/mcp/src/agent.ts": "agent — «Предложено»",
"packages/cli/src/index.ts": "human — администратор",
"packages/runner/src/product-link.ts": "acceptance — «Предложено»",
"packages/runner/src/product-review.ts": "acceptance — «Предложено»",
"packages/runner/src/intake.ts": "analyst — «Предложено»",
"packages/runner/src/message-intent.ts": "human — кнопка «Создать» в чате",
"packages/runner/src/runners.ts": "human — «Оформить стори» из свободного раннера",
"packages/runner/src/planner.ts": "human — план эпика применяет человек",
"packages/runner/src/gitea-events.ts": "human — issue владельца или участника",
"apps/web/app/(app)/actions.ts": "human — «+ Задача»",
"apps/bot/src/bot.ts": "human — сообщение в Telegram",
};
const found = new Set<string>();
const walk = (dir: string) => {
for (const name of readdirSync(dir)) {
if (name === "node_modules" || name === ".next" || name === "test") continue;
const path = join(dir, name);
if (statSync(path).isDirectory()) walk(path);
else if (/\.tsx?$/.test(name) && /\bcreateTask\(db,/.test(readFileSync(path, "utf8"))) found.add(relative(ROOT, path));
}
};
for (const dir of ["packages/core/src", "packages/runner/src", "packages/mcp/src", "packages/cli/src", "apps/web", "apps/bot/src"]) walk(join(ROOT, dir));
assert.deepEqual([...found].sort(), Object.keys(KNOWN).sort());
// Paths not from a person pass their origin: the rule in createTask sees them.
for (const [file, why] of Object.entries(KNOWN)) {
if (why.startsWith("human")) continue;
const origin = why.split(" ")[0];
assert.match(readFileSync(join(ROOT, file), "utf8"), new RegExp(`createTask\\(db,[^;]*origin: "${origin}"`, "s"), `${file} passes origin ${origin}`);
}
});
});