// 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 { addIntakeNote, createTask, dedupRemark, dedupSimilarNote, finishVersionIfReady, getAgentLimits, getDigest, normTitle, rejectedTitles, setChatOffer, setDigest, SEVERITY_LABEL, versionFinished, type ProductReviewReply, guardUntrusted, 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, isProjectPaused, } from "@peppa/core"; import { projects, releases, settings, tasks, type Db } from "@peppa/db"; import { and, desc, eq, isNull, ne, sql } from "drizzle-orm"; import { m as tr, t, type Locale } from "@peppa/shared/i18n"; import { sayInDiscussion } from "./analyst-chat.ts"; import { checkDuplicate } from "./task-dedup.ts"; import { claudePrint } from "./claude-print.ts"; import { releaseScreenshotFiles, type Release } from "./deploy.ts"; const inFlight = new Set(); const MAX_ATTEMPTS = 2; const MAX_SHOTS = 3; export interface ProductReviewOptions { log?: (m: string) => void; /** Wait for the model calls (tests); the watchdog lets them run in the background. */ wait?: boolean; now?: Date; } /** Deploys the product agent has not looked at yet. */ export async function productReviewTick(db: Db, opts: ProductReviewOptions = {}): Promise { if (process.env.PEPPA_PRODUCT_REVIEW === "off") return; const log = opts.log ?? (() => {}); const jobs: Promise[] = []; await productDigestTick(db, opts.now ?? new Date(), log).catch((e) => log(`product digest: ${(e as Error).message}`)); 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)); // PEP-174: the product agent waits while the project is on pause. if (inFlight.has(projectId) || (await isProjectPaused(db, 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 { 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): Promise { 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 { // 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) }); } for (const p of pages) await guardUntrusted(db, { projectId: project.id, source: `страница ${p.path} продукта`, text: p.text }); 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), rejected: (await rejectedTitles(db, project.id)).slice(-30), }), }); 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 }); // PEP-197: what the agent found is checked for repeats and goes to «Предложено» (a breakage — to the backlog). const filed = await fileStories(db, project, reply.stories, { envLabel, url, log }); 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.created.map((f) => f.key) }); const chat = await ensureProjectChat(db, project.id); // PEP-197: the version is finished when everything a person asked for is accepted and nothing is broken. const versionDone = await finishVersionIfReady(db, project.id, filed.breakage); const found = { n: filed.created.length, important: filed.created.filter((f) => f.severity !== "minor").length }; let text = productReviewMessage(reply, { env: rel.env === "prod" ? "prod" : "staging", url, openNeeds: stillOpen, filed: filed.created.map((f) => `${f.key} «${f.title}» — ${tr(SEVERITY_LABEL[f.severity])}`), webUrl: process.env.PEPPA_WEB_URL ?? "", projectKey: project.key, found }); if (versionDone) text += `\n\n${tr("Версия готова. Продукт: {url}", { url })}\n${tr("Что умеет: {summary}", { summary: reply.summary })}`; // One message, buttons under it: «Делать» / «Не надо» per item, «Делать важные» / «Отклонить всё». const said = await sayInDiscussion(db, project, chat.id, text, PRODUCT_AGENT_NAME, { buttons: (locale) => proposalButtons(filed.created, locale) }); if (said && filed.created.length) await setChatOffer(db, said.id, { kind: "proposals", text: "", items: filed.created.map((f) => ({ id: f.id, key: f.key, title: f.title, severity: f.severity })) }); log(`product review ${project.key}: ${rel.env} ${rel.sha.slice(0, 7)} — needs ${stillOpen.length}, stories ${filed.created.length}`); } const SEVERITY_ORDER = { breakage: 0, important: 1, minor: 2 } as const; type Severity = "breakage" | "important" | "minor"; interface Filed { id: number; key: string; title: string; severity: Severity; } /** * Files the stories the acceptance agent found: not more than the project's limit per pass, * never what the owner declined, never a repeat (a remark goes to the open story instead). * An improvement waits in «Предложено»; a breakage goes to the backlog at once, marked. * After the version's finish only breakages are filed; the rest is kept for the weekly message. */ export async function fileStories(db: Db, project: Project, stories: ProductReviewReply["stories"], o: { envLabel: string; url: string; log?: (m: string) => void; ignoreFinish?: boolean }): Promise<{ created: Filed[]; breakage: boolean; kept: number }> { const limits = await getAgentLimits(db, project.id); const finished = o.ignoreFinish ? false : await versionFinished(db, project.id); const rejected = new Set(await rejectedTitles(db, project.id)); const created: Filed[] = []; let breakage = false; let kept = 0; const ordered = [...stories].sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]).slice(0, Math.max(0, limits.perPass)); for (const s of ordered) { if (rejected.has(normTitle(s.title))) continue; if (s.severity === "breakage") breakage = true; const dup = await checkDuplicate(db, project, s, { log: o.log }); if (dup.kind === "open") { await addIntakeNote(db, dup.task, "acceptance", dedupRemark(s.title, s.description)); o.log?.(`product review ${project.key}: «${s.title}» — повтор ${dup.key}, замечание дописано`); continue; } if (finished && s.severity !== "breakage") { const d = await getDigest(db, project.id); if (!d.items.some((i) => normTitle(i.title) === normTitle(s.title))) await setDigest(db, project.id, { items: [...d.items, { title: s.title, description: s.description, severity: s.severity }].slice(-20), sentAt: d.sentAt ?? new Date().toISOString() }); kept++; continue; } // glossary-user: описание задачи, которое читает владелец let description = `${s.description}\n\n_Заведено агентом приёмки${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`; if (dup.kind === "done") description += `\n\n_${dedupSimilarNote(dup.key, dup.doneAt.toISOString().slice(0, 10))}_`; const isBreakage = s.severity === "breakage"; const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity, proposed: !isBreakage }); // Already formulated: «продакт» and «аналитик» of the intake skip it. await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена агентом приёмки" }); created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity }); } return { created, breakage, kept }; } /** Telegram buttons under the message: per item «Делать» / «Не надо» (`p::do|no`), then for all. */ export function proposalButtons(items: Array<{ id: number; key: string; severity: string }>, locale: Locale): Array> { const open = items.filter((i) => i.severity !== "breakage"); if (!open.length) return []; const rows = open.map((i) => [ { text: `✅ ${t(locale, "Делать")} ${i.key}`, callback_data: `p:${i.id}:do` }, { text: `✖️ ${t(locale, "Не надо")} ${i.key}`, callback_data: `p:${i.id}:no` }, ]); const ids = open.map((i) => i.id).join(","); rows.push([{ text: `✅ ${t(locale, "Делать важные")}`, callback_data: `p:${ids}:important` }, { text: `✖️ ${t(locale, "Отклонить всё")}`, callback_data: `p:${ids}:none` }]); return rows; } const DIGEST_EVERY_MS = 7 * 86_400_000; /** * After the version's finish the improvements were only kept; once a week they go to the owner in * one message (to «Предложено», with the same buttons). */ export async function productDigestTick(db: Db, now: Date, log: (m: string) => void = () => {}): Promise { const rows = await db.select().from(settings).where(sql`${settings.key} like ${"product.digest:%"}`); for (const row of rows) { const projectId = Number(row.key.slice("product.digest:".length)); const d = await getDigest(db, projectId); if (!d.items.length || (d.sentAt && now.getTime() - Date.parse(d.sentAt) < DIGEST_EVERY_MS)) continue; if (await isProjectPaused(db, projectId)) continue; const [project] = await db.select().from(projects).where(eq(projects.id, projectId)); if (!project) continue; await setDigest(db, projectId, { items: [], sentAt: now.toISOString() }); const filed = await fileStories(db, project, d.items.map((i) => ({ title: i.title, description: i.description, severity: i.severity })), { envLabel: "", url: "", log, ignoreFinish: true }); if (!filed.created.length) continue; const chat = await ensureProjectChat(db, project.id); const found = { n: filed.created.length, important: filed.created.filter((f) => f.severity !== "minor").length }; const lines = filed.created.map((f) => `• ${f.key} «${f.title}» — ${tr(SEVERITY_LABEL[f.severity])}`).join("\n"); const said = await sayInDiscussion(db, project, chat.id, `${tr("Раз в неделю: нашёл улучшений: {n} (важных: {k}).", { n: found.n, k: found.important })}\n${lines}`, PRODUCT_AGENT_NAME, { buttons: (locale) => proposalButtons(filed.created, locale) }); if (said) await setChatOffer(db, said.id, { kind: "proposals", text: "", items: filed.created.map((f) => ({ id: f.id, key: f.key, title: f.title, severity: f.severity })) }); log(`product digest ${project.key}: ${filed.created.length}`); } }