// PEP-112: the product works for a person, not in demo mode — the «чтобы заработало // по-настоящему» list, project secrets in deploys, the restart after a secret changes, and the // product agent that accepts each deploy (mock-intake, role "accept"). import { stripAsIs } from "@peppa/shared/i18n"; import assert from "node:assert/strict"; import { createHmac } from "node:crypto"; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; 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 { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { releases } from "@peppa/db"; import { core, db, runner, teardown } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; process.env.PEPPA_WEB_URL = "http://peppa.test"; const { createAgentServer } = await import("@peppa/mcp/agent"); const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-acceptance-")); const scenario = join(TMP, "scenario.json"); const calls = () => (existsSync(`${scenario}.log.jsonl`) ? readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; prompt: string; argv: string[]; files?: string[] }) : []); const accepts = () => calls().filter((c) => c.role === "accept"); const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s)); const DEMO_PAGE = `
Демо-режим: показаны вымышленные примеры (ключ Claude API не подключён)
О сервисеlogo`; const REAL_PAGE = `О сервисе: подбираем стажировки
"); res.writeHead(req.url === "/" ? 200 : 404, { "content-type": "text/html" }).end(page); }); await new PromiseДемо-режим[^<]*<\/p>/, ""); await healthy(p, "prod", "abc1234", { previousSha: "abc1234" }); assert.ok(await core.pendingProductReview(db, p.id), "a restart with new secrets is worth another look"); await tick(); const talk = await chatOf(p.id); assert.equal(talk.length, 2); assert.match(talk[1]!.text, /Агент приёмки посмотрел рабочую версию/); assert.ok(!/Пока не настоящее/.test(talk[1]!.text)); assert.equal((await core.openNeeds(db, p.id)).length, 0, "the product agent's item is gone with the demo notice"); assert.equal((await core.listTasks(db, { projectId: p.id })).length, storiesBefore, "the «токен» story is not filed twice"); }); test("Scenario: Роли выключены", async () => { page = REAL_PAGE; const p = await proj({ intake: false }); const before = accepts().length; await healthy(p, "staging", "abc1234"); await tick(); assert.equal(accepts().length, before); assert.equal((await chatOf(p.id)).length, 0); assert.equal(await core.pendingProductReview(db, p.id), null); }); test("Scenario: Продукт не открылся — ни сообщения, ни стори; вторая неудача снимает приёмку", async () => { const p = await proj(); up = false; try { await healthy(p, "staging", "abc1234"); await tick(); assert.equal((await core.pendingProductReview(db, p.id))?.attempts, 1); await tick(); assert.equal(await core.pendingProductReview(db, p.id), null); } finally { up = true; } assert.equal((await chatOf(p.id)).length, 0); assert.equal((await core.listTasks(db, { projectId: p.id })).length, 0); }); test("an answer that is not the JSON asked for: retried once, then dropped without a message", async () => { page = REAL_PAGE; const p = await proj(); setScenario({ garbage: true }); try { await healthy(p, "staging", "abc1234"); await tick(); await tick(); } finally { setScenario({}); } assert.equal(await core.pendingProductReview(db, p.id), null); assert.equal((await chatOf(p.id)).length, 0); }); test("a preview stand is not accepted, and neither is FORGE itself", async () => { const p = await proj(); await runner.recordRelease(db, await core.getProject(db, p.key), { env: "preview", sha: "abc1234", status: "healthy", host: "pr.mock.test", prNumber: 4 }); assert.equal(await core.pendingProductReview(db, p.id), null); }); test("screenshots of the stories' stands go to the model as files it may read", async () => { page = REAL_PAGE; const p = await proj(); const project = await core.getProject(db, p.key); const story = await core.createTask(db, { projectId: p.id, title: "Каталог" }); await core.updateTask(db, story, { prUrl: `http://gitea.test/${project.giteaOwner}/${project.giteaRepo}/pulls/7` }); await runner.recordRelease(db, project, { env: "preview", sha: "pr00007", status: "healthy", host: "pr7.mock.test", prNumber: 7 }); const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; assert.equal((await runner.recordScreenshots(db, project, { sha: "pr00007", prNumber: 7, shots: [{ path: "/", png }] })).saved, 1); await healthy(p, "staging", "def5678", { commits: [`Merge pull request '${story.key}' (#7) from task/${story.key} into main`] }); await tick(); const call = accepts().at(-1)!; assert.deepEqual(call.files, ["screenshot-1.png"]); assert.match(call.prompt, /Прочитай файлы инструментом Read: screenshot-1\.png/); assert.ok(call.argv.join(" ").includes("--allowedTools Read")); assert.equal((await chatOf(p.id)).length, 1); }); }); describe("PEP-112: страница глазами пользователя", () => { test("pageText keeps what a person reads: text, field labels, buttons; pageLinks — same-site pages only", () => { assert.equal(core.pageText('
'), "Цена — 5₽\n[поле: Почта] [картинка: Логотип]");
assert.deepEqual(core.pageLinks('ДЦEAcЦt'), ["/pricing"]);
});
test("parseProductReview: missing parts are empty, too many stories are cut, no summary — no review", () => {
const r = core.parseProductReview('Вот: {"summary":"Работает","stories":[{"title":"А111"},{"title":"Б222"},{"title":"В333"},{"title":"Г444"},{"title":"Д555"},{"title":"Е666"},{"title":"Ж777"}]}')!;
assert.deepEqual([r.howto, r.notReal, r.needs], [[], [], []]);
assert.equal(r.stories.length, core.PRODUCT_REVIEW_MAX_STORIES);
assert.equal(core.parseProductReview('{"howto":["x"]}'), null);
assert.equal(core.parseProductReview("Не могу помочь"), null);
});
});
// ── PEP-197: the factory does not set tasks for itself in a circle ───────────────────────────
const found = (...stories: Array<{ title: string; description?: string; severity?: string }>) =>
setScenario({ accept: { summary: "Продукт открывается.", howto: [], not_real: [], needs: [], stories: stories.map((x) => ({ description: "Что должен увидеть пользователь.", ...x })) } });
let sha = 0;
const pass = async (p: { id: number; key: string }) => {
await healthy(p, "staging", `sha${++sha}00000`);
await tick();
};
/** The owner has asked for something that is still open: the version is not finished. */
const asked = (projectId: number) => core.createTask(db, { projectId, title: "Просьба владельца" });
const byTitle = async (projectId: number, title: string) => (await core.listTasks(db, { projectId, includeArchived: true })).find((t) => t.title === title);
describe("PEP-197: приёмка предлагает, а не запускает", () => {
test("Scenario: Агент приёмки находит улучшение — задача в «Предложено», диспетчер её не берёт; поломка — в бэклоге с пометкой", async () => {
page = REAL_PAGE;
const p = await proj();
await asked(p.id);
found({ title: "Подписать кнопку «Подобрать»", severity: "important" }, { title: "Страница не открывается без токена", severity: "breakage" });
await pass(p);
const idea = (await byTitle(p.id, "Подписать кнопку «Подобрать»"))!;
assert.deepEqual([idea.origin, idea.proposed, idea.severity, idea.status], ["acceptance", true, "important", "backlog"]);
const broken = (await byTitle(p.id, "Страница не открывается без токена"))!;
assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", false, "breakage", "backlog"], "a breakage goes to the backlog at once, marked");
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [broken.id], "the dispatcher sees the breakage only");
});
test("Scenario: Повтор открытой задачи не создаётся — к ней дописано замечание; похожая сделанная — в «Предложено» с пометкой", async () => {
page = REAL_PAGE;
const p = await proj();
await asked(p.id);
const open = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки на главном экране" });
const done = await core.createTask(db, { projectId: p.id, title: "Добавить кнопку назад на рецепт" });
await core.updateTask(db, done, { status: "done" });
found({ title: "Подписать кнопки на экране", severity: "important" }, { title: "Кнопка назад на рецепт", severity: "minor" });
const before = (await core.listTasks(db, { projectId: p.id })).length;
await pass(p);
assert.equal(await byTitle(p.id, "Подписать кнопки на экране"), undefined, "a repeat of an open story is not created");
assert.match((await core.storyComments(db, open.task.id)).map((c) => c.text).join("\n"), /Приёмка снова заметила то же самое: «Подписать кнопки на экране»/);
const similar = (await byTitle(p.id, "Кнопка назад на рецепт"))!;
assert.equal(similar.proposed, true);
assert.match(similar.description ?? "", new RegExp(`Похоже на ${done.key}, сделано \\d{4}-\\d{2}-\\d{2}`));
assert.equal((await core.listTasks(db, { projectId: p.id })).length, before + 1);
const log = await db.select().from((await import("@peppa/db")).events).where((await import("drizzle-orm")).eq((await import("@peppa/db")).events.type, "task_dedup"));
assert.ok(log.some((e) => (e.payload as { decision?: string }).decision === "remark" && e.projectId === p.id), "the decision is in the journal");
assert.ok(log.some((e) => (e.payload as { decision?: string }).decision === "similar_done" && e.projectId === p.id));
});
test("Scenario: После прохода — одно сообщение; «Делать» и «Не надо» работают; отклонённое больше не предлагается", async () => {
page = REAL_PAGE;
const p = await proj();
await asked(p.id);
found({ title: "Убрать слово «ID» с экрана", severity: "important" }, { title: "Выровнять отступы в шапке", severity: "minor" }, { title: "Починить вход", severity: "breakage" });
await pass(p);
const talk = await chatOf(p.id);
assert.equal(talk.length, 1, "one message instead of a stream");
assert.match(talk[0]!.text, /Нашёл улучшений: 3 \(важных: 2\)\./);
assert.match(talk[0]!.text, /«Починить вход» — Поломка/);
const msg = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id))[0]!;
const offer = (await core.chatOffers(db, [msg.id])).get(msg.id)!;
assert.equal(offer.kind, "proposals");
assert.deepEqual(offer.items!.map((i) => [i.title, i.open]), [["Починить вход", false], ["Убрать слово «ID» с экрана", true], ["Выровнять отступы в шапке", true]]);
const idea = (await byTitle(p.id, "Убрать слово «ID» с экрана"))!;
const minor = (await byTitle(p.id, "Выровнять отступы в шапке"))!;
await runner.decideProposals(db, pm, [idea.id], "do");
assert.equal((await byTitle(p.id, idea.title))!.proposed, false, "«Делать» moves it to the backlog");
await runner.decideProposals(db, pm, [minor.id], "no");
const rejected = (await byTitle(p.id, minor.title))!;
assert.ok(rejected.archivedAt, "«Не надо» archives it");
await assert.rejects(runner.decideProposals(db, pm, [minor.id], "do"), /уже принято/);
const after = (await core.chatOffers(db, [msg.id])).get(msg.id)!;
assert.deepEqual(after.items!.map((i) => i.decision), ["approved", "approved", "rejected"]);
found({ title: "Выровнять отступы в шапке", severity: "minor" });
const count = (await core.listTasks(db, { projectId: p.id, includeArchived: true })).length;
await pass(p);
assert.equal((await core.listTasks(db, { projectId: p.id, includeArchived: true })).length, count, "declined — not suggested again");
});
test("«Делать важные» и «Отклонить всё»; предел предложений за проход", async () => {
page = REAL_PAGE;
const p = await proj();
await asked(p.id);
await core.setAgentLimits(db, p.id, { perPass: 2 });
found({ title: "Первое замечание по экрану", severity: "minor" }, { title: "Второе замечание по входу", severity: "important" }, { title: "Третье замечание по оплате", severity: "important" });
await pass(p);
const made = (await core.listTasks(db, { projectId: p.id })).filter((t) => t.origin === "acceptance");
assert.equal(made.length, 2, "not more than the limit per pass (the most important first)");
assert.deepEqual(made.map((t) => t.severity).sort(), ["important", "important"]);
await core.setAgentLimits(db, p.id, "reset");
assert.equal((await core.getAgentLimits(db, p.id)).perPass, 5);
await runner.decideProposals(db, pm, made.map((t) => t.id), "none");
assert.equal((await core.proposedTasks(db, p.id)).length, 0);
});
});
describe("PEP-197: версия с финишем", () => {
test("Scenario: Задачи человека приняты, поломок нет — «Версия готова»; дальше только поломки, улучшения копятся на неделю", async () => {
page = REAL_PAGE;
const p = await proj();
const mine = await core.createTask(db, { projectId: p.id, title: "Подбор стажировок" });
found();
await pass(p);
assert.ok(!(await chatOf(p.id)).some((m) => /Версия готова/.test(m.text)), "a story of a person is still open");
assert.equal((await core.getVersion(db, p.id))?.doneAt, null);
await core.updateTask(db, mine, { status: "done" });
found({ title: "Шапка плохо выглядит на телефоне", severity: "important" });
await pass(p);
const talk = await chatOf(p.id);
assert.ok(talk.some((m) => /Версия готова\. Продукт: https:\/\/staging\.mock\.test/.test(m.text) && /Что умеет: Продукт открывается\./.test(m.text)), "«Версия готова» with the link and what it can do");
assert.equal((await core.projectProduct(db, p.id)).versionDone, true, "the card «Ваш продукт» says «Готово»");
assert.equal((await byTitle(p.id, "Шапка плохо выглядит на телефоне"))!.title.length > 0, true);
});
test("после финиша агент приёмки заводит только поломки; улучшения — одним сообщением раз в неделю", async () => {
page = REAL_PAGE;
const p = await proj();
found();
await pass(p); // nothing open from a person: the version is finished at once
assert.ok((await core.getVersion(db, p.id))?.doneAt);
found({ title: "Подсказка под полем поиска", severity: "important" }, { title: "Сайт упал после входа", severity: "breakage" });
await pass(p);
assert.equal(await byTitle(p.id, "Подсказка под полем поиска"), undefined, "an improvement is only kept");
assert.equal((await byTitle(p.id, "Сайт упал после входа"))!.severity, "breakage");
assert.equal((await core.getDigest(db, p.id)).items.length, 1);
const week = new Date(Date.now() + 8 * 86_400_000);
await runner.productDigestTick(db, new Date());
assert.equal(await byTitle(p.id, "Подсказка под полем поиска"), undefined, "not before the week is out");
await runner.productDigestTick(db, week);
const idea = (await byTitle(p.id, "Подсказка под полем поиска"))!;
assert.equal(idea.proposed, true);
assert.ok((await chatOf(p.id)).some((m) => /Раз в неделю: нашёл улучшений: 1/.test(m.text)));
await runner.productDigestTick(db, week);
assert.equal((await core.listTasks(db, { projectId: p.id })).filter((t) => t.title === idea.title).length, 1);
// A new story of a person starts the next version.
await core.createTask(db, { projectId: p.id, title: "Ещё одна просьба владельца" });
assert.equal((await core.getVersion(db, p.id))?.doneAt, null);
});
test("mayAutoAccept: whose stories are accepted by FORGE", () => {
const human = { origin: "human", severity: null };
const idea = { origin: "acceptance", severity: "important" };
const broken = { origin: "incident", severity: "breakage" };
assert.deepEqual([human, idea, broken].map((t) => core.mayAutoAccept(t, "mine")), [true, false, false]);
assert.deepEqual([human, idea, broken].map((t) => core.mayAutoAccept(t, "mine_breakage")), [true, false, true]);
assert.deepEqual([human, idea, broken].map((t) => core.mayAutoAccept(t, "all")), [true, true, true]);
});
});