// PEP-127: the PM gets the «готова к ревью» message (with «Принять») only when the story can // be merged right now — green checks of the PR head and no conflict. Otherwise the message is // held (`review.hold:`) and the watchdog sends it once the gate opens // (runner/review-card.ts). import { settings, type Db } from "@peppa/db"; import { asIs, m } from "@peppa/shared/i18n"; import { like } from "drizzle-orm"; import { logEvent } from "./audit.ts"; import { prGate } from "./ci.ts"; import type { GiteaClient } from "./gitea.ts"; import { raiseSessionQuestion, type Session } from "./sessions.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { askPm, type Question, type TaskRef } from "./tasks.ts"; import { getTaskResult } from "./message-details.ts"; import { reviewPreview, reviewPreviewNote } from "./preview.ts"; import { demoNote } from "./product-needs.ts"; export interface ReviewHold { /** The main text of the message the PM gets when the gate opens. */ text: string; /** PEP-152: its technical details (under «Подробнее»). */ details?: string | null; /** When it was held (ms). */ at: number; /** Head SHA the agent was asked to rebase (once per head commit). */ rebaseSha?: string; /** Head SHA for which Peppa asked Gitea to bring the base branch into the PR branch. */ updateSha?: string; } const PREFIX = "review.hold:"; const key = (taskId: number) => `${PREFIX}${taskId}`; /** Answer that takes a ready-for-review message back when its PR got into a conflict. */ export const REVIEW_REVOKED_ANSWER = m("🔄 Агент обновляет изменения — пришлём задачу снова, когда её можно будет принять."); /** Gate reason when Gitea could not be asked: closed, never "ok". */ export const GATE_UNKNOWN_REASON = m("не удалось проверить состояние проверок — повторите позже"); export const getReviewHold = (db: Db, taskId: number) => getSetting(db, key(taskId)); export const setReviewHold = (db: Db, taskId: number, h: ReviewHold) => setSetting(db, key(taskId), h); export const clearReviewHold = (db: Db, taskId: number) => deleteSetting(db, key(taskId)); export async function listReviewHolds(db: Db): Promise> { const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`)); return new Map(rows.map((r) => [Number(r.key.slice(PREFIX.length)), r.value as ReviewHold])); } /** PEP-152: the «готово» message in the common format — the main text and the details apart. */ export interface ReviewCard { text: string; details?: string | null; } const webBase = () => (process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, ""); /** * PEP-152: builds «готово» like any message for the person: the gist, the agent's own words about * the result (when it gave them with `update_task`), «Что нужно от вас», «Где посмотреть» (the * version to look at, else the story page). The result address, the changes, the checks, the * reviewer's note and the agent's last reply are details. */ export async function buildReviewCard(db: Db, ref: TaskRef, extra: { note?: string; agentText?: string | null } = {}): Promise { const preview = await reviewPreview(db, ref).catch(() => null); const result = await getTaskResult(db, ref.task.id); const look = preview?.previewUrl ?? (webBase() ? `${webBase()}/t/${ref.key}` : null); const text = [ m("✅ Задача {key} готова к ревью", { key: ref.key }), // PEP-139: the agent's own words are free text — not translated. asIs(result?.summary), m("Что нужно от вас: {need}", { need: m("посмотрите результат и нажмите «Принять» — или напишите, что поправить") }), // No address of the site (a bare test environment) — no line: a path alone is not a link. look ? m("Где посмотреть: {url}", { url: look }) : "", ] .filter(Boolean) .join("\n"); const details = [ ref.task.prUrl ? m("Результат: {url}", { url: ref.task.prUrl }) : "", preview ? reviewPreviewNote(preview) : "", await demoNote(db, ref.project.id, ref.project.key).catch(() => ""), extra.note, asIs(result?.details), asIs(extra.agentText?.trim()), ] .filter(Boolean) .join("\n\n") .slice(0, 6000); return { text, details: details || null }; } /** * Sends «готова к ревью» to the PM if the story's PR can be merged now; otherwise holds the * message (event `awaiting_checks` with the reason) and returns null. A Gitea error keeps the * gate closed. */ export async function sendReviewCard(db: Db, ref: TaskRef, message: string | ReviewCard, session?: Session | null, gitea?: GiteaClient): Promise { const { text, details = null } = typeof message === "string" ? { text: message } : message; const gate = await prGate(ref, gitea).catch(() => null); if (gate?.ok) { await clearReviewHold(db, ref.task.id); // PEP-151: «готово» for the same head commit is one message, however many times it is sent. // PEP-149: it is a `done` message and always carries a link to the result. const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null, msgType: "done" as const, details }; // A card built in the format has its «Где посмотреть» already; a bare text gets the story page. const card = typeof message !== "string" || !webBase() || /https?:\/\//.test(text) ? text : `${text}\n${m("Где посмотреть: {url}", { url: `${webBase()}/t/${ref.key}` })}`; return session ? raiseSessionQuestion(db, session, "attention", card, undefined, false, state) : askPm(db, ref, { kind: "attention", text: card, ...state }); } const prev = await getReviewHold(db, ref.task.id); await setReviewHold(db, ref.task.id, { ...prev, text, details, at: Date.now() }); await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: session?.id ?? null, type: "awaiting_checks", payload: { reason: gate?.reason ?? GATE_UNKNOWN_REASON, sha: gate?.pull?.head.sha ?? null } }); return null; }