peppa/packages/runner/src/product-review.ts

316 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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,
addToDigest,
deferredFindings,
getDigest,
takeFromDigest,
proposalRoom,
logEvent,
normTitle,
rejectedTitles,
setChatOffer,
setDigest,
SEVERITY_LABEL,
versionFinished,
type ProductReviewReply,
type DigestItem,
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, keyPrefix } 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<number>();
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<void> {
if (process.env.PEPPA_PRODUCT_REVIEW === "off") return;
const log = opts.log ?? (() => {});
const jobs: Promise<void>[] = [];
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(keyPrefix(settings.key, 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<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) });
}
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 };
const deferred = await deferredFindings(db, project.id);
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, deferred: { n: deferred.items.length, breakage: deferred.breakage } });
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;
proposed: boolean;
}
/**
* Files the stories the acceptance agent found: never what the owner declined, never a repeat (a
* remark goes to the open story instead). Every finding waits in «Предложено» (PEP-295: a breakage
* too — the agent sets the severity itself), marked.
* Improvements: not more than `perPass` per pass and the project's `perDay` (PEP-270); after the
* version's finish they are only kept. What is not filed goes to the weekly digest — never dropped.
* PEP-302: a breakage is filed the same day, past both limits (it still waits for «Делать»).
*/
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;
let improvements = 0;
const ordered = [...stories].sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
for (const s of ordered) {
if (rejected.has(normTitle(s.title))) continue;
const isBreakage = s.severity === "breakage";
if (isBreakage) 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 (!isBreakage) {
// PEP-270: not more than perDay proposals of agents a day; the rest waits for the weekly message.
const overDay = (await proposalRoom(db, project.id)).room <= 0;
const overPass = improvements >= Math.max(0, limits.perPass);
if (overDay) await logEvent(db, { projectId: project.id, type: "proposal_limited", payload: { title: s.title, via: "acceptance", severity: s.severity } });
if (overDay || overPass || finished) {
await addToDigest(db, project.id, { title: s.title, description: s.description, severity: s.severity });
kept++;
continue;
}
improvements++;
}
// 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 ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity });
// 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, proposed: ref.task.proposed });
}
return { created, breakage, kept };
}
/** Telegram buttons under the message: per item «Делать» / «Не надо» (`p:<task>:do|no`), then for all. */
export function proposalButtons(items: Array<{ id: number; key: string; severity: string; proposed?: boolean }>, locale: Locale): Array<Array<{ text: string; callback_data: string }>> {
// PEP-295: every finding is a proposal unless the owner let them go to work at once.
const open = items.filter((i) => i.proposed !== false);
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 (or past the limits) the improvements were only kept; once a week they
* go to the owner in one message (to «Предложено», with the same buttons). What does not fit stays
* kept, and the message says how many. PEP-302: a breakage never waits for the week — one put
* aside before (by an older version of the rule) is filed on the next pass.
*/
export async function productDigestTick(db: Db, now: Date, log: (m: string) => void = () => {}): Promise<void> {
const rows = await db.select().from(settings).where(keyPrefix(settings.key, "product.digest:"));
for (const row of rows) {
const projectId = Number(row.key.slice("product.digest:".length));
if (await isProjectPaused(db, projectId)) continue;
const [project] = await db.select().from(projects).where(eq(projects.id, projectId));
if (!project) continue;
const broken = await takeFromDigest(db, projectId, (i) => i.severity === "breakage");
if (broken.length) {
const filed = await fileStories(db, project, broken.map(digestStory), { envLabel: "", url: "", log, ignoreFinish: true });
if (filed.created.length) await tellFiled(db, project, tr("Поломки, которые ждали сводки, — в «Предложено»: {n}.", { n: filed.created.length }), filed.created);
log(`product digest ${project.key}: breakages ${filed.created.length}`);
}
const d = await getDigest(db, projectId);
if (!d.items.length || (d.sentAt && now.getTime() - Date.parse(d.sentAt) < DIGEST_EVERY_MS)) continue;
await setDigest(db, projectId, { items: [], sentAt: now.toISOString() });
const filed = await fileStories(db, project, d.items.map(digestStory), { envLabel: "", url: "", log, ignoreFinish: true });
const left = (await getDigest(db, projectId)).items.length;
if (!filed.created.length && !left) continue;
const found = { n: filed.created.length, important: filed.created.filter((f) => f.severity !== "minor").length };
const head = filed.created.length ? tr("Раз в неделю: нашёл улучшений: {n} (важных: {k}).", { n: found.n, k: found.important }) : tr("Раз в неделю: сегодня новых задач не завёл — суточный предел уже набран.");
const tail = left ? `\n${tr("Осталось отложенными: {n} — они на доске в «Предложено» → «Отложено».", { n: left })}` : "";
await tellFiled(db, project, head, filed.created, tail);
log(`product digest ${project.key}: ${filed.created.length}, left ${left}`);
}
}
const digestStory = (i: DigestItem) => ({ title: i.title, description: i.description, severity: i.severity });
/** One message of the acceptance agent with the filed stories and «Делать» / «Не надо» under it. */
async function tellFiled(db: Db, project: Project, head: string, created: Filed[], tail = ""): Promise<void> {
const chat = await ensureProjectChat(db, project.id);
const lines = created.map((f) => `• ${f.key} «${f.title}» — ${tr(SEVERITY_LABEL[f.severity])}`).join("\n");
const said = await sayInDiscussion(db, project, chat.id, `${head}${lines ? `\n${lines}` : ""}${tail}`, PRODUCT_AGENT_NAME, { buttons: (locale) => proposalButtons(created, locale) });
if (said && created.length) await setChatOffer(db, said.id, { kind: "proposals", text: "", items: created.map((f) => ({ id: f.id, key: f.key, title: f.title, severity: f.severity })) });
}