- PEP-30: .peppa/memory.md in the project repo (core/memory.ts), agent MCP get_memory/remember (dedupe, 12k size limit, replace to compact), runner appends memory + last finished stories to the launch rules, RULES.md rule, memory on the project «Спеки» tab. - PEP-41: agent settings platform → project → story (provider, model, effort, escalation model after N failures, fallback provider); Claude --effort / Codex model_reasoning_effort; sticky escalation relaunches a live runner on the stronger model (sendWithEscalation from CI feedback and the reviewer); fallback provider when the main one has no working subscription; web panels, MCP PM `agent`, CLI `peppa project agent`. - PEP-31: first-run checklist on the home page (core/onboarding.ts), hide button, «Агенты не запустятся» warning on the project page when its pool has no working subscription. No migrations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
224 lines
12 KiB
TypeScript
224 lines
12 KiB
TypeScript
// Reviewer agent (PEP-26): before a story with green checks reaches the PM, one short
|
||
// `claude -p` call reviews the PR diff. Findings go back to the story's agent like a red CI
|
||
// run; "ok" moves the story to review with the reviewer's summary. Off unless the PM turns it
|
||
// on in the project settings. Tests use mock-reviewer (same contract as the CLI).
|
||
import {
|
||
askPm,
|
||
claimReview,
|
||
finishReview,
|
||
formatFindings,
|
||
getReviewSettings,
|
||
giteaForBot,
|
||
latestReview,
|
||
listSessions,
|
||
pendingReview,
|
||
queueReview,
|
||
raiseSessionQuestion,
|
||
resolveTask,
|
||
reviewNote,
|
||
reviewPreview,
|
||
reviewPreviewNote,
|
||
reviewRejections,
|
||
reviewsToRun,
|
||
taskPrNumber,
|
||
updateTask,
|
||
type CodeReview,
|
||
type GiteaClient,
|
||
type ReviewFinding,
|
||
type TaskRef,
|
||
} from "@peppa/core";
|
||
import { projects, tasks, type Db } from "@peppa/db";
|
||
import { formatTaskKey } from "@peppa/shared";
|
||
import { eq } from "drizzle-orm";
|
||
import { claudePrint } from "./claude-print.ts";
|
||
import { sendToSession } from "./sessions.ts";
|
||
import { sendWithEscalation } from "./escalation.ts";
|
||
import { moveTask } from "./flow.ts";
|
||
|
||
export interface ReviewVerdict {
|
||
verdict: "ok" | "changes";
|
||
summary: string;
|
||
findings: ReviewFinding[];
|
||
}
|
||
|
||
/** The diff the reviewer sees is cut to this many characters. */
|
||
export const REVIEW_DIFF_LIMIT = 120_000;
|
||
const reviewTimeoutMs = () => Number(process.env.PEPPA_REVIEW_TIMEOUT_MS ?? 300_000);
|
||
|
||
export function reviewPrompt(ref: Pick<TaskRef, "key" | "project"> & { task: { title: string; description: string | null } }, diff: string, rules: string | null): string {
|
||
const cut = diff.length > REVIEW_DIFF_LIMIT;
|
||
return [
|
||
"Ты — ревьюер кода софтвейр-фабрики Пеппа. Агент сделал стори и открыл PR; автоматические проверки (lint, typecheck, test, build) уже зелёные.",
|
||
"Прочитай дифф и реши, можно ли отдавать стори PM на приёмку. Чек-лист:",
|
||
"1. Сделано то, что просит стори (ничего важного не пропущено и не сделано лишнего).",
|
||
"2. Нет явных багов: краевые случаи, ошибки, гонки, потеря данных.",
|
||
"3. Безопасность: нет секретов в коде, инъекций, обхода проверок доступа.",
|
||
"4. Новое поведение покрыто тестами, тесты действительно что-то проверяют.",
|
||
"5. Нет мусора: отладочного вывода, закомментированного кода, временных файлов.",
|
||
'Вердикт "changes" — только при проблемах, которые надо исправить до приёмки. Стиль, вкус и мелкие улучшения — не повод: при них "ok" (можешь упомянуть в summary).',
|
||
...(rules?.trim() ? ["", "Дополнительные правила PM:", rules.trim()] : []),
|
||
"",
|
||
`Проект: ${ref.project.key} — ${ref.project.name}`,
|
||
`Стори ${ref.key}: ${ref.task.title}`,
|
||
"Описание стори:",
|
||
ref.task.description?.trim() || "(нет)",
|
||
"",
|
||
`Дифф PR${cut ? ` (обрезан до ${REVIEW_DIFF_LIMIT} символов)` : ""}:`,
|
||
"```diff",
|
||
cut ? diff.slice(0, REVIEW_DIFF_LIMIT) : diff,
|
||
"```",
|
||
"",
|
||
'Ответь ОДНИМ JSON без пояснений: {"verdict":"ok|changes","summary":"1–2 предложения по-русски","findings":[{"file":"путь","line":12,"severity":"blocker|major|minor","text":"что не так и как исправить"}]}',
|
||
].join("\n");
|
||
}
|
||
|
||
/** The verdict from the reviewer's answer (bare JSON, or JSON inside text / a code fence). */
|
||
export function parseReviewOutput(text: string): ReviewVerdict | null {
|
||
const start = text.indexOf("{");
|
||
const end = text.lastIndexOf("}");
|
||
if (start < 0 || end <= start) return null;
|
||
try {
|
||
const d = JSON.parse(text.slice(start, end + 1)) as { verdict?: unknown; summary?: unknown; findings?: unknown };
|
||
if (d.verdict !== "ok" && d.verdict !== "changes") return null;
|
||
const findings: ReviewFinding[] = (Array.isArray(d.findings) ? d.findings : [])
|
||
.filter((f): f is Record<string, unknown> => !!f && typeof f === "object" && typeof (f as { text?: unknown }).text === "string")
|
||
.slice(0, 30)
|
||
.map((f) => ({
|
||
text: String(f.text).slice(0, 1000),
|
||
...(typeof f.file === "string" && f.file ? { file: f.file.slice(0, 300) } : {}),
|
||
...(Number.isInteger(f.line) && (f.line as number) > 0 ? { line: f.line as number } : {}),
|
||
...(typeof f.severity === "string" ? { severity: f.severity.slice(0, 20) } : {}),
|
||
}));
|
||
// "changes" without anything to fix is not actionable for the agent.
|
||
if (d.verdict === "changes" && !findings.length) return null;
|
||
return { verdict: d.verdict, summary: String(d.summary ?? "").slice(0, 500), findings };
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** Runs `$PEPPA_REVIEW_BIN -p` (default `claude`, model `sonnet`) on the project's pool subscription. */
|
||
export async function runReviewer(db: Db, ref: TaskRef, diff: string, rules: string | null): Promise<{ ok: true; verdict: ReviewVerdict } | { ok: false; error: string }> {
|
||
const out = await claudePrint(db, ref.project, {
|
||
bin: process.env.PEPPA_REVIEW_BIN ?? "claude",
|
||
model: process.env.PEPPA_REVIEW_MODEL ?? "sonnet",
|
||
timeoutMs: reviewTimeoutMs(),
|
||
prompt: reviewPrompt(ref, diff, rules),
|
||
who: "ревьюер",
|
||
});
|
||
if (!out.ok) return out;
|
||
const verdict = parseReviewOutput(out.text);
|
||
return verdict ? { ok: true, verdict } : { ok: false, error: "ревьюер ответил не по формату" };
|
||
}
|
||
|
||
export type ReviewRequest =
|
||
/** Go to review now; `note` — what to tell the PM about the reviewer. */
|
||
| { action: "review"; note?: string }
|
||
/** A review is queued/running: the story stays in work, the agent ends its turn. */
|
||
| { action: "queued"; review: CodeReview };
|
||
|
||
/**
|
||
* The agent asks for review and the CI gate passed: decides whether the reviewer runs first.
|
||
* Off, no PR, Gitea unreachable → review now. Same head already approved → review now.
|
||
* Rejected `maxIterations` times already → review now with the last findings.
|
||
*/
|
||
export async function requestReview(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<ReviewRequest> {
|
||
const settings = await getReviewSettings(db, ref.project.id);
|
||
if (!settings.enabled) return { action: "review" };
|
||
const n = taskPrNumber(ref.project, ref.task.prUrl);
|
||
if (!n) return { action: "review" };
|
||
let sha: string;
|
||
try {
|
||
const pull = await gitea.getPullRequest(ref.project.giteaOwner, ref.project.giteaRepo, n);
|
||
if (pull.merged) return { action: "review" };
|
||
sha = pull.head.sha;
|
||
} catch (e) {
|
||
return { action: "review", note: `🔎 Ревьюер не запускался: Gitea недоступна (${(e as Error).message.slice(0, 120)})` };
|
||
}
|
||
const pending = await pendingReview(db, ref.task.id);
|
||
if (pending?.sha === sha) return { action: "queued", review: pending };
|
||
const last = await latestReview(db, ref.task.id);
|
||
if (last?.sha === sha && last.state === "done" && last.verdict === "ok") return { action: "review", note: reviewNote(last) };
|
||
if ((await reviewRejections(db, ref.task.id)) >= settings.maxIterations) return { action: "review", note: reviewNote(last, true) };
|
||
const review = await queueReview(db, { projectId: ref.project.id, taskId: ref.task.id, prNumber: n, sha });
|
||
startReview(db, review.id);
|
||
return { action: "queued", review };
|
||
}
|
||
|
||
const inFlight = new Set<number>();
|
||
|
||
/** Runs a review in the background of this process (MCP server or watchdog). */
|
||
export function startReview(db: Db, id: number, log: (m: string) => void = () => {}): void {
|
||
if (inFlight.has(id)) return;
|
||
inFlight.add(id);
|
||
processReview(db, id)
|
||
.catch((e) => log(`review #${id}: ${(e as Error).message}`))
|
||
.finally(() => inFlight.delete(id));
|
||
}
|
||
|
||
/** Watchdog: queued reviews whose process never ran them, and runs stuck past twice the timeout. */
|
||
export async function reviewTick(db: Db, log: (m: string) => void = () => {}): Promise<number> {
|
||
const rows = await reviewsToRun(db, new Date(Date.now() - 2 * reviewTimeoutMs()));
|
||
for (const r of rows) startReview(db, r.id, log);
|
||
return rows.length;
|
||
}
|
||
|
||
async function taskRef(db: Db, taskId: number): Promise<TaskRef | null> {
|
||
const [t] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, taskId));
|
||
return t ? resolveTask(db, formatTaskKey(t.key, t.number)) : null;
|
||
}
|
||
|
||
/**
|
||
* Claims and runs one review, then acts on it: findings → the agent; ok or a broken reviewer
|
||
* → the story goes to review and the PM gets "ready for review". A story the PM moved out of
|
||
* work meanwhile is left where it is (the result is still on the card).
|
||
*/
|
||
export async function processReview(db: Db, id: number, gitea: GiteaClient = giteaForBot()): Promise<CodeReview | null> {
|
||
const claimed = await claimReview(db, id, new Date(Date.now() - 2 * reviewTimeoutMs()));
|
||
if (!claimed) return null;
|
||
const ref = await taskRef(db, claimed.taskId);
|
||
if (!ref) return finishReview(db, id, { error: "стори не найдена" });
|
||
const settings = await getReviewSettings(db, ref.project.id);
|
||
let diff: string | null = null;
|
||
let error: string | null = null;
|
||
try {
|
||
diff = await gitea.pullDiff(ref.project.giteaOwner, ref.project.giteaRepo, claimed.prNumber);
|
||
} catch (e) {
|
||
error = `не удалось получить дифф PR: ${(e as Error).message.slice(0, 200)}`;
|
||
}
|
||
const res = diff !== null ? await runReviewer(db, ref, diff, settings.rules) : { ok: false as const, error: error! };
|
||
const review = await finishReview(db, id, res.ok ? res.verdict : { error: res.error });
|
||
|
||
const fresh = await taskRef(db, claimed.taskId);
|
||
if (!fresh || !["proposing", "in_progress"].includes(fresh.task.status)) return review;
|
||
const sessionId = (await listSessions(db, { active: true, taskId: fresh.task.id }))[0]?.id ?? null;
|
||
|
||
if (review.verdict === "changes") {
|
||
const iteration = await reviewRejections(db, fresh.task.id);
|
||
const text = [
|
||
`🔎 Ревьюер вернул ${fresh.key} (коммит ${review.sha.slice(0, 7)}, итерация ${iteration} из ${settings.maxIterations}): ${review.summary}`,
|
||
formatFindings(review.findings),
|
||
"Исправь замечания, запушь в ту же ветку, дождись зелёных проверок и снова update_task(status: review). Если замечание неверно — объясни это в описании PR и всё равно снова update_task(status: review).",
|
||
].join("\n\n");
|
||
if (sessionId) {
|
||
try {
|
||
await sendWithEscalation(db, sessionId, text);
|
||
return review;
|
||
} catch {}
|
||
}
|
||
await moveTask(db, fresh, "in_progress", { prompt: text });
|
||
return review;
|
||
}
|
||
|
||
await updateTask(db, fresh, { status: "review" });
|
||
const look = reviewPreviewNote(await reviewPreview(db, fresh));
|
||
const msg = `✅ Стори ${fresh.key} готова к ревью${fresh.task.prUrl ? ` · PR: ${fresh.task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${reviewNote(review)}`.slice(0, 3500);
|
||
const [s] = sessionId ? await listSessions(db, { active: true, taskId: fresh.task.id }) : [];
|
||
// Still in the turn that asked for review: its Stop hook sends "ready for review" with this
|
||
// note (OpenCode has no turn hooks — it gets the message now).
|
||
if (s && s.provider !== "opencode" && (s.status === "running" || s.status === "starting")) return review;
|
||
if (s) await raiseSessionQuestion(db, s, "attention", msg);
|
||
else await askPm(db, fresh, { kind: "attention", text: msg });
|
||
return review;
|
||
}
|