PEP-112: go-live needs, project secrets in deploys, restart on secret change, product agent accepts deploys

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 16:12:54 +05:00
parent 81f83fc37e
commit eb760d7a92
28 changed files with 1275 additions and 45 deletions

View File

@ -52,6 +52,8 @@ import {
setTaskBudget,
type Budget,
setProjectSecret,
setNeedDone,
removeNeed,
deleteProjectSecret,
reencryptAll,
markSecretRotated,
@ -646,6 +648,23 @@ export async function saveProjectSecretAction(f: FormData) {
});
}
// PEP-112: «чтобы заработало по-настоящему» on the «Ваш продукт» card.
export async function setNeedDoneAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const project = await projectForUser(db, user.id, Number(str(f, "projectId")));
await setNeedDone(db, project.id, str(f, "id"), str(f, "done") !== "0");
});
}
export async function removeNeedAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const project = await projectForUser(db, user.id, Number(str(f, "projectId")));
await removeNeed(db, project.id, str(f, "id"));
});
}
export async function deleteProjectSecretAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {

View File

@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest } from "@peppa/runner";
import { poolSubscriptions, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { PRODUCT_PROJECT_TABS } from "@peppa/core";
import { productNeeds, lastProductReview } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@ -156,6 +156,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const specs = tab === "specs" ? listSpecs(p) : [];
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
const product = await projectProduct(db, p.id);
const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]);
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
const sharedReq = await sharedRequest(db, p.id);
@ -487,7 +488,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</p>
)}
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} engineer={engineer} back={back} />}
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} engineer={engineer} projectId={p.id} needs={productNeedList} review={productReview} back={back} />}
<nav aria-label="Разделы проекта" className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
{visibleTabs.map((t) => (
<Fragment key={t.id}>

View File

@ -1,10 +1,11 @@
import Link from "next/link";
import { ExternalLink, Rocket } from "lucide-react";
import type { ProjectProduct } from "@peppa/core";
import { ExternalLink, KeyRound, Rocket, X } from "lucide-react";
import type { ProductNeedView, ProductReview, ProjectProduct } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Hidden } from "@/components/cards";
import { deployProdAction } from "@/app/(app)/actions";
import { Input } from "@/components/ui/input";
import { deployProdAction, removeNeedAction, saveProjectSecretAction, setNeedDoneAction } from "@/app/(app)/actions";
const host = (url: string) => url.replace(/^https?:\/\//, "");
@ -12,7 +13,28 @@ const host = (url: string) => url.replace(/^https?:\/\//, "");
* PEP-111: «Ваш продукт» on the project page — where the result is and what to do next, for a
* product manager who asks «где это работает?». Nothing is shown before the first accepted story.
*/
export function ProductCard({ product, projectKey, chat = true, engineer = false, back }: { product: ProjectProduct; projectKey: string; chat?: boolean; /** PEP-119: «Инженер» gets the link to the releases tab, «Продакт» — one button. */ engineer?: boolean; back?: string }) {
export function ProductCard({
product,
projectKey,
chat = true,
engineer = false,
projectId,
needs = [],
review = null,
back,
}: {
product: ProjectProduct;
projectKey: string;
chat?: boolean;
/** PEP-119: «Инженер» gets the link to the releases tab, «Продакт» — the button right here. */
engineer?: boolean;
projectId?: number;
/** PEP-112: what the owner has to give before the product is real. */
needs?: ProductNeedView[];
/** PEP-112: the product agent's last acceptance. */
review?: ProductReview | null;
back?: string;
}) {
// «Показать всем»: the same action as the button in «Релизы», without sending a product manager there.
const showAll = engineer ? (
<>
@ -25,14 +47,17 @@ export function ProductCard({ product, projectKey, chat = true, engineer = false
</form>
);
const { live, check, doneStories } = product;
if (!live && !check && doneStories === 0) return null;
const open = needs.filter((n) => n.open);
if (!live && !check && doneStories === 0 && !open.length) return null;
const deployed = !!(live || check);
const mayEdit = chat && projectId != null && !!back;
const next = chat && (
<p className="m-0 text-sm text-muted-foreground">
Что дальше: опишите следующую задачу <Link href={`/chats/${projectKey}`}>аналитику в чате</Link> — он поможет сформулировать стори, агенты сделают.
</p>
);
return (
<section aria-label="Ваш продукт" className="mb-5 flex flex-col gap-3 rounded-xl border border-ok/40 bg-ok/5 p-4">
<section aria-label="Ваш продукт" className={`mb-5 flex flex-col gap-3 rounded-xl border p-4 ${open.length ? "border-warn/50 bg-warn/5" : "border-ok/40 bg-ok/5"}`}>
{live ? (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
@ -62,7 +87,7 @@ export function ProductCard({ product, projectKey, chat = true, engineer = false
</a>
</Button>
</div>
) : (
) : doneStories === 0 ? null : (
<div className="flex flex-col gap-0.5">
<span className="text-[15px] font-semibold">Готово стори: {doneStories}</span>
<span className="text-sm text-muted-foreground">
@ -81,6 +106,81 @@ export function ProductCard({ product, projectKey, chat = true, engineer = false
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — {showAll}
</p>
)}
{open.length > 0 && (
<div role="note" aria-label="Демо-режим" className="flex flex-col gap-2 rounded-lg border border-warn/40 bg-warn/10 p-3">
<span className="text-sm font-semibold">
{deployed ? "Работает в демо-режиме" : "Продукт будет работать в демо-режиме"}: нужно {open.length === 1 ? "одно действие" : `действий: ${open.length}`} от вас
</span>
<span className="text-sm text-muted-foreground">
Пока этого нет, продукт показывает примеры вместо настоящей работы. Ключи хранятся зашифрованными; Пеппа сама передаст их продукту и перезапустит его — через пару минут после сохранения.
</span>
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{open.map((n) => (
<li key={n.id} className="flex flex-col gap-1.5 rounded-md border bg-background/60 p-2.5 text-sm">
<div className="flex items-start gap-2">
<KeyRound className="mt-0.5 size-4 shrink-0 text-warn" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="font-medium">{n.title}</span>
{n.why && <span className="text-muted-foreground">Зачем: {n.why}</span>}
{n.how && <span className="text-muted-foreground">Где взять: {n.how}</span>}
</div>
{mayEdit && (
<form action={removeNeedAction}>
<Hidden fields={{ projectId, id: n.id, back }} />
<Button variant="ghost" size="icon" aria-label={`Не нужно: ${n.title}`} title="Не нужно — убрать пункт">
<X />
</Button>
</form>
)}
</div>
{mayEdit &&
(n.secret ? (
<form action={saveProjectSecretAction} className="flex flex-wrap items-center gap-2" autoComplete="off">
<Hidden fields={{ projectId, name: n.secret, back }} />
<Input name="value" type="password" required placeholder="Вставьте ключ сюда" aria-label={`Ключ: ${n.title}`} className="min-w-0 flex-1 font-mono" autoComplete="off" spellCheck={false} />
<Button size="sm">Сохранить</Button>
</form>
) : (
<form action={setNeedDoneAction}>
<Hidden fields={{ projectId, id: n.id, done: 1, back }} />
<Button size="sm" variant="outline">
Сделано
</Button>
</form>
))}
</li>
))}
</ul>
</div>
)}
{review && deployed && (review.howto.length > 0 || review.notReal.length > 0) && (
<details className="text-sm">
<summary className="cursor-pointer font-medium">Как пользоваться продуктом</summary>
<div className="mt-2 flex flex-col gap-2">
<p className="m-0 text-muted-foreground">{review.summary}</p>
{review.howto.length > 0 && (
<ol className="m-0 flex list-decimal flex-col gap-1 pl-5">
{review.howto.map((step, i) => (
<li key={i}>{step}</li>
))}
</ol>
)}
{review.notReal.length > 0 && (
<div className="flex flex-col gap-1">
<span className="font-medium">Пока не настоящее</span>
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-muted-foreground">
{review.notReal.map((x, i) => (
<li key={i}>{x}</li>
))}
</ul>
</div>
)}
<p className="m-0 text-xs text-muted-foreground">
Продукт посмотрел продакт-агент {ago(new Date(review.at))} — подробности в <Link href={`/chats/${projectKey}`}>обсуждении проекта</Link>.
</p>
</div>
</details>
)}
{next}
</section>
);

View File

@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { deleteProjectSecretAction, saveProjectSecretAction } from "@/app/(app)/actions";
/** PEP-54: the project's secrets for agents — names only; values are write-only. */
/** PEP-54: the project's secrets for agents and (PEP-112) for the deployed product — names only; values are write-only. */
export function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: number; secrets: ProjectSecretView[]; back: string }) {
return (
<div className="flex flex-col gap-3">
@ -38,7 +38,7 @@ export function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: n
<Button size="sm" className="self-start">Сохранить</Button>
</form>
<p className="m-0 text-xs text-muted-foreground">
Секреты получают агенты проекта как переменные окружения с тем же именем — при следующем запуске сессии. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена (<code>list_secrets</code>).
Секреты получают агенты проекта (при следующем запуске сессии) и сам выкаченный продукт — как переменные окружения с тем же именем; после изменения Пеппа через пару минут перезапускает продукт. Имена <code>ANTHROPIC_…</code>, <code>CLAUDE_…</code>, <code>OPENCODE_…</code> идут только в продукт. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена (<code>list_secrets</code>).
</p>
</div>
);

View File

@ -71,7 +71,7 @@ export async function discussionHistory(db: Db, chatId: number, limit = HISTORY)
.where(and(eq(chatMessages.chatId, chatId), isNull(chatMessages.threadKey), eq(chatMessages.kind, "user")))
.orderBy(desc(chatMessages.id))
.limit(limit);
return rows.reverse().filter((r) => !r.text.startsWith("/") && r.kind !== "system").map((r) => ({ who: r.kind === "agent" ? ANALYST_NAME : (r.login ?? "пользователь"), text: r.text }));
return rows.reverse().filter((r) => !r.text.startsWith("/") && r.kind !== "system").map((r) => ({ who: r.kind === "agent" ? (r.login ?? ANALYST_NAME) : (r.login ?? "пользователь"), text: r.text }));
}
export async function analystChatContext(db: Db, project: Project): Promise<string> {

View File

@ -29,6 +29,8 @@ export * from "./analyst-chat.ts";
export * from "./ui-mode.ts";
export * from "./product.ts";
export * from "./story-refine.ts";
export * from "./product-needs.ts";
export * from "./product-review.ts";
export * from "./local-users.ts";
export * from "./new-users.ts";
export * from "./specs.ts";

View File

@ -0,0 +1,141 @@
// PEP-112: «чтобы заработало по-настоящему» — what the project's owner has to give before the
// product stops being a demo: a key, an account, a decision. The developer agent declares the
// items (MCP `declare_needs`), the product agent adds what it saw on the deployed product, the
// «Ваш продукт» card shows the open ones. An item that names a secret closes itself while that
// secret is stored in the project's secrets (Peppa hands them to the deploy); the rest the owner
// ticks off. One `settings` row per project — the list is short and always read whole.
import { projectSecrets, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { secretNameError } from "./secrets.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
export type NeedSource = "agent" | "product";
export interface ProductNeed {
id: string;
/** What to give, in the owner's words: «Ключ Claude API». */
title: string;
/** What does not work without it. */
why: string;
/** Where to get it, step by step. */
how: string;
/** Name of the project secret that closes the item. */
secret: string | null;
source: NeedSource;
/** Story key that declared it. */
story: string | null;
/** Ticked off by the owner (ISO). */
doneAt: string | null;
}
export interface ProductNeedView extends ProductNeed {
open: boolean;
}
export interface NeedInput {
title: string;
why?: string | null;
how?: string | null;
secret?: string | null;
}
export const MAX_NEEDS = 20;
const key = (projectId: number) => `product.needs:${projectId}`;
const clip = (s: string | null | undefined, n: number) => (s ?? "").replace(/\s+/g, " ").trim().slice(0, n);
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
const mergeKey = (n: Pick<ProductNeed, "title" | "secret">) => (n.secret ? `s:${n.secret}` : `t:${norm(n.title)}`);
async function stored(db: Db, projectId: number): Promise<ProductNeed[]> {
return (await getSetting<ProductNeed[]>(db, key(projectId))) ?? [];
}
/** The project's list with each item's state (open = the owner still has to act). */
export async function productNeeds(db: Db, projectId: number): Promise<ProductNeedView[]> {
const list = await stored(db, projectId);
if (!list.length) return [];
const have = new Set((await db.select({ name: projectSecrets.name }).from(projectSecrets).where(eq(projectSecrets.projectId, projectId))).map((r) => r.name));
return list.map((n) => ({ ...n, open: n.secret ? !have.has(n.secret) : !n.doneAt }));
}
export async function openNeeds(db: Db, projectId: number): Promise<ProductNeedView[]> {
return (await productNeeds(db, projectId)).filter((n) => n.open);
}
function clean(input: NeedInput): Pick<ProductNeed, "title" | "why" | "how" | "secret"> {
const title = clip(input.title, 120);
if (!title) throw new PeppaError("У пункта нет названия (title): что нужно дать, словами владельца");
const secret = input.secret?.trim() || null;
if (secret) {
const err = secretNameError(secret);
if (err) throw new PeppaError(err);
}
return { title, why: clip(input.why, 300), how: clip(input.how, 600), secret };
}
/**
* Adds items to the list (merging by secret name, else by title) and returns the ones that are
* new and still open — the caller tells the owner about those. With `replaceSource` the items
* of that source that have no secret and are not in `inputs` are dropped first: the product
* agent looks at the product afresh every time. Items the owner ticked off stay ticked.
*/
export async function declareNeeds(db: Db, projectId: number, inputs: NeedInput[], o: { source: NeedSource; story?: string | null; replaceSource?: boolean }): Promise<{ added: ProductNeedView[]; all: ProductNeedView[] }> {
const incoming = inputs.map(clean);
let list = await stored(db, projectId);
if (o.replaceSource) {
const keep = new Set(incoming.map(mergeKey));
list = list.filter((n) => n.source !== o.source || n.secret || n.doneAt || keep.has(mergeKey(n)));
}
const addedIds = new Set<string>();
for (const n of incoming) {
const cur = list.find((x) => mergeKey(x) === mergeKey(n));
if (cur) {
// The developer agent knows the exact wording and the secret's name: its text wins.
if (o.source === "agent" || cur.source === o.source) Object.assign(cur, { title: n.title, why: n.why || cur.why, how: n.how || cur.how });
continue;
}
if (list.length >= MAX_NEEDS) break;
const id = `n${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
list.push({ id, ...n, source: o.source, story: o.story ?? null, doneAt: null });
addedIds.add(id);
}
await setSetting(db, key(projectId), list);
const all = await productNeeds(db, projectId);
return { added: all.filter((n) => addedIds.has(n.id) && n.open), all };
}
/** The owner ticks an item without a secret off (or back on). */
export async function setNeedDone(db: Db, projectId: number, id: string, done: boolean, now = new Date()): Promise<void> {
const list = await stored(db, projectId);
const n = list.find((x) => x.id === id);
if (!n) throw new PeppaError("Такого пункта нет");
n.doneAt = done ? now.toISOString() : null;
await setSetting(db, key(projectId), list);
}
/** The owner removes an item that does not apply. */
export async function removeNeed(db: Db, projectId: number, id: string): Promise<void> {
const list = (await stored(db, projectId)).filter((x) => x.id !== id);
if (list.length) await setSetting(db, key(projectId), list);
else await deleteSetting(db, key(projectId));
}
/** «что дать и куда вставить» for a message to the owner, plain text. */
export function needsText(needs: ProductNeed[], webUrl: string, projectKey: string): string {
const lines = needs.map((n, i) => {
const parts = [`${i + 1}. ${n.title}${n.why ? ` — ${n.why}` : ""}`];
if (n.how) parts.push(` Где взять: ${n.how}`);
parts.push(n.secret ? " Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом." : " Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».");
return parts.join("\n");
});
return [...lines, "", `Карточка «Ваш продукт»: ${webUrl}/p/${projectKey}`, "Ключи хранятся зашифрованными, Пеппа сама передаст их продукту и перезапустит его."].join("\n");
}
/** One line for messages and the card: «нужно: Ключ Claude API, Аккаунт Stripe». */
export const needsLine = (needs: Pick<ProductNeed, "title">[]) => needs.map((n) => n.title).join(", ");
/** A line for «готово к ревью»: the story is done, but the product is not real yet ("" when it is). */
export async function demoNote(db: Db, projectId: number, projectKey: string, webUrl = process.env.PEPPA_WEB_URL ?? ""): Promise<string> {
const open = await openNeeds(db, projectId).catch(() => []);
return open.length ? `⚠️ Продукт пока работает в демо-режиме. Нужно от вас: ${needsLine(open)} — вставить можно в карточке «Ваш продукт»: ${webUrl}/p/${projectKey}` : "";
}

View File

@ -0,0 +1,208 @@
// PEP-112: the product agent accepts the work. After a deploy Peppa opens the product the way
// its user would (the text of its pages, screenshots of the stand), compares it with the stories
// that went in, and tells the owner in the project's discussion: what came out, how to use it
// step by step, what is not real yet (demo data, stubs) and what the owner has to give. What a
// user would not understand becomes a backlog story. This module is the pure part (state,
// prompt, parsing, page text); the model call and the page fetch are runner/product-review.ts.
import type { ProductNeedView } from "./product-needs.ts";
import { getSetting, setSetting, deleteSetting } from "./settings.ts";
import type { Db } from "@peppa/db";
/** The product agent's name on its messages (an AI agent, shown with the robot badge). */
export const PRODUCT_AGENT_NAME = "Продакт";
export const PRODUCT_REVIEW_MAX_STORIES = 3;
export const PRODUCT_REVIEW_MAX_PAGES = 4;
export const PRODUCT_PAGE_MAX_CHARS = 6000;
export interface ProductReview {
at: string;
env: "staging" | "prod";
sha: string;
url: string;
summary: string;
howto: string[];
notReal: string[];
/** Story keys filed by this review. */
filed: string[];
}
export interface PendingProductReview {
releaseId: number;
attempts: number;
}
const reviewKey = (projectId: number) => `product.review:${projectId}`;
const pendingKey = (projectId: number) => `product.review.pending:${projectId}`;
export const PRODUCT_REVIEW_PENDING_PREFIX = "product.review.pending:";
export const lastProductReview = (db: Db, projectId: number) => getSetting<ProductReview>(db, reviewKey(projectId));
export const saveProductReview = (db: Db, projectId: number, r: ProductReview) => setSetting(db, reviewKey(projectId), r);
export const pendingProductReview = (db: Db, projectId: number) => getSetting<PendingProductReview>(db, pendingKey(projectId));
export const setPendingProductReview = (db: Db, projectId: number, p: PendingProductReview | null) => (p ? setSetting(db, pendingKey(projectId), p) : deleteSetting(db, pendingKey(projectId)));
const restartKey = (projectId: number) => `product.restart:${projectId}`;
const RESTART_WINDOW_MS = 30 * 60_000;
/** Peppa restarted the deployed versions because the project's secrets changed. */
export const markSecretsRestart = (db: Db, projectId: number, now = Date.now()) => setSetting(db, restartKey(projectId), { at: now });
/**
* A healthy staging/prod release: should the product agent look at it? Once per commit and
* environment — except a restart after the secrets changed, when what was a demo may be real now.
*/
export async function queueProductReview(db: Db, projectId: number, rel: { id: number; env: string; sha: string }, now = Date.now()): Promise<boolean> {
if (rel.env !== "staging" && rel.env !== "prod") return false;
const last = await lastProductReview(db, projectId);
if (last && last.sha === rel.sha && last.env === rel.env) {
const restart = await getSetting<{ at: number }>(db, restartKey(projectId));
if (!restart || now - restart.at > RESTART_WINDOW_MS || Date.parse(last.at) > restart.at) return false;
}
await setPendingProductReview(db, projectId, { releaseId: rel.id, attempts: 0 });
return true;
}
// ── the product as its user sees it ───────────────────────────────────────────────
const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", laquo: "«", raquo: "»", mdash: "—", ndash: "–", hellip: "…" };
/** What a person reads on an HTML page: visible text, field placeholders and button labels. */
export function pageText(html: string, max = PRODUCT_PAGE_MAX_CHARS): string {
const attr = (tag: string, name: string) => new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i").exec(tag)?.slice(2).find((v) => v != null) ?? "";
const text = html
.replace(/<!--[\s\S]*?-->/g, " ")
.replace(/<(script|style|noscript|template|svg|head)\b[\s\S]*?<\/\1>/gi, (m, tag: string) => (tag.toLowerCase() === "head" ? ` ${/<title[^>]*>([\s\S]*?)<\/title>/i.exec(m)?.[1] ?? ""}\n` : " "))
.replace(/<(input|textarea|select)\b[^>]*>/gi, (tag) => {
if (/\stype\s*=\s*["']?hidden/i.test(tag)) return " ";
const label = attr(tag, "placeholder") || attr(tag, "aria-label") || attr(tag, "value") || attr(tag, "name");
return ` [поле: ${label || "без подписи"}] `;
})
.replace(/<img\b[^>]*>/gi, (tag) => (attr(tag, "alt") ? ` [картинка: ${attr(tag, "alt")}] ` : " "))
.replace(/<button\b[^>]*>([\s\S]*?)<\/button>/gi, (_m, inner: string) => ` [кнопка: ${inner.replace(/<[^>]+>/g, " ").trim()}] `)
.replace(/<\/(p|div|li|h[1-6]|tr|section|article|header|footer|form|label|ul|ol|table|main|nav)>|<br\s*\/?>/gi, "\n")
.replace(/<[^>]+>/g, " ")
.replace(/&#(\d+);/g, (_m, n: string) => String.fromCodePoint(Number(n)))
.replace(/&([a-z]+);/gi, (m, n: string) => ENTITIES[n.toLowerCase()] ?? m)
.replace(/[ \t\r\f\v]+/g, " ")
.split("\n")
.map((l) => l.trim())
.filter(Boolean)
.join("\n");
return text.length > max ? `${text.slice(0, max)}\n…(обрезано)` : text;
}
/** Same-site pages linked from a page (paths, no assets, no anchors), in order of appearance. */
export function pageLinks(html: string, max = PRODUCT_REVIEW_MAX_PAGES - 1): string[] {
const out: string[] = [];
for (const m of html.matchAll(/<a\b[^>]*\shref\s*=\s*["']([^"'#?]+)[^"']*["']/gi)) {
const href = m[1]!.trim();
if (!href.startsWith("/") || href.startsWith("//") || href === "/" || /\.(png|jpe?g|svg|css|js|ico|pdf|zip|xml|json|txt|webp|gif|woff2?)$/i.test(href)) continue;
if (/^\/(api|_next|static|assets|logout|auth\/logout)\b/i.test(href)) continue;
if (!out.includes(href)) out.push(href);
if (out.length >= max) break;
}
return out;
}
// ── prompt and answer ─────────────────────────────────────────────────────────────
export interface ProductReviewInput {
projectName: string;
/** «версия для проверки» / «рабочая версия». */
envLabel: string;
url: string;
stories: Array<{ key: string; title: string; description: string }>;
pages: Array<{ path: string; text: string }>;
/** Screenshot files in the working directory of the call. */
screenshots: string[];
needs: ProductNeedView[];
secretNames: string[];
/** Titles of the project's open stories — not to file the same thing twice. */
openStories: string[];
}
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}\n…(обрезано)` : s);
export function productReviewPrompt(i: ProductReviewInput): string {
return [
"Ты — продакт-менеджер софтвер-фабрики на приёмке. Агенты сделали и выкатили продукт. Владелец продукта — не программист. Посмотри на продукт глазами его пользователя и скажи владельцу, что получилось и что с этим делать. Ты ИИ-агент и не выдаёшь себя за человека.",
"1. summary — что получилось, 2–4 фразы: что продукт уже умеет для пользователя. Сверь со стори ниже: чего из обещанного на экране нет — скажи прямо.",
"2. howto — как этим пользоваться в жизни, по шагам (3–7 шагов): открыть адрес, что нажать, что получится. Только то, что реально есть на экране.",
"3. not_real — что пока не настоящее: демо-режим, вымышленные примеры, заглушки, «скоро», данные-образцы. Каждое — одной фразой простыми словами. Пусто, если всё настоящее.",
"4. needs — что нужно от владельца, чтобы заработало по-настоящему (ключ сервиса, аккаунт, реквизиты): title — что дать, why — что без этого не работает, how — где это взять, по шагам для непрограммиста. Не повторяй пункты из раздела «Уже объявлено». Пусто, если ничего не нужно.",
`5. stories — доработки (не больше ${PRODUCT_REVIEW_MAX_STORIES}): всё, что пользователь не поймёт или не должен видеть. Служебные поля на экране («токен», «ключ API», «ID», технические коды), жаргон, непонятные ошибки, пустые экраны без подсказки, обещанное в стори, но отсутствующее. title — что исправить; description — что должен увидеть пользователь и критерии приёмки списком. Не заводи то, что уже есть в «Открытых стори». Пусто, если придраться не к чему.`,
"Тон: коллега, а не помощник. Простые слова, без жаргона (PR, CI, API, деплой, env, токен — нельзя; «ключ сервиса», «версия для проверки» — можно). Не хвали, без восклицаний. Не выдумывай: чего нет в тексте страниц и на скриншотах — того нет.",
"",
`Продукт: ${i.projectName} — ${i.envLabel}, адрес ${i.url}`,
"",
"## Стори, которые вошли в эту версию",
i.stories.length ? i.stories.map((s) => `### ${s.key} «${s.title}»\n${clip(s.description.trim() || "(без описания)", 2500)}`).join("\n\n") : "(неизвестно — суди по самому продукту)",
"",
"## Что видит пользователь (текст страниц)",
...i.pages.map((p) => `### Страница ${p.path}\n${p.text || "(страница пустая или рисуется скриптом — смотри скриншоты)"}`),
...(i.screenshots.length ? ["", "## Скриншоты", `Прочитай файлы инструментом Read: ${i.screenshots.join(", ")}`] : []),
"",
"## Уже объявлено: что нужно от владельца",
i.needs.length ? i.needs.map((n) => `- ${n.title}${n.why ? ` — ${n.why}` : ""} (${n.open ? "ещё не дано" : "уже дано"})`).join("\n") : "(ничего)",
...(i.secretNames.length ? ["", `Ключи, которые владелец уже дал: ${i.secretNames.join(", ")}`] : []),
"",
"## Открытые стори проекта",
i.openStories.length ? i.openStories.map((t) => `- ${t}`).join("\n") : "(нет)",
"",
'Ответь ОДНОЙ строкой JSON без пояснений: {"summary":"…","howto":["…"],"not_real":["…"],"needs":[{"title":"…","why":"…","how":"…"}],"stories":[{"title":"…","description":"…"}]}',
].join("\n");
}
export interface ProductReviewReply {
summary: string;
howto: string[];
notReal: string[];
needs: Array<{ title: string; why: string; how: string }>;
stories: Array<{ title: string; description: string }>;
}
const str = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
const list = (v: unknown, max: number, each = 400) => (Array.isArray(v) ? v.map((x) => str(x, each)).filter(Boolean).slice(0, max) : []);
/** The model's answer; null when it is not the JSON asked for. */
export function parseProductReview(text: string): ProductReviewReply | null {
const m = /\{[\s\S]*\}/.exec(text);
if (!m) return null;
try {
const o = JSON.parse(m[0]) as Record<string, unknown>;
const summary = str(o.summary, 1500);
if (!summary) return null;
const objs = (v: unknown) => (Array.isArray(v) ? (v as Array<Record<string, unknown>>).filter((x) => x && typeof x === "object") : []);
return {
summary,
howto: list(o.howto, 8),
notReal: list(o.not_real ?? o.notReal, 8),
needs: objs(o.needs)
.map((n) => ({ title: str(n.title, 120), why: str(n.why, 300), how: str(n.how, 600) }))
.filter((n) => n.title)
.slice(0, 6),
stories: objs(o.stories)
.map((s) => ({ title: str(s.title, 120), description: str(s.description, 6000) }))
.filter((s) => s.title.length >= 3)
.slice(0, PRODUCT_REVIEW_MAX_STORIES),
};
} catch {
return null;
}
}
/** The product agent's message to the owner in the project's discussion. */
export function productReviewMessage(r: ProductReviewReply, o: { envLabel: string; url: string; openNeeds: ProductNeedView[]; filed: string[]; webUrl: string; projectKey: string }): string {
const steps = (items: string[]) => items.map((x, i) => `${i + 1}. ${x}`).join("\n");
const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n");
return [
`Посмотрел ${o.envLabel}: ${o.url}`,
r.summary,
...(r.howto.length ? [`Как пользоваться:\n${steps(r.howto)}`] : []),
...(r.notReal.length ? [`Пока не настоящее:\n${bullets(r.notReal)}`] : []),
...(o.openNeeds.length
? [
`Чтобы заработало по-настоящему, нужно от вас:\n${bullets(o.openNeeds.map((n) => `${n.title}${n.why ? ` — ${n.why}` : ""}${n.how ? `. Где взять: ${n.how}` : ""}`))}\nВставить или отметить «Сделано» — в карточке «Ваш продукт»: ${o.webUrl}/p/${o.projectKey}`,
]
: []),
...(o.filed.length ? [`Завёл доработки в бэклог:\n${bullets(o.filed)}`] : []),
].join("\n\n");
}

View File

@ -6,6 +6,7 @@ import { and, asc, eq, inArray } from "drizzle-orm";
import { logEvent } from "./audit.ts";
import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { setSetting } from "./settings.ts";
import { projectForUser } from "./users.ts";
export const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
@ -16,7 +17,16 @@ export const MASK = "••••";
/** Env the runner or the shell sets itself: a project secret must not shadow it. */
const RESERVED = new Set(["PATH", "HOME", "USER", "SHELL", "PWD", "TERM", "TMPDIR", "LANG", "NODE_OPTIONS", "CODEX_HOME", "GIT_DIR", "GIT_WORK_TREE"]);
const RESERVED_PREFIX = ["PEPPA_", "CLAUDE_", "ANTHROPIC_", "OPENCODE_", "LD_", "DYLD_", "TMUX"];
const RESERVED_PREFIX = ["PEPPA_", "LD_", "DYLD_", "TMUX"];
/**
* PEP-112: names the agents' own CLIs read. A product may need them (its own Claude API key),
* so they are stored and go to the deployed product, but never into an agent session — there
* they would replace the agent's own sign-in.
*/
const PRODUCT_ONLY_PREFIX = ["CLAUDE_", "ANTHROPIC_", "OPENCODE_"];
export const productOnlySecret = (name: string) => PRODUCT_ONLY_PREFIX.some((p) => name.startsWith(p));
/** `settings` key: when the project's secrets last changed and deployed versions need a restart. */
export const secretsChangedKey = (projectId: number) => `product.redeploy:${projectId}`;
export function secretNameError(name: string): string | null {
if (!SECRET_NAME_RE.test(name)) return "Имя секрета: A–Z, 0–9 и _, с буквы";
@ -57,6 +67,7 @@ export async function setProjectSecret(db: Db, userId: number, projectId: number
if (existing) await db.update(projectSecrets).set({ valueEnc, updatedBy: userId, updatedAt: new Date() }).where(eq(projectSecrets.id, existing.id));
else await db.insert(projectSecrets).values({ projectId, name, valueEnc, createdBy: userId, updatedBy: userId });
await logEvent(db, { projectId, type: "secret_set", payload: { name, replaced: !!existing } });
await setSetting(db, secretsChangedKey(projectId), { at: Date.now() });
return (await listProjectSecrets(db, projectId)).find((s) => s.name === name)!;
}
@ -65,17 +76,20 @@ export async function deleteProjectSecret(db: Db, userId: number, projectId: num
const gone = await db.delete(projectSecrets).where(and(eq(projectSecrets.projectId, projectId), eq(projectSecrets.name, name))).returning({ id: projectSecrets.id });
if (!gone.length) throw new PeppaError(`Секрета ${name} нет`);
await logEvent(db, { projectId, type: "secret_deleted", payload: { name } });
await setSetting(db, secretsChangedKey(projectId), { at: Date.now() });
}
/**
* name → value for an agent session (runner only). Unreadable values (wrong key) are
* skipped and reported, so one broken secret never blocks a session.
* name → value for an agent session or for a deploy of the product (runner only). Unreadable
* values (wrong key) are skipped and reported, so one broken secret never blocks a session.
* PEP-112: product-only names (ANTHROPIC_*, …) are left out of agent sessions.
*/
export async function projectSecretEnv(db: Db, projectId: number): Promise<{ env: Record<string, string>; unreadable: string[] }> {
export async function projectSecretEnv(db: Db, projectId: number, target: "agent" | "deploy" = "agent"): Promise<{ env: Record<string, string>; unreadable: string[] }> {
const rows = await db.select().from(projectSecrets).where(eq(projectSecrets.projectId, projectId)).orderBy(asc(projectSecrets.name));
const env: Record<string, string> = {};
const unreadable: string[] = [];
for (const r of rows) {
if (target === "agent" && productOnlySecret(r.name)) continue;
try {
env[r.name] = decrypt(r.valueEnc);
} catch {
@ -102,7 +116,7 @@ export type Masker = (text: string) => string;
/** A masker over the project's current secret values (empty project → identity). */
export async function projectSecretMasker(db: Db, projectId: number): Promise<Masker> {
// Multi-line values (PEM keys) reach the terminal line by line: mask each long line too.
const values = Object.values((await projectSecretEnv(db, projectId)).env)
const values = Object.values((await projectSecretEnv(db, projectId, "deploy")).env)
.flatMap((v) => (v.includes("\n") ? [v, ...v.split(/\r?\n/).filter((l) => l.trim().length >= 8)] : [v]))
.filter((v) => v.length >= MASK_MIN_LENGTH)
.sort((a, b) => b.length - a.length);

View File

@ -12,6 +12,7 @@ import { getAutonomy, type AutonomySettings } from "./autonomy.ts";
import { reviewPreview, type ReviewPreview } from "./preview.ts";
import { blockersOf, dependentsOf, type Blocker } from "./deps.ts";
import { taskBudgetView, type TaskBudgetView } from "./budgets.ts";
import { productNeeds, type ProductNeedView } from "./product-needs.ts";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@ -243,6 +244,8 @@ export interface TaskDetails {
/** PEP-42: stories this one waits for, and stories that wait for it. */
blockers: Blocker[];
dependents: Array<{ id: number; key: string; title: string; status: TaskStatus }>;
/** PEP-112: what the owner has to give before the product works for real. */
needs?: ProductNeedView[];
/** PEP-43/5: what the story spent and its budget. */
budget: TaskBudgetView;
}
@ -289,7 +292,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
.orderBy(desc(events.id))
.limit(20);
const incident = await incidentForTask(db, ref.task.id);
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref), budget: await taskBudgetView(db, ref.task) };
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref), budget: await taskBudgetView(db, ref.task), needs: await productNeeds(db, ref.project.id) };
}
export interface NewQuestion {

View File

@ -32,9 +32,13 @@ import {
memoryContext,
rememberFact,
replaceMemory,
declareNeeds,
ensureProjectChat,
needsText,
productOnlySecret,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { requestReview, reviewGate, storyBranch } from "@peppa/runner";
import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
@ -286,7 +290,40 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
const p = sessionId ? await getProject(db, (await getSession(db, sessionId)).projectKey) : await projectOrDefault();
const rows = await listProjectSecrets(db, p.id);
if (!rows.length) return `${p.key} has no secrets.`;
return [`Secrets of ${p.key} (in your env):`, ...rows.map((r) => `- ${r.name}`)].join("\n");
// PEP-112: ANTHROPIC_*/CLAUDE_*/OPENCODE_* go to the deployed product only.
return [`Secrets of ${p.key} (in your env; every one of them also reaches the deployed product as env of the same name):`, ...rows.map((r) => `- ${r.name}${productOnlySecret(r.name) ? " (deployed product only — not in your env)" : ""}`)].join("\n");
},
);
tool(
"declare_needs",
"Declare what the product's OWNER must give before the product works for real instead of on mocks/demo data: an API key, an account, credentials. Call it BEFORE moving the story to review whenever the story needs something only the owner has. The owner (a product manager, not a programmer) gets the list in plain words in the project chat and on the «Ваш продукт» card, with a field to paste each key; an item with `secret` closes itself once the owner stores that secret, and Peppa hands all project secrets to the deployed product as env vars of the same name and restarts it. Write title/why/how in the owner's language, no jargon. Items add up across stories (same secret or title = same item). Returns the whole list with states.",
{
task: taskArg.optional().describe("The story that needs it (for the record)"),
needs: z
.array(
z.object({
title: z.string().describe("What to give, in the owner's words: «Ключ Claude API»"),
why: z.string().optional().describe("What does not work without it, plainly: «без него ответы — вымышленные примеры»"),
how: z.string().optional().describe("Where to get it, step by step for a non-programmer"),
secret: z.string().optional().describe("Env name the product reads it from (A–Z, 0–9, _), e.g. ANTHROPIC_API_KEY. Omit for things that are not a key (the owner ticks them off)"),
}),
)
.min(1)
.max(10),
},
async ({ task, needs }) => {
const ref = task ? await resolve(task) : null;
const session = sessionId ? await getSession(db, sessionId) : null;
const p = ref?.project ?? (session ? await getProject(db, session.projectKey) : await projectOrDefault());
const { added, all } = await declareNeeds(db, p.id, needs, { source: "agent", story: ref?.key ?? null });
if (added.length) {
const chat = await ensureProjectChat(db, p.id);
const text = ["Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:", "", needsText(added, process.env.PEPPA_WEB_URL ?? "", p.key)].join("\n");
await sayInDiscussion(db, p, chat.id, text, session?.agentName ? `Агент ${session.agentName}` : "Агент");
}
const line = (n: (typeof all)[number]) => `- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}`;
return [`Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].join("\n");
},
);

View File

@ -47,6 +47,12 @@ export function formatTask(d: TaskDetails): string {
lines.push("", `- [${q.kind} #${q.id}] ${q.text}`, q.answer ? ` - Ответ (${q.answeredVia}): ${q.answer}` : " - _ожидает ответа_");
}
}
// PEP-112: what the owner still has to give before the product is real.
if (d.needs?.length) {
lines.push("", "## Чтобы продукт работал по-настоящему (declare_needs)");
for (const n of d.needs) lines.push(`- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}${n.story ? ` · ${n.story}` : ""}`);
if (d.needs.some((n) => n.open)) lines.push("", "Пока пункт открыт, продукт работает на моке — не называй стори готовой молча.");
}
// PEP-32: the PM's comments on the story — instructions to take into account.
if (d.comments?.length) {
lines.push("", "## Комментарии PM");

View File

@ -78,11 +78,15 @@ export async function analystChatTick(db: Db, opts: AnalystChatOptions = {}): Pr
if (opts.wait) await Promise.all(jobs);
}
async function say(db: Db, project: Project, chatId: number, text: string, agent = true) {
const m = await addChatMessage(db, agent ? { chatId, kind: "user", authorKind: "agent", authorLogin: ANALYST_NAME, text } : { chatId, kind: "user", authorKind: "system", text });
/**
* A message in the project's discussion from an AI role (`author`: «Аналитик», «Продакт», an
* agent's name) or, without an author, a system note. An agent's message also reaches the
* project's people in their own Telegram bot / browser.
*/
export async function sayInDiscussion(db: Db, project: Project, chatId: number, text: string, author: string | null = ANALYST_NAME) {
const m = await addChatMessage(db, author ? { chatId, kind: "user", authorKind: "agent", authorLogin: author, text } : { chatId, kind: "user", authorKind: "system", text });
await notify(db, { type: "chat_message", messageId: m?.id ?? 0 });
// The answer reaches the project's people in their own Telegram bot / browser too.
if (agent && m) {
if (author && m) {
const short = text.length > 800 ? `${text.slice(0, 800)}…` : text;
for (const u of await projectAudience(db, project.id)) {
await deliverToUser(db, u, {
@ -90,14 +94,16 @@ async function say(db: Db, project: Project, chatId: number, text: string, agent
projectId: project.id,
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
pushKey: `chat:m${m.id}:u${u.id}`,
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${ANALYST_NAME}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: `${project.name}: ${ANALYST_NAME}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` },
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${esc(author)}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: `${project.name}: ${author}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` },
}).catch(() => null);
}
}
return m;
}
const say = (db: Db, project: Project, chatId: number, text: string, agent = true) => sayInDiscussion(db, project, chatId, text, agent ? ANALYST_NAME : null);
async function answer(db: Db, project: Project, chatId: number, upTo: number, log: (m: string) => void): Promise<void> {
const history = await discussionHistory(db, chatId);
const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history));

View File

@ -6,8 +6,10 @@ import {
giteaForBot,
listSessions,
listTasks,
logEvent,
PeppaError,
prGate,
projectSecretEnv,
pipelineChanges,
runLink,
taskForCheck,
@ -177,6 +179,16 @@ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ statu
});
return { status: 200, body: { ok: true, release: rel.id, status: rel.status } };
}
if (req.event === "deploy-env") {
// PEP-112: the deploy step asks for the project's secrets to hand them to the product's
// container. Signed like every report; a stale request (replayed) gets nothing.
const ts = typeof payload.ts === "number" ? payload.ts * 1000 : 0;
if (Math.abs(Date.now() - ts) > 10 * 60_000) return { status: 400, body: { error: "stale request" } };
const { env } = await projectSecretEnv(db, project.id, "deploy");
const names = Object.keys(env);
if (names.length) await logEvent(db, { projectId: project.id, type: "secrets_deployed", payload: { names, env: String(payload.env ?? "") } });
return { status: 200, body: { ok: true, env } };
}
if (req.event === "screenshots") {
if (typeof payload.sha !== "string" || !Array.isArray(payload.shots)) return { status: 400, body: { error: "bad screenshots report" } };
const out = await recordScreenshots(db, project, {

View File

@ -2,7 +2,7 @@
// subscription of the project's pool (PEP-67). Used by the incident triager (PEP-58) and the
// reviewer agent (PEP-26); tests point `bin` at mock-triage / mock-reviewer.
import { spawn } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { claudeTokenForProject, mayUseMachineLogin, type Project } from "@peppa/core";
@ -16,6 +16,11 @@ export interface ClaudePrintOptions {
timeoutMs: number;
/** For error messages: "триажёр", "ревьюер". */
who: string;
/**
* PEP-112: files copied into the (otherwise empty) working directory under these names; the
* CLI then may read them (`Read` only, a few turns) — screenshots for the product agent.
*/
files?: Array<{ name: string; path: string }>;
}
export type ClaudePrintResult = { ok: true; text: string } | { ok: false; error: string };
@ -41,8 +46,11 @@ export async function claudePrint(db: Db, project: Pick<Project, "id">, o: Claud
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
try {
const files = (o.files ?? []).filter((f) => /^[\w.-]+$/.test(f.name));
for (const f of files) copyFileSync(f.path, join(cwd, f.name));
const turns = files.length ? ["--max-turns", String(files.length + 2), "--allowedTools", "Read"] : ["--max-turns", "1"];
const out = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
const child = spawn(o.bin, ["-p", "--output-format", "json", "--max-turns", "1", "--model", o.model], {
const child = spawn(o.bin, ["-p", "--output-format", "json", ...turns, "--model", o.model], {
cwd,
env: { ...process.env, ...(token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}) },
stdio: ["pipe", "pipe", "pipe"],

View File

@ -2,8 +2,8 @@
// the host (docker compose behind Traefik, health check, rollback) and reports each step
// here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a
// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API).
import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type GiteaClient, type Project, type Question } from "@peppa/core";
import { projects, questions, releases, type Db } from "@peppa/db";
import { answerQuestion, askPmProject, deleteSetting, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core";
import { projects, questions, releases, settings, type Db } from "@peppa/db";
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { deployPlatform, isPlatform } from "./platform-release.ts";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
@ -89,7 +89,8 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
status: r.status,
reason: r.reason ?? null,
runUrl: r.runUrl ?? open?.runUrl ?? null,
logTail: r.logTail ?? open?.logTail ?? null,
// PEP-112: the product's own output may print a key — never keep it readable.
logTail: r.logTail ? (await projectSecretMasker(db, project.id))(r.logTail) : (open?.logTail ?? null),
};
let rel: Release;
if (r.status === "removed") {
@ -105,6 +106,8 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
? await db.update(releases).set(values).where(eq(releases.id, open.id)).returning()
: await db.insert(releases).values({ projectId: project.id, env: r.env, sha: r.sha, ...values }).returning();
await notifyRelease(db, project, rel!);
// PEP-112: the product agent looks at what was deployed (not at Peppa itself).
if (rel!.status === "healthy" && !isPlatform(project)) await queueProductReview(db, project.id, rel!);
return rel!;
}
@ -117,6 +120,13 @@ async function notifyRelease(db: Db, project: Project, rel: Release) {
kind: "attention",
text: `❌ ${project.name}: релиз ${short(rel.sha)} в ${rel.env} не прошёл${back}.\nПричина: ${rel.reason ?? "неизвестна"}${log ? `\nЛог: ${log}` : ""}`,
});
} else if (rel.status === "healthy" && rel.env !== "preview" && rel.previousSha === rel.sha) {
// PEP-112: the same version started again (the project's secrets changed) — not a new one.
const open = await openNeeds(db, project.id);
await askPmProject(db, project, {
kind: "attention",
text: `🔑 ${project.name}: ${rel.env === "prod" ? "ваш продукт" : "версия для проверки"} перезапущен${rel.env === "prod" ? "" : "а"} с новыми настройками${rel.host ? `\nОткрыть: https://${rel.host}` : ""}${open.length ? `\nЕщё работает в демо-режиме, нужно: ${needsLine(open)}` : ""}`,
});
} else if (rel.status === "healthy" && rel.env === "staging") {
await expireProdOffers(db, project.id);
await askPmProject(db, project, {
@ -164,6 +174,56 @@ export async function deployProd(db: Db, project: Project, by: string, client?:
return rel!;
}
const REDEPLOY_PREFIX = "product.redeploy:";
/**
* PEP-112: the project's secrets changed → its deployed versions start again with the new
* environment. Peppa tags the commit each healthy version runs (`deploy-prod-*` /
* `deploy-staging-*`), the project's workflow redeploys it; the image is already built. Waits
* for a quiet spell so a series of edits makes one restart. Returns the tags it created.
*/
export async function productRedeployTick(db: Db, o: { now?: Date; client?: GiteaClient; log?: (m: string) => void } = {}): Promise<string[]> {
if (process.env.PEPPA_SECRETS_REDEPLOY === "off") return [];
const now = (o.now ?? new Date()).getTime();
const quietMs = Math.max(0, Number(process.env.PEPPA_SECRETS_REDEPLOY_DELAY_SEC ?? 120)) * 1000;
const created: string[] = [];
const rows = await db.select().from(settings).where(sql`${settings.key} like ${`${REDEPLOY_PREFIX}%`}`);
for (const row of rows) {
const at = (row.value as { at?: number } | null)?.at ?? 0;
if (now - at < quietMs) continue;
await deleteSetting(db, row.key);
const [project] = await db.select().from(projects).where(eq(projects.id, Number(row.key.slice(REDEPLOY_PREFIX.length))));
if (!project || isPlatform(project)) continue;
const current = await currentReleases(db, project.id);
const stamp = new Date(now).toISOString().replace(/\D/g, "").slice(0, 17);
const tags: string[] = [];
for (const env of ["staging", "prod"] as const) {
const rel = current[env];
if (!rel) continue;
const [running] = await db.select({ id: releases.id }).from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, env), eq(releases.status, "deploying"))).limit(1);
if (running) continue; // that deploy picks the new secrets up itself
const tag = `deploy-${env}-${stamp}`;
try {
await (o.client ?? giteaForBot()).createTag(project.giteaOwner, project.giteaRepo, tag, rel.sha, "Перезапуск: изменились секреты проекта");
tags.push(tag);
} catch (e) {
o.log?.(`secrets redeploy ${project.key} ${env}: ${(e as Error).message}`);
}
}
if (tags.length) {
await markSecretsRestart(db, project.id, now);
await logEvent(db, { projectId: project.id, type: "secrets_redeploy", payload: { tags } });
created.push(...tags);
}
}
return created;
}
/** Local PNG files of a release's screenshots (PEP-112: the product agent reads them). */
export function releaseScreenshotFiles(rel: Pick<Release, "projectId" | "screenshots">): string[] {
return rel.screenshots.filter((s) => /^r\d+-\d+\.png$/.test(s.file)).map((s) => join(screenshotDir(rel.projectId), s.file));
}
/** The PM pressed "deploy to prod" on a "staging updated" message (any channel). */
export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: string): Promise<boolean> {
if (q.taskId || q.sessionId || !(q.options ?? []).includes(PROD_OPTION) || answer.trim() !== PROD_OPTION) return false;

View File

@ -25,6 +25,7 @@ import {
reviewNote,
reviewPreview,
reviewPreviewNote,
demoNote,
reviewRejections,
getSession,
logSessionEvent,
@ -232,7 +233,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
const note = settings.enabled ? reviewNote(await latestReview(db, task.id), (await reviewRejections(db, task.id)) >= settings.maxIterations) : "";
// PEP-44: the preview stand, the diff and the checks — the PM reviews without a terminal.
const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId));
const look = project ? reviewPreviewNote(await reviewPreview(db, { project, task, key: s.taskKey ?? "" }).catch(() => ({ previewUrl: null, releaseId: null, sha: null, diffUrl: null, checks: "", screenshots: [], issueUrl: null }))) : "";
const look = project ? [reviewPreviewNote(await reviewPreview(db, { project, task, key: s.taskKey ?? "" }).catch(() => ({ previewUrl: null, releaseId: null, sha: null, diffUrl: null, checks: "", screenshots: [], issueUrl: null }))), await demoNote(db, project.id, project.key)].filter(Boolean).join("\n") : "";
await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${note ? `${note}\n\n` : ""}${text ?? ""}`.trim()));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;

View File

@ -15,6 +15,7 @@ export * from "./ci.ts";
export * from "./transfer.ts";
export * from "./incidents.ts";
export * from "./analyst-chat.ts";
export * from "./product-review.ts";
export * from "./triage.ts";
export * from "./ci-feedback.ts";
export * from "./deploy.ts";

View File

@ -0,0 +1,170 @@
// PEP-112: the product agent accepts the work. A healthy deploy (the version to check or the
// working one) leaves a mark; the watchdog calls `productReviewTick`, which opens the product
// like its user (page text, screenshots of the stories' stands), asks the model on the
// project's own subscription (like the intake roles), and tells the owner in the project's
// discussion what came out, how to use it, what is not real yet and what they have to give.
// What the owner must give goes to the «чтобы заработало по-настоящему» list; what a user would
// not understand becomes backlog stories.
import {
createTask,
declareNeeds,
ensureProjectChat,
getIntakeSettings,
pageText,
listProjectSecrets,
openNeeds,
pageLinks,
parseProductReview,
PRODUCT_AGENT_NAME,
PRODUCT_REVIEW_MAX_PAGES,
PRODUCT_REVIEW_PENDING_PREFIX,
productNeeds,
productReviewMessage,
productReviewPrompt,
resolveTask,
saveProductReview,
setIntakeState,
setPendingProductReview,
taskPrNumber,
type PendingProductReview,
type Project,
} from "@peppa/core";
import { projects, releases, settings, tasks, type Db } from "@peppa/db";
import { and, desc, eq, isNull, ne, sql } from "drizzle-orm";
import { sayInDiscussion } from "./analyst-chat.ts";
import { claudePrint } from "./claude-print.ts";
import { releaseScreenshotFiles, type Release } from "./deploy.ts";
const inFlight = new Set<number>();
const MAX_ATTEMPTS = 2;
const MAX_SHOTS = 3;
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
export interface ProductReviewOptions {
log?: (m: string) => void;
/** Wait for the model calls (tests); the watchdog lets them run in the background. */
wait?: boolean;
}
/** Deploys the product agent has not looked at yet. */
export async function productReviewTick(db: Db, opts: ProductReviewOptions = {}): Promise<void> {
if (process.env.PEPPA_PRODUCT_REVIEW === "off") return;
const log = opts.log ?? (() => {});
const jobs: Promise<void>[] = [];
const rows = await db.select().from(settings).where(sql`${settings.key} like ${`${PRODUCT_REVIEW_PENDING_PREFIX}%`}`);
for (const row of rows) {
const projectId = Number(row.key.slice(PRODUCT_REVIEW_PENDING_PREFIX.length));
if (inFlight.has(projectId)) continue;
const pending = row.value as PendingProductReview;
const [project] = await db.select().from(projects).where(eq(projects.id, projectId));
const [rel] = project ? await db.select().from(releases).where(eq(releases.id, pending.releaseId)) : [];
// The roles are off, the release is gone or no longer what runs: nothing to accept.
if (!project || !rel?.host || rel.status !== "healthy" || !(await getIntakeSettings(db, projectId)).enabled) {
await setPendingProductReview(db, projectId, null);
continue;
}
inFlight.add(projectId);
jobs.push(
review(db, project, rel, pending, log)
.catch(async (e) => {
log(`product review ${project.key}: ${(e as Error).message}`);
await setPendingProductReview(db, projectId, null);
})
.finally(() => inFlight.delete(projectId)),
);
}
if (opts.wait) await Promise.all(jobs);
}
async function fetchPage(url: string): Promise<string | null> {
try {
const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(15_000), headers: { accept: "text/html,*/*", "user-agent": "peppa-product-review" } });
if (!res.ok) return null;
return (await res.text()).slice(0, 400_000);
} catch {
return null;
}
}
/** Screenshots the CI took of the stands of the stories in this release (PEP-44), newest first. */
async function storyScreenshots(db: Db, project: Project, prUrls: Array<string | null>): Promise<string[]> {
const out: string[] = [];
for (const pr of prUrls.map((u) => taskPrNumber(project, u)).filter((n): n is number => n != null).reverse()) {
const previews = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, pr))).orderBy(desc(releases.id)).limit(5);
const withShots = previews.find((r) => r.screenshots.length);
if (withShots) out.push(...releaseScreenshotFiles(withShots));
if (out.length >= MAX_SHOTS) break;
}
return out.slice(0, MAX_SHOTS);
}
async function review(db: Db, project: Project, rel: Release, pending: PendingProductReview, log: (m: string) => void): Promise<void> {
// One more try later, then give up quietly: an acceptance that failed must not make noise.
const retry = async (why: string) => {
const attempts = pending.attempts + 1;
await setPendingProductReview(db, project.id, attempts >= MAX_ATTEMPTS ? null : { ...pending, attempts });
log(`product review ${project.key}: ${why}${attempts >= MAX_ATTEMPTS ? " — пропущено" : " — повтор"}`);
};
const url = `https://${rel.host}`;
// Tests (and a stand reachable only from inside) open the product at another base.
const base = (process.env.PEPPA_PRODUCT_FETCH_BASE ?? url).replace(/\/$/, "");
const home = await fetchPage(`${base}/`);
if (home === null) return retry(`продукт не открылся (${url})`);
const pages = [{ path: "/", text: pageText(home) }];
for (const path of pageLinks(home, PRODUCT_REVIEW_MAX_PAGES - 1)) {
const html = await fetchPage(`${base}${path}`);
if (html !== null) pages.push({ path, text: pageText(html) });
}
const stories: Array<{ key: string; title: string; description: string; prUrl: string | null }> = [];
for (const key of rel.tasks.slice(-8)) {
const ref = await resolveTask(db, key, project.key).catch(() => null);
if (ref && ref.project.id === project.id) stories.push({ key: ref.key, title: ref.task.title, description: ref.task.description ?? "", prUrl: ref.task.prUrl });
}
const shots = await storyScreenshots(db, project, stories.map((s) => s.prUrl));
const files = shots.map((path, i) => ({ name: `screenshot-${i + 1}.png`, path }));
const all = await db.select({ title: tasks.title, status: tasks.status }).from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt), ne(tasks.status, "done")));
const envLabel = rel.env === "prod" ? "рабочая версия (открыта для всех)" : "версия для проверки";
const out = await claudePrint(db, project, {
bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
model: process.env.PEPPA_PRODUCT_REVIEW_MODEL ?? process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
who: "продакт",
files,
prompt: productReviewPrompt({
projectName: project.name,
envLabel,
url,
stories,
pages,
screenshots: files.map((f) => f.name),
needs: await productNeeds(db, project.id),
secretNames: (await listProjectSecrets(db, project.id)).map((s) => s.name),
openStories: all.map((t) => t.title),
}),
});
if (!out.ok) return retry(out.error);
const reply = parseProductReview(out.text);
if (!reply) return retry("ответ не по форме");
// Dealt with from here on: whatever fails below is not retried into a second message.
await setPendingProductReview(db, project.id, null);
await declareNeeds(db, project.id, reply.needs, { source: "product", replaceSource: true });
const known = new Set((await db.select({ title: tasks.title }).from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt)))).map((t) => norm(t.title)));
const filed: string[] = [];
for (const s of reply.stories) {
if (known.has(norm(s.title))) continue;
known.add(norm(s.title));
const description = `${s.description}\n\n_Заведено продакт-агентом на приёмке: ${envLabel}, ${url}._`;
const ref = await createTask(db, { projectId: project.id, title: s.title, description });
// Already formulated: «продакт» and «аналитик» of the intake skip it.
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена продакт-агентом на приёмке" });
filed.push(`${ref.key} «${s.title}»`);
}
const stillOpen = await openNeeds(db, project.id);
await saveProductReview(db, project.id, { at: new Date().toISOString(), env: rel.env as "staging" | "prod", sha: rel.sha, url, summary: reply.summary, howto: reply.howto, notReal: reply.notReal, filed: filed.map((f) => f.split(" ")[0]!) });
const chat = await ensureProjectChat(db, project.id);
await sayInDiscussion(db, project, chat.id, productReviewMessage(reply, { envLabel: rel.env === "prod" ? "рабочую версию" : "версию для проверки", url, openNeeds: stillOpen, filed, webUrl: process.env.PEPPA_WEB_URL ?? "", projectKey: project.key }), PRODUCT_AGENT_NAME);
log(`product review ${project.key}: ${rel.env} ${rel.sha.slice(0, 7)} — needs ${stillOpen.length}, stories ${filed.length}`);
}

View File

@ -18,6 +18,7 @@ import {
reviewNote,
reviewPreview,
reviewPreviewNote,
demoNote,
reviewRejections,
reviewsToRun,
taskPrNumber,
@ -211,7 +212,7 @@ export async function processReview(db: Db, id: number, gitea: GiteaClient = git
}
await updateTask(db, fresh, { status: "review" });
const look = reviewPreviewNote(await reviewPreview(db, fresh));
const look = [reviewPreviewNote(await reviewPreview(db, fresh)), await demoNote(db, fresh.project.id, fresh.project.key)].filter(Boolean).join("\n");
const msg = `✅ Стори ${fresh.key} готова к ревью${fresh.task.prUrl ? ` · PR: ${fresh.task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${reviewNote(review)}`.slice(0, 3500);
const [s] = sessionId ? await listSessions(db, { active: true, taskId: fresh.task.id }) : [];
// Still in the turn that asked for review: its Stop hook sends "ready for review" with this

View File

@ -38,6 +38,8 @@ import { autonomyTick } from "./autonomy.ts";
import { intakeTick } from "./intake.ts";
import { storyRefineTick } from "./story-refine.ts";
import { analystChatTick } from "./analyst-chat.ts";
import { productReviewTick } from "./product-review.ts";
import { productRedeployTick } from "./deploy.ts";
import { budgetTick } from "./budgets.ts";
import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
import { serveRunnerCommands, type RunnerService } from "./runner-service.ts";
@ -99,6 +101,9 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
// PEP-110: the analyst answers people in the projects' discussions.
await analystChatTick(db, { log }).catch(failed(db, log, "analyst chat"));
// PEP-112: changed secrets restart the deployed product; the product agent accepts each deploy.
await productRedeployTick(db, { now: opts.now, log }).catch(failed(db, log, "secrets redeploy"));
await productReviewTick(db, { log }).catch(failed(db, log, "product review"));
// Errors of running products (PEP-58): Bugsink poll + incident policies.
await incidentTick(db, { now: opts.now, log }).catch(failed(db, log, "incidents"));
// Daily digest at each user's time (PEP-29); a no-op outside their window.

View File

@ -83,8 +83,9 @@ case "$1" in
[[ -n "${MOCK_DOCKER_BUILD_FAIL:-}" ]] && { echo "mock build failed" >&2; exit 1; }
shift; while [[ $# -gt 0 ]]; do [[ $1 == -t ]] && { echo "$2" >> "$st/images"; break; }; shift; done
echo "Successfully built" ;;
compose) # docker compose -p <project> -f <file> <up|down|run> ...
shift; project=""; while [[ $# -gt 0 ]]; do case "$1" in -p) project="$2"; shift 2 ;; -f) shift 2 ;; *) break ;; esac; done
compose) # docker compose -p <project> -f <file> [-f <override>] <up|down|run> ...
# PEP-112: the override with the project's secrets is kept as env-<project>.json.
shift; project=""; while [[ $# -gt 0 ]]; do case "$1" in -p) project="$2"; shift 2 ;; -f) [[ "$2" == *peppa-env.* ]] && cp "$2" "$st/env-$project.json"; shift 2 ;; *) break ;; esac; done
svc="${MOCK_DOCKER_SERVICE:-web}"
case "$1" in
up) grep -qxF "$IMAGE" "$st/images" || { echo "pull access denied for $IMAGE" >&2; exit 1; }

View File

@ -5,9 +5,11 @@
// assumptions[], questions[{q, default}], comment}, "garbage": false, "fail": false }
// Without a scenario: the product manager keeps the story as is, the analyst asks one question
// (none once the prompt carries the PM's answer). Every call is appended to <scenario>.log.jsonl.
import { appendFileSync, existsSync, readFileSync } from "node:fs";
import { appendFileSync, existsSync, readdirSync, readFileSync } from "node:fs";
interface Scenario {
/** PEP-112: the product agent on acceptance: {summary, howto[], not_real[], needs[], stories[]}. */
accept?: object;
/** PEP-110: the analyst in the project chat: {reply, create[]}. */
chat?: object;
/** PEP-115: the analyst reworking a backlog story after a comment (the analyst's JSON). */
@ -23,10 +25,10 @@ interface Scenario {
const file = process.env.MOCK_INTAKE_SCENARIO;
const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
const prompt = readFileSync(0, "utf8");
const role = prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst";
const role = prompt.startsWith("Ты — продакт-менеджер софтвер-фабрики на приёмке") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst";
const answered = /Ответ продакта:\n/.test(prompt);
const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? "";
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
if (!process.argv.includes("-p")) {
console.error("mock-intake: expected -p (non-interactive print mode)");
process.exit(2);
@ -62,6 +64,17 @@ const refine = sc.refine ?? {
questions: [],
comment: `Добавил критерий: ${lastComment}`,
};
// PEP-112, acceptance: without a scenario it reads the page text in the prompt — a «демо» notice
// becomes a not-real item and a need, a «токен» field becomes a story.
const demo = /демо-режим[^\n]*/i.exec(prompt.split("## Что видит пользователь")[1]?.split("## Уже объявлено")[0] ?? "")?.[0];
const tokenField = /\[поле: [^\]]*токен[^\]]*\]/i.test(prompt);
const accept = sc.accept ?? {
summary: "Продукт открывается и показывает главную страницу.",
howto: ["Откройте адрес продукта", "Нажмите главную кнопку"],
not_real: demo ? [demo] : [],
needs: demo && !/Уже объявлено: что нужно от владельца\n- /.test(prompt) ? [{ title: "Ключ сервиса", why: "без него показаны примеры", how: "В кабинете сервиса" }] : [],
stories: tokenField ? [{ title: "Убрать служебное поле «Токен запуска» с экрана", description: "Пользователь не видит служебных полей.\n- На странице нет поля «Токен запуска»" }] : [],
};
if (sc.slowMs) await new Promise((r) => setTimeout(r, sc.slowMs));
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst);
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "accept" ? accept : role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst);
process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n");

View File

@ -0,0 +1,389 @@
// 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 = `<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(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 задаёт раннер/);
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>Демо-режим[^<]*<\/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>Цена&nbsp;&mdash; 5&#8381;</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":"А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);
});
});

View File

@ -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();

View File

@ -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 <status> [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 <image> <compose args…>
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

View File

@ -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:

View File

@ -1,7 +1,8 @@
# Стенд проекта Пеппы (PEP-57). Деплой: docker compose -p <slug>-<env> -f deploy/compose.yml up -d
# с переменными IMAGE (образ peppa/<slug>:<sha>), 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}