// 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, 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 { sayInDiscussion } from "./analyst-chat.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; 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 { if (process.env.PEPPA_PRODUCT_REVIEW === "off") return; const log = opts.log ?? (() => {}); const jobs: Promise[] = []; 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), }), }); 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)); // glossary-user: описание задачи, которое читает владелец 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, { env: rel.env === "prod" ? "prod" : "staging", 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}`); }