peppa/packages/core/src/product-review.ts
2026-11-15 19:57:05 +05:00

209 lines
14 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. 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");
}