546 lines
37 KiB
TypeScript
546 lines
37 KiB
TypeScript
// 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 = `<html><head><title>FRTVL</title><style>p{color:red}</style></head><body>
|
||
<h1>Подбор стажировок</h1><p>Демо-режим: показаны вымышленные примеры (ключ Claude API не подключён)</p>
|
||
<form><input name="token" placeholder="Токен запуска"><button>Подобрать</button></form>
|
||
<a href="/about">О сервисе</a><a href="/logo.png">logo</a><script>var secret = 1</script></body></html>`;
|
||
const REAL_PAGE = `<html><body><h1>Подбор стажировок</h1><button>Подобрать</button></body></html>`;
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let pm: User;
|
||
let server: Server;
|
||
let page = DEMO_PAGE;
|
||
let up = true;
|
||
let n = 0;
|
||
|
||
async function proj(o: { intake?: boolean } = {}) {
|
||
n++;
|
||
const ws = join(TMP, `ws-${n}`);
|
||
mkdirSync(join(ws, ".peppa"), { recursive: true });
|
||
const p = await core.createProject(db, { slug: `mock-acc-${n}`, key: `MAC${String.fromCharCode(64 + n)}`, name: `Стажировки ${n}`, giteaOwner: "x", giteaRepo: `mock-acc-${n}`, workspacePath: ws, ownerId: pm.id });
|
||
if (o.intake !== false) await core.setIntakeSettings(db, p.id, { enabled: true });
|
||
return p;
|
||
}
|
||
const chatOf = async (projectId: number) => (await core.discussionMessages(db, (await core.ensureProjectChat(db, projectId)).id)).map((m) => ({ kind: m.authorKind, who: m.authorLogin, text: m.text }));
|
||
const tick = () => runner.productReviewTick(db, { wait: true });
|
||
const healthy = (p: { id: number; key: string }, env: "staging" | "prod", sha: string, o: { previousSha?: string; commits?: string[] } = {}) =>
|
||
core.getProject(db, p.key).then((project) => runner.recordRelease(db, project, { env, sha, status: "healthy", host: `${env}.mock.test`, previousSha: o.previousSha ?? null, commits: o.commits ?? [] }));
|
||
|
||
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: 1201, login: "asel" }, { access_token: "x" });
|
||
server = createServer((req, res) => {
|
||
if (!up) return void res.writeHead(503).end();
|
||
if (req.url === "/about") return void res.writeHead(200, { "content-type": "text/html" }).end("<p>О сервисе: подбираем стажировки</p>");
|
||
res.writeHead(req.url === "/" ? 200 : 404, { "content-type": "text/html" }).end(page);
|
||
});
|
||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||
process.env.PEPPA_PRODUCT_FETCH_BASE = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||
});
|
||
after(async () => {
|
||
server.close();
|
||
await teardown();
|
||
});
|
||
|
||
describe("PEP-112: список «чтобы заработало по-настоящему»", () => {
|
||
test("Scenario: Ключ заведён — пункт закрыт; Секрет удалён — пункт снова открыт", async () => {
|
||
const p = await proj();
|
||
const { added } = await core.declareNeeds(db, p.id, [{ title: "Ключ Claude API", why: "без него ответы — примеры", how: "console.anthropic.com → API keys", secret: "ANTHROPIC_API_KEY" }], { source: "agent", story: "FRT-3" });
|
||
assert.equal(added.length, 1);
|
||
assert.equal((await core.openNeeds(db, p.id)).length, 1);
|
||
assert.match(stripAsIs(await core.demoNote(db, p.id, p.key)), /демо-режиме. Нужно от вас: Ключ Claude API/);
|
||
await core.setProjectSecret(db, pm.id, p.id, "ANTHROPIC_API_KEY", "sk-ant-mock-1");
|
||
assert.equal((await core.openNeeds(db, p.id)).length, 0);
|
||
assert.equal(await core.demoNote(db, p.id, p.key), "");
|
||
await core.deleteProjectSecret(db, pm.id, p.id, "ANTHROPIC_API_KEY");
|
||
assert.deepEqual((await core.openNeeds(db, p.id)).map((x) => x.title), ["Ключ Claude API"]);
|
||
});
|
||
|
||
test("a need without a secret is ticked off by the owner; the same need declared twice stays one", async () => {
|
||
const p = await proj();
|
||
await core.declareNeeds(db, p.id, [{ title: "Аккаунт в платёжном сервисе" }], { source: "agent" });
|
||
const again = await core.declareNeeds(db, p.id, [{ title: "аккаунт в платёжном сервисе!" }], { source: "agent" });
|
||
assert.equal(again.added.length, 0);
|
||
assert.equal(again.all.length, 1);
|
||
await core.setNeedDone(db, p.id, again.all[0]!.id, true);
|
||
assert.equal((await core.openNeeds(db, p.id)).length, 0);
|
||
await core.removeNeed(db, p.id, again.all[0]!.id);
|
||
assert.equal((await core.productNeeds(db, p.id)).length, 0);
|
||
});
|
||
|
||
test("the product agent's own items are replaced at each look; the developer's and ticked ones stay", async () => {
|
||
const p = await proj();
|
||
await core.declareNeeds(db, p.id, [{ title: "Ключ карты", secret: "MAPS_KEY" }], { source: "agent" });
|
||
await core.declareNeeds(db, p.id, [{ title: "Реквизиты компании" }, { title: "Логотип" }], { source: "product", replaceSource: true });
|
||
const logo = (await core.productNeeds(db, p.id)).find((x) => x.title === "Логотип")!;
|
||
await core.setNeedDone(db, p.id, logo.id, true);
|
||
await core.declareNeeds(db, p.id, [{ title: "Текст оферты" }], { source: "product", replaceSource: true });
|
||
assert.deepEqual((await core.productNeeds(db, p.id)).map((x) => [x.title, x.open]), [["Ключ карты", true], ["Логотип", false], ["Текст оферты", true]]);
|
||
});
|
||
});
|
||
|
||
describe("PEP-112: агент объявляет потребности до ревью", () => {
|
||
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 };
|
||
};
|
||
}
|
||
|
||
test("Scenario: Новый пункт — сообщение владельцу; Повторное объявление не шумит", async () => {
|
||
const p = await proj();
|
||
const story = await core.createTask(db, { projectId: p.id, title: "Подбор стажировок" });
|
||
const call = await agent(p.key);
|
||
const need = { title: "Ключ Claude API", why: "без него ответы — вымышленные примеры", how: "console.anthropic.com → API keys → Create key", secret: "ANTHROPIC_API_KEY" };
|
||
const out = await call("declare_needs", { task: story.key, needs: [need] });
|
||
assert.equal(out.isError, false, out.text);
|
||
assert.match(out.text, /⏳ ждёт владельца: Ключ Claude API \(\$ANTHROPIC_API_KEY\)/);
|
||
const talk = await chatOf(p.id);
|
||
assert.equal(talk.length, 1);
|
||
assert.equal(talk[0]!.kind, "agent");
|
||
assert.match(talk[0]!.text, /Ключ Claude API — без него ответы — вымышленные примеры/);
|
||
assert.match(talk[0]!.text, /Где взять: console\.anthropic\.com/);
|
||
assert.match(talk[0]!.text, /карточка «Ваш продукт»/);
|
||
assert.match(talk[0]!.text, new RegExp(`http://peppa.test/p/${p.key}`));
|
||
assert.match((await call("get_task", { task: story.key })).text, /Чтобы продукт работал по-настоящему[\s\S]*⏳ ждёт владельца: Ключ Claude API/);
|
||
|
||
const again = await call("declare_needs", { needs: [need] });
|
||
assert.match(again.text, /Новых пунктов нет/);
|
||
assert.equal((await core.productNeeds(db, p.id)).length, 1);
|
||
assert.equal((await chatOf(p.id)).length, 1, "no second message");
|
||
});
|
||
|
||
test("Scenario: Недопустимое имя секрета", async () => {
|
||
const p = await proj();
|
||
const out = await (await agent(p.key))("declare_needs", { needs: [{ title: "Токен", secret: "PEPPA_TOKEN" }] });
|
||
assert.equal(out.isError, true);
|
||
assert.match(out.text, /PEPPA_TOKEN занято самой Peppa FACTORY/);
|
||
assert.equal((await core.productNeeds(db, p.id)).length, 0);
|
||
});
|
||
});
|
||
|
||
describe("PEP-112: секреты проекта в выкатке", () => {
|
||
const sign = (projectId: number, body: string) => createHmac("sha256", core.projectHookSecret(projectId)).update(body).digest("hex");
|
||
const ask = (p: { id: number; giteaOwner: string; giteaRepo: string }, o: { ts?: number; signature?: string } = {}) => {
|
||
const body = JSON.stringify({ repository: `${p.giteaOwner}/${p.giteaRepo}`, env: "staging", sha: "abc1234", ts: o.ts ?? Math.floor(Date.now() / 1000) });
|
||
return runner.handleGiteaHook(db, { event: "deploy-env", signature: o.signature ?? sign(p.id, body), body });
|
||
};
|
||
|
||
test("Scenario: Ключ Claude для продукта — агенту не выдаётся, выкатка получает оба", async () => {
|
||
const p = await proj();
|
||
await core.setProjectSecret(db, pm.id, p.id, "ANTHROPIC_API_KEY", "sk-ant-mock-2");
|
||
await core.setProjectSecret(db, pm.id, p.id, "STRIPE_TEST_KEY", "sk_test_mock$1");
|
||
assert.deepEqual(Object.keys((await core.projectSecretEnv(db, p.id)).env), ["STRIPE_TEST_KEY"]);
|
||
assert.deepEqual((await core.projectSecretEnv(db, p.id, "deploy")).env, { ANTHROPIC_API_KEY: "sk-ant-mock-2", STRIPE_TEST_KEY: "sk_test_mock$1" });
|
||
await assert.rejects(core.setProjectSecret(db, pm.id, p.id, "PEPPA_HOME", "x"), /PEPPA_HOME занято самой Peppa FACTORY/);
|
||
});
|
||
|
||
test("Scenario: Выкатка с секретами; Неверная подпись; устаревший запрос", async () => {
|
||
const p = await proj();
|
||
await core.setProjectSecret(db, pm.id, p.id, "STRIPE_KEY", "sk_live_1");
|
||
const ok = await ask(p);
|
||
assert.equal(ok.status, 200);
|
||
assert.deepEqual(ok.body.env, { STRIPE_KEY: "sk_live_1" });
|
||
const bad = await ask(p, { signature: "00" });
|
||
assert.equal(bad.status, 401);
|
||
assert.equal(bad.body.env, undefined);
|
||
const stale = await ask(p, { ts: Math.floor(Date.now() / 1000) - 3600 });
|
||
assert.equal(stale.status, 400);
|
||
assert.equal(stale.body.env, undefined);
|
||
});
|
||
|
||
test("the release log never keeps a secret value readable", async () => {
|
||
const p = await proj({ intake: false });
|
||
await core.setProjectSecret(db, pm.id, p.id, "STRIPE_KEY", "sk_live_printed");
|
||
const rel = await runner.recordRelease(db, await core.getProject(db, p.key), { env: "staging", sha: "feed123", status: "failed", reason: "x", logTail: "boot: key=sk_live_printed" });
|
||
assert.equal(rel.logTail, "boot: key=••••");
|
||
});
|
||
});
|
||
|
||
describe("PEP-112: смена секрета перезапускает продукт", () => {
|
||
const fakeGitea = () => {
|
||
const tags: Array<{ tag: string; sha: string }> = [];
|
||
return { tags, client: { createTag: async (_o: string, _r: string, tag: string, sha: string) => void tags.push({ tag, sha }) } as never };
|
||
};
|
||
const later = () => new Date(Date.now() + 3 * 60_000);
|
||
|
||
test("Scenario: Ключ добавлен — продукт перезапущен (один раз на серию правок)", async () => {
|
||
const p = await proj({ intake: false });
|
||
await db.insert(releases).values([
|
||
{ projectId: p.id, env: "staging", sha: "abc1234", status: "healthy", host: "s.mock.test", tasks: [] },
|
||
{ projectId: p.id, env: "prod", sha: "abc1234", status: "healthy", host: "p.mock.test", tasks: [] },
|
||
]);
|
||
await core.setProjectSecret(db, pm.id, p.id, "A_KEY", "value-a");
|
||
await core.setProjectSecret(db, pm.id, p.id, "B_KEY", "value-b");
|
||
const g = fakeGitea();
|
||
assert.deepEqual(await runner.productRedeployTick(db, { client: g.client }), [], "waits for a quiet spell");
|
||
const created = await runner.productRedeployTick(db, { client: g.client, now: later() });
|
||
assert.equal(created.length, 2);
|
||
assert.match(g.tags[0]!.tag, /^deploy-staging-\d{17}$/);
|
||
assert.match(g.tags[1]!.tag, /^deploy-prod-\d{17}$/);
|
||
assert.deepEqual(g.tags.map((t) => t.sha), ["abc1234", "abc1234"]);
|
||
assert.deepEqual(await runner.productRedeployTick(db, { client: g.client, now: later() }), [], "once");
|
||
});
|
||
|
||
test("Scenario: Нечего перезапускать", async () => {
|
||
const p = await proj({ intake: false });
|
||
await core.setProjectSecret(db, pm.id, p.id, "A_KEY", "value-a");
|
||
const g = fakeGitea();
|
||
assert.deepEqual(await runner.productRedeployTick(db, { client: g.client, now: later() }), []);
|
||
assert.equal(g.tags.length, 0);
|
||
});
|
||
|
||
test("Scenario: Отчёт о перезапуске — «перезапущен с новыми настройками» без вопроса «Показать всем?»", async () => {
|
||
const p = await proj({ intake: false });
|
||
await core.declareNeeds(db, p.id, [{ title: "Ключ почты", secret: "MAIL_KEY" }], { source: "agent" });
|
||
await healthy(p, "staging", "abc1234", { previousSha: "abc1234" });
|
||
const qs = await core.pendingQuestions(db, p.id);
|
||
assert.equal(qs.length, 1);
|
||
assert.match(qs[0]!.text, /версия для проверки перезапущена с новыми настройками/);
|
||
assert.match(stripAsIs(qs[0]!.text), /Ещё работает в демо-режиме, нужно: Ключ почты/);
|
||
assert.ok(!qs.some((q) => q.options?.includes(runner.PROD_OPTION)));
|
||
});
|
||
});
|
||
|
||
describe("PEP-112: агент приёмки принимает выкаченный продукт", () => {
|
||
test("Scenario: Приёмка после выкатки — сообщение, потребность, стори-доработка; Тот же коммит повторно не проверяется", async () => {
|
||
page = DEMO_PAGE;
|
||
const p = await proj();
|
||
const story = await core.createTask(db, { projectId: p.id, title: "Подбор стажировок", description: "Студент видит подходящие стажировки.\n\n## Критерии приёмки\n- Виден список стажировок" });
|
||
const before = accepts().length;
|
||
await healthy(p, "staging", "abc1234", { commits: [`Merge pull request '${story.key}' (#1) from task/${story.key} into main`] });
|
||
assert.ok(await core.pendingProductReview(db, p.id));
|
||
await tick();
|
||
assert.equal(await core.pendingProductReview(db, p.id), null);
|
||
|
||
const call = accepts().at(-1)!;
|
||
assert.equal(accepts().length, before + 1);
|
||
assert.match(call.prompt, /версия для проверки, адрес https:\/\/staging\.mock\.test/);
|
||
assert.match(call.prompt, new RegExp(`### ${story.key} «Подбор стажировок»\\nСтудент видит подходящие стажировки`), "the stories that went in, with their acceptance criteria");
|
||
assert.match(call.prompt, /### Страница \/\n«««ДАННЫЕ[^\n]*\nFRTVL\nПодбор стажировок\nДемо-режим: показаны вымышленные примеры/, "the page as its user reads it");
|
||
assert.match(call.prompt, /\[поле: Токен запуска\] \[кнопка: Подобрать\]/);
|
||
assert.match(call.prompt, /### Страница \/about\n«««ДАННЫЕ[^\n]*\nО сервисе: подбираем стажировки/, "linked pages of the same site");
|
||
assert.ok(!call.prompt.includes("var secret") && !call.prompt.includes("color:red") && !call.prompt.includes("logo.png"));
|
||
assert.deepEqual(call.argv.slice(0, 5), ["-p", "--output-format", "json", "--max-turns", "1"], "no tools without screenshots");
|
||
|
||
const talk = await chatOf(p.id);
|
||
assert.equal(talk.length, 1);
|
||
assert.deepEqual([talk[0]!.kind, talk[0]!.who], ["agent", "Аналитик"], "PEP-198: the findings come from the analyst");
|
||
assert.match(talk[0]!.text, /Агент приёмки посмотрел версию для проверки: https:\/\/staging\.mock\.test/);
|
||
assert.match(talk[0]!.text, /Как пользоваться:\n1\. Откройте адрес продукта/);
|
||
assert.match(talk[0]!.text, /Пока не настоящее:\n• Демо-режим: показаны вымышленные примеры/);
|
||
assert.match(talk[0]!.text, /Чтобы заработало по-настоящему, нужно от вас:\n• Ключ сервиса — без него показаны примеры/);
|
||
assert.match(talk[0]!.text, /Нашёл улучшений: 1 \(важных: 1\)\.\n• MAC\w-2 «Убрать служебное поле «Токен запуска» с экрана» — Важно/);
|
||
|
||
assert.deepEqual((await core.openNeeds(db, p.id)).map((x) => [x.title, x.source]), [["Ключ сервиса", "product"]]);
|
||
const stories = await core.listTasks(db, { projectId: p.id });
|
||
const filed = stories.find((t) => /Токен запуска/.test(t.title))!;
|
||
assert.equal(filed.status, "backlog");
|
||
assert.equal(filed.proposed, true, "PEP-197: a story of the acceptance agent waits in «Предложено»");
|
||
assert.equal(filed.origin, "acceptance");
|
||
assert.match(filed.description ?? "", /Заведено агентом приёмки/);
|
||
assert.equal((await core.getIntakeState(db, filed.id))?.stage, "done", "already formulated: the intake roles skip it");
|
||
const review = (await core.lastProductReview(db, p.id))!;
|
||
assert.deepEqual([review.env, review.sha, review.howto.length, review.notReal.length], ["staging", "abc1234", 2, 1]);
|
||
|
||
// The same commit reported again: not looked at twice.
|
||
await healthy(p, "staging", "abc1234");
|
||
assert.equal(await core.pendingProductReview(db, p.id), null);
|
||
await tick();
|
||
assert.equal(accepts().length, before + 1);
|
||
assert.equal((await chatOf(p.id)).length, 1);
|
||
});
|
||
|
||
test("a restart after the secrets changed is looked at again: the demo is gone, the needs are closed, no duplicate story", async () => {
|
||
page = DEMO_PAGE;
|
||
const p = await proj();
|
||
await db.insert(releases).values({ projectId: p.id, env: "prod", sha: "abc1234", status: "healthy", host: "prod.mock.test", tasks: [] });
|
||
await healthy(p, "prod", "abc1234");
|
||
await tick();
|
||
assert.equal((await core.openNeeds(db, p.id)).length, 1);
|
||
const storiesBefore = (await core.listTasks(db, { projectId: p.id })).length;
|
||
|
||
await core.setProjectSecret(db, pm.id, p.id, "SERVICE_KEY", "value-1");
|
||
const tags: string[] = [];
|
||
await runner.productRedeployTick(db, { client: { createTag: async (_o: string, _r: string, tag: string) => void tags.push(tag) } as never, now: new Date(Date.now() + 3 * 60_000) });
|
||
assert.equal(tags.length, 1);
|
||
page = DEMO_PAGE.replace(/<p>Демо-режим[^<]*<\/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 Peppa 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('<div>Цена — 5₽</div><input type="hidden" name="csrf" value="zzz"><input aria-label="Почта"><img alt="Логотип" src="x.png">'), "Цена — 5₽\n[поле: Почта] [картинка: Логотип]");
|
||
assert.deepEqual(core.pageLinks('<a href="/">Д</a><a href="/pricing?x=1">Ц</a><a href="https://else.test/x">E</a><a href="/api/x">A</a><a href="/a.css">c</a><a href="/pricing">Ц</a><a href="#top">t</a>'), ["/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 Peppa", () => {
|
||
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]);
|
||
});
|
||
});
|