// CI feedback (PEP-57): results come from the CI step itself (signed report with the log), // from Gitea webhooks, and from the watchdog polling commit statuses as a fallback. A red // check goes back to the agent with the step and the log tail; 3 red runs in a row → the PM. import { m } from "@peppa/shared/i18n"; import { askPm, giteaForBot, listSessions, listTasks, logEvent, PeppaError, prGate, projectSecretEnv, pipelineChanges, runLink, taskForCheck, taskPrNumber, upsertCheckRun, verifyHookSignature, type CheckReport, type GiteaClient, type Project, type TaskRef, } from "@peppa/core"; import { checkRuns, projects, tasks, type Db } from "@peppa/db"; import { and, eq, sql } from "drizzle-orm"; import { sendToSession } from "./sessions.ts"; import { sendWithEscalation } from "./escalation.ts"; import { moveTask } from "./flow.ts"; import { recordRelease, recordScreenshots } from "./deploy.ts"; import { offerPlatformRelease } from "./platform-release.ts"; import { handleGiteaEvent } from "./gitea-events.ts"; /** Red runs in a row after which the PM is asked instead of the agent. */ export const MAX_CI_ATTEMPTS = 3; const LOG_LINES = 100; const tail = (log: string | null | undefined, n = LOG_LINES) => (log ?? "").trimEnd().split("\n").slice(-n).join("\n"); async function activeSessionId(db: Db, taskId: number): Promise { return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null; } export interface CheckOutcome { task: string | null; /** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */ action: "none" | "agent" | "restarted" | "pm" | "green"; } /** Records one CI result and reacts to it for the task of that branch/PR. */ export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise { const ref = await taskForCheck(db, project, r.branch, r.prNumber); const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r); if (changed && r.state === "success" && r.branch === "main") await offerPlatformRelease(db, project, r.sha); if (!ref || !changed) return { task: ref?.key ?? null, action: "none" }; if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" }; if (r.state === "success") { const [red] = await db .select({ id: checkRuns.id }) .from(checkRuns) .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), sql`${checkRuns.state} in ('failure','error')`)); if (red || ref.task.ciAttempts === 0) return { task: ref.key, action: "none" }; await db.update(tasks).set({ ciAttempts: 0, ciFailedSha: null }).where(eq(tasks.id, ref.task.id)); return { task: ref.key, action: "green" }; } if (r.state !== "failure" && r.state !== "error") return { task: ref.key, action: "none" }; // Several red checks of one commit are one attempt. const newRun = ref.task.ciFailedSha !== r.sha; const attempts = newRun ? ref.task.ciAttempts + 1 : ref.task.ciAttempts; if (newRun) await db.update(tasks).set({ ciAttempts: attempts, ciFailedSha: r.sha }).where(eq(tasks.id, ref.task.id)); const link = runLink(r.runUrl); const sessionId = await activeSessionId(db, ref.task.id); if (attempts >= MAX_CI_ATTEMPTS) { if (!newRun) return { task: ref.key, action: "none" }; // the PM already has this commit // Not tied to the session: the "wait for the PM" paste below (and any prompt of the agent) // would close it as answered in the terminal. The answer still reaches the task's agent. await askPm(db, ref, { kind: "question", text: `${m("❌ {key}: проверки не проходят {n} раза подряд — агент не справился сам. Не прошла «{check}».", { key: ref.key, n: attempts, check: r.check })}${link ? `\n${m("Подробности: {url}", { url: link })}` : ""}\n\n${m("Что делать? Ответ уйдёт агенту.")}`, }); if (sessionId) { await sendToSession(db, sessionId, `Проверки PR ${ref.key} красные ${attempts} раза подряд — я спросил PM. Не пушь новых попыток, закончи ход и жди ответа PM.`).catch(() => {}); } return { task: ref.key, action: "pm" }; } const text = [ `❌ CI по ${ref.key}: упала проверка «${r.check}» (коммит ${r.sha.slice(0, 7)}, попытка ${attempts} из ${MAX_CI_ATTEMPTS}).${link ? ` Лог: ${link}` : ""}`, r.logTail ? `Последние строки лога:\n${tail(r.logTail)}` : "Лога в отчёте нет — открой ссылку.", `Почини (локально: bash .gitea/peppa-check.sh ${r.check}) и запушь в ту же ветку; не ослабляй проверки.`, ].join("\n\n"); if (sessionId) { // PEP-41: at the failure threshold the runner is relaunched on the stronger model. await sendWithEscalation(db, sessionId, text); // The work is not done: a task that already went to review goes back. if (ref.task.status === "review") await moveTask(db, ref, "in_progress"); return { task: ref.key, action: "agent" }; } await moveTask(db, ref, "in_progress", { prompt: text }); return { task: ref.key, action: "restarted" }; } /** Project of a repository "owner/name" (case-insensitive). */ export async function projectByRepo(db: Db, fullName: string): Promise { const [owner, name] = fullName.split("/"); if (!owner || !name) return null; const [p] = await db .select() .from(projects) .where(and(sql`lower(${projects.giteaOwner}) = ${owner.toLowerCase()}`, sql`lower(${projects.giteaRepo}) = ${name.toLowerCase()}`)); return p ?? null; } export interface HookRequest { /** X-Gitea-Event (Gitea webhooks) or X-Peppa-Event (the CI step). */ event: string; signature: string | null; body: string; } /** Handlers for Gitea events other than CI checks (deploys hook in here). */ export type GiteaEventHandler = (db: Db, project: Project, event: string, payload: Record) => Promise; const eventHandlers: GiteaEventHandler[] = []; export function onGiteaEvent(h: GiteaEventHandler) { eventHandlers.push(h); } /** POST /api/hooks/gitea: verifies the project's signature, then records/dispatches. */ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ status: number; body: Record }> { let payload: Record; try { payload = JSON.parse(req.body) as Record; } catch { return { status: 400, body: { error: "invalid json" } }; } const repo = typeof payload.repository === "string" ? payload.repository : ((payload.repository as { full_name?: string } | undefined)?.full_name ?? ""); const project = await projectByRepo(db, repo); if (!project) return { status: 404, body: { error: "unknown repository" } }; if (!verifyHookSignature(project.id, req.body, req.signature)) return { status: 401, body: { error: "bad signature" } }; if (req.event === "check") { const state = String(payload.state); if (!["success", "failure", "error", "pending"].includes(state) || typeof payload.sha !== "string" || typeof payload.check !== "string") { return { status: 400, body: { error: "bad check report" } }; } const out = await recordCheck(db, project, { sha: payload.sha, branch: (payload.branch as string) || null, prNumber: typeof payload.pr === "number" ? payload.pr : null, check: payload.check, state: state as CheckReport["state"], runUrl: (payload.run_url as string) ?? null, logTail: (payload.log_tail as string) ?? null, durationSec: typeof payload.duration_sec === "number" ? payload.duration_sec : null, source: "report", }); return { status: 200, body: { ok: true, ...out } }; } if (req.event === "deploy") { const env = String(payload.env); const status = String(payload.status); if (!["preview", "staging", "prod"].includes(env) || !["deploying", "healthy", "rolled_back", "failed", "removed"].includes(status) || typeof payload.sha !== "string") { return { status: 400, body: { error: "bad deploy report" } }; } const rel = await recordRelease(db, project, { env: env as "preview", sha: payload.sha, previousSha: (payload.previous_sha as string) || null, image: (payload.image as string) ?? null, host: (payload.host as string) ?? null, prNumber: typeof payload.pr === "number" ? payload.pr : null, status: status as "healthy", reason: (payload.reason as string) ?? null, runUrl: (payload.run_url as string) ?? null, commits: Array.isArray(payload.commits) ? payload.commits.map(String) : [], logTail: (payload.log_tail as string) ?? null, }); return { status: 200, body: { ok: true, release: rel.id, status: rel.status } }; } if (req.event === "deploy-env") { // PEP-112: the deploy step asks for the project's secrets to hand them to the product's // container. Signed like every report; a stale request (replayed) gets nothing. const ts = typeof payload.ts === "number" ? payload.ts * 1000 : 0; if (Math.abs(Date.now() - ts) > 10 * 60_000) return { status: 400, body: { error: "stale request" } }; const { env } = await projectSecretEnv(db, project.id, "deploy"); const names = Object.keys(env); if (names.length) await logEvent(db, { projectId: project.id, type: "secrets_deployed", payload: { names, env: String(payload.env ?? "") } }); return { status: 200, body: { ok: true, env } }; } if (req.event === "screenshots") { if (typeof payload.sha !== "string" || !Array.isArray(payload.shots)) return { status: 400, body: { error: "bad screenshots report" } }; const out = await recordScreenshots(db, project, { sha: payload.sha, prNumber: typeof payload.pr === "number" ? payload.pr : null, shots: (payload.shots as Array<{ path?: unknown; png?: unknown }>).map((s) => ({ path: String(s.path ?? "/"), png: String(s.png ?? "") })), }); return { status: 200, body: { ok: true, ...out } }; } // PEP-46: issues, comments and reviews in PRs, PRs merged by hand. const out = await handleGiteaEvent(db, project, payload); for (const h of eventHandlers) await h(db, project, req.event, payload); return { status: 200, body: { ok: true, ...out } }; } /** * Fallback when reports/webhooks are lost: commit statuses `peppa/*` of the PR heads of * tasks in work or review (the watchdog calls this about once a minute). */ export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Promise { let seen = 0; for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) { if (!t.prUrl) continue; const [p] = await db.select().from(projects).where(eq(projects.id, t.projectId)); const n = p && taskPrNumber(p, t.prUrl); if (!p || !n) continue; try { const pull = await gitea.getPullRequest(p.giteaOwner, p.giteaRepo, n); if (pull.state !== "open") continue; const st = await gitea.combinedStatus(p.giteaOwner, p.giteaRepo, pull.head.sha); for (const s of st.statuses ?? []) { if (!s.context.startsWith("peppa/")) continue; const state = s.status === "warning" ? "pending" : s.status; await recordCheck(db, p, { sha: pull.head.sha, branch: pull.head.ref, prNumber: n, check: s.context.slice(6), state, runUrl: s.target_url ?? null, source: "poll" }); seen++; } } catch {} } return seen; } /** * Merge on "Accept" (PEP-57): only with green checks of the PR head and no conflicts. * Throws with the reason for the PM; a task without a PR has nothing to merge. */ export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<"merged" | "already" | "no_pr"> { if (!taskPrNumber(ref.project, ref.task.prUrl)) return "no_pr"; const gitea = client ?? giteaForBot(); const gate = await prGate(ref, gitea); if (!gate.pull) return "no_pr"; if (gate.pull.merged) return "already"; if (!gate.ok) throw new PeppaError(m("Принять не удалось: {reason}", { reason: gate.reason })); return (await mergeOrCloseEmpty(ref, gate.pull, gitea)) ? "merged" : "already"; } /** * PEP-93: a PR whose commits are all in the base already (a later story's branch grew from this * one and was merged first) can't be merged — Gitea answers 405 «Please try again later». Then * the work is in main: close the PR with a note instead. True when merged, false when closed. */ export async function mergeOrCloseEmpty(ref: TaskRef, pull: { number: number; head: { sha: string; ref: string }; base: { ref: string } }, gitea: GiteaClient): Promise { const { giteaOwner: owner, giteaRepo: repo } = ref.project; // PEP-101: Gitea 1.22 compares branch names only (a SHA → 404); a failed compare never blocks // the merge — Gitea itself refuses what can't be merged. const ahead = await gitea.commitsAhead(owner, repo, pull.base.ref, pull.head.ref).catch(() => null); if (ahead === 0) { await gitea.commentIssue(owner, repo, pull.number, `Все коммиты этого PR уже в \`${pull.base.ref}\` (вошли с другим PR) — закрываю без мержа. ${ref.key} принята.`).catch(() => {}); await gitea.closePullRequest(owner, repo, pull.number); return false; } await gitea.mergePullRequest(owner, repo, pull.number, pull.head.sha); return true; } /** * Automatic merge (auto mode of a project, PEP-23/25): the same gate, and a PR that changes * the pipeline is never merged automatically — the PM gets a question describing the change. */ export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<{ merged: boolean; reason?: string }> { const gate = await prGate(ref, gitea); if (!gate.pull) return { merged: false, reason: m("результата ещё нет") }; if (gate.pull.merged) return { merged: true }; if (!gate.ok) return { merged: false, reason: gate.reason }; const changes = await pipelineChanges(ref, gate.pull, gitea); if (changes.length) { // An "attention" on a story in review is its review message: the PM gets «Принять» (merges). await askPm(db, ref, { kind: "attention", text: `${m("⚠️ {key}: изменения затрагивают проверки или обновление продукта — сами не принимаются, нужно ваше решение.", { key: ref.key })}\n${changes.map((c) => `• ${c}`).join("\n")}\n${m("Результат: {url}", { url: gate.pull.html_url })}\n${m("«Принять» примет изменения.")}`, }); return { merged: false, reason: m("изменение конвейера требует ревью PM") }; } await mergeOrCloseEmpty(ref, gate.pull, gitea); return { merged: true }; }