// 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 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 = `FRTVL

Подбор стажировок

Демо-режим: показаны вымышленные примеры (ключ Claude API не подключён)

О сервисеlogo`; const REAL_PAGE = `

Подбор стажировок

`; type User = Awaited>; 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("

О сервисе: подбираем стажировки

"); res.writeHead(req.url === "/" ? 200 : 404, { "content-type": "text/html" }).end(page); }); await new Promise((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(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 = {}) => { 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 задаёт раннер/); 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 задаёт раннер/); }); 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(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, /### Страница \/\nFRTVL\nПодбор стажировок\nДемо-режим: показаны вымышленные примеры/, "the page as its user reads it"); assert.match(call.prompt, /\[поле: Токен запуска\] \[кнопка: Подобрать\]/); assert.match(call.prompt, /### Страница \/about\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", "Продакт"]); 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, /Завёл доработки в бэклог:\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.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>/, ""); 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('

Цена — 5₽
Логотип'), "Цена — 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":"А1"},{"title":"Б22"},{"title":"В33"},{"title":"Г44"},{"title":"Д55"}]}')!; 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); }); });