= {}) => {
+ 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);
+ });
+});
diff --git a/packages/testkit/test/secrets.test.ts b/packages/testkit/test/secrets.test.ts
index e154f360..580e0c44 100644
--- a/packages/testkit/test/secrets.test.ts
+++ b/packages/testkit/test/secrets.test.ts
@@ -73,7 +73,7 @@ describe("project secrets (PEP-54)", () => {
["stripe-key", /A–Z, 0–9 и _/],
["PATH", /PATH задаёт раннер/],
["PEPPA_DB", /PEPPA_DB задаёт раннер/],
- ["CLAUDE_CODE_OAUTH_TOKEN", /задаёт раннер/],
+ ["LD_PRELOAD", /задаёт раннер/],
] as const) {
test(`Недопустимое имя: ${name}`, async () => {
const { proj } = await ownedProject();
diff --git a/template/.gitea/peppa-deploy.sh b/template/.gitea/peppa-deploy.sh
index 2586968f..1120a073 100644
--- a/template/.gitea/peppa-deploy.sh
+++ b/template/.gitea/peppa-deploy.sh
@@ -5,6 +5,9 @@
# (deploy.health, по умолчанию /healthz, PEPPA_HEALTH_TIMEOUT секунд, по умолчанию 120).
# Не прошла — откат на образ, который работал до этого. Итог уходит в Пеппу (подпись
# PEPPA_CI_SECRET): окружение, SHA, предыдущий SHA, коммиты (для списка задач), хвост лога.
+# Секреты проекта (PEP-112): перед запуском скрипт берёт их у Пеппы («⋯ Настройки проекта →
+# Секреты», та же подпись) и передаёт сервису как переменные окружения — в compose.yml и в
+# secrets Actions их вписывать не нужно. Значения не попадают ни в лог, ни в репозиторий.
set -uo pipefail
mode="$1"
cfg=.peppa/project.json
@@ -68,9 +71,35 @@ report() { # report [reason]
echo "peppa: Пеппа недоступна — релиз не записан"
}
+# PEP-112: секреты проекта из Пеппы → compose-override с environment сервиса (JSON — тоже YAML;
+# «$» удваивается, чтобы compose не подставлял переменные). Файл живёт до конца скрипта.
+override=""
+trap '[[ -n "$override" ]] && rm -f "$override"' EXIT
+project_secrets() {
+ local peppa_url body sig out n
+ peppa_url=$(jq -r '.peppaUrl // empty' "$cfg")
+ [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]] || return 0
+ body=$(jq -nc --arg repo "${GITHUB_REPOSITORY:-}" --arg env "$env_name" --arg sha "$sha" --argjson ts "$(date +%s)" \
+ '{repository:$repo, env:$env, sha:$sha, ts:$ts}')
+ sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}')
+ if ! out=$(curl -fsS -m 20 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \
+ -H "X-Peppa-Event: deploy-env" -H "X-Gitea-Signature: $sig" --data-binary "$body" 2>/dev/null); then
+ echo "peppa: секреты проекта не получены (Пеппа недоступна) — продукт запускается без них"
+ return 0
+ fi
+ n=$(jq -r '(.env // {}) | length' <<<"$out" 2>/dev/null || echo 0)
+ [[ "$n" =~ ^[1-9][0-9]*$ ]] || { echo "peppa: секретов проекта нет"; return 0; }
+ override=$(mktemp "${TMPDIR:-/tmp}/peppa-env.XXXXXX")
+ chmod 600 "$override"
+ jq -c --arg svc "$service" '{services: {($svc): {environment: (.env | map_values(tostring | gsub("\\$"; "$$")))}}}' <<<"$out" > "$override"
+ echo "peppa: секретов проекта передано сервису $service: $n"
+}
+
dc() { # dc
local img="$1"; shift
- IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@"
+ local files=(-f "$compose")
+ [[ -n "$override" ]] && files+=(-f "$override")
+ IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" "${files[@]}" "$@"
}
healthy() {
@@ -123,6 +152,7 @@ if [[ $mode == preview-down ]]; then
fi
report deploying
+project_secrets
if ! docker image inspect "$image" >/dev/null 2>&1; then
docker build -t "$image" --label "peppa.project=$slug" -f "$dockerfile" . || { report failed "сборка образа не удалась"; exit 1; }
fi
diff --git a/template/.gitea/workflows/deploy.yml b/template/.gitea/workflows/deploy.yml
index 7400926c..c35dbc02 100644
--- a/template/.gitea/workflows/deploy.yml
+++ b/template/.gitea/workflows/deploy.yml
@@ -1,11 +1,12 @@
# CD проекта Пеппы (PEP-57): preview на PR (удаляется при закрытии), staging на мерж в main,
-# прод — тег deploy-prod-* (его ставит Пеппа по кнопке PM). Настройки — .peppa/project.json →
+# прод — тег deploy-prod-* (его ставит Пеппа по кнопке PM), перезапуск staging с новыми секретами
+# проекта — тег deploy-staging-* (PEP-112, его ставит Пеппа). Настройки — .peppa/project.json →
# "deploy"; без них шаг пропускается. Изменение файла PM видит отдельно.
name: deploy
on:
push:
branches: [main]
- tags: ["deploy-prod-*"]
+ tags: ["deploy-prod-*", "deploy-staging-*"]
pull_request:
types: [opened, synchronize, reopened, closed]
env:
diff --git a/template/deploy/compose.yml b/template/deploy/compose.yml
index 01936ba5..cb098b86 100644
--- a/template/deploy/compose.yml
+++ b/template/deploy/compose.yml
@@ -1,7 +1,8 @@
# Стенд проекта Пеппы (PEP-57). Деплой: docker compose -p - -f deploy/compose.yml up -d
# с переменными IMAGE (образ peppa/:), HOST, ROUTER, APP_PORT — их задаёт
# .gitea/peppa-deploy.sh. Сервис и порт — .peppa/project.json → deploy.service / deploy.port.
-# Секреты приложения — в secrets Actions репозитория, сюда только через environment.
+# Секреты приложения сюда не вписывают: PM заводит их в Пеппе («⋯ Настройки проекта → Секреты»),
+# peppa-deploy.sh сам передаёт их сервису как переменные окружения с тем же именем (PEP-112).
services:
web:
image: ${IMAGE}