// 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, getSetting, setSetting, pendingReview, clearPlatformDelay, platformDelay, giteaForBot, listSessions, listTasks, logEvent, PeppaError, prGate, projectSecretEnv, pipelineChanges, runLink, taskForCheck, taskPrNumber, foreignPrUrl, upsertCheckRun, verifyHookSignature, type CheckReport, type GiteaClient, type Project, type TaskRef, isProjectPaused, } 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 { conflictStep } from "./conflict-step.ts"; import { recordRelease, recordScreenshots } from "./deploy.ts"; import { offerPlatformRelease } from "./platform-release.ts"; import { handleGiteaEvent } from "./gitea-events.ts"; import { getReviewWanted } from "./review-wanted-state.ts"; /** Red runs in a row after which the superadmin is told (PEP-150: the owner is not asked). */ export const MAX_CI_ATTEMPTS = 3; /** Red runs in a row after which the agent stops trying. */ export const CI_STOP_ATTEMPTS = 6; 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; } const wokeKey = (taskId: number) => `ci.woke:${taskId}`; /** * PEP-149: an agent that ended its turn waiting for the checks is woken by Peppa, not by the * person: every check of the PR head passed and the story is still in work → one message per * commit. Returns true when the agent was told. */ export async function wakeOnGreen(db: Db, ref: TaskRef, r: Pick, gitea: GiteaClient = giteaForBot()): Promise { if (!["proposing", "in_progress"].includes(ref.task.status)) return false; const [s] = await listSessions(db, { active: true, taskId: ref.task.id }); if (!s || (s.status !== "idle" && s.status !== "waiting_input")) return false; if ((await getSetting(db, wokeKey(ref.task.id))) === r.sha) return false; if (await pendingReview(db, ref.task.id)) return false; // PEP-205: the agent already asked for review — the platform moves the story on green, no turn needed. if (await getReviewWanted(db, ref.task.id)) return false; const { giteaOwner: o, giteaRepo: repo } = ref.project; const n = taskPrNumber(ref.project, ref.task.prUrl) ?? r.prNumber ?? (r.branch ? (await gitea.openPullForBranch(o, repo, r.branch))?.number : null); if (!n) return false; const gate = await prGate({ ...ref, task: { ...ref.task, prUrl: `/${o}/${repo}/pulls/${n}` } }, gitea); if (!gate.summary || gate.pull?.head.sha !== r.sha) return false; // PEP-196: green checks but the PR conflicts with main — nobody else would wake the agent, and it // would wait forever. Tell it to bring the branch up to date (once per commit). const conflict = !gate.ok && !gate.behind && gate.summary.state === "success" && gate.pull?.mergeable === false; // Only the commit the PR stands on now; a branch behind the base is updated by Peppa itself. if (!(gate.ok || gate.behind || conflict)) return false; await setSetting(db, wokeKey(ref.task.id), r.sha); await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s.id, type: "checks_passed_wake", payload: { sha: r.sha, pr: n, ...(conflict ? { conflict: true } : {}) } }); // PEP-269: the conflict is one step — the agent is asked once (not on every green commit), then a person. if (conflict) return (await conflictStep(db, { ...ref, task: { ...ref.task, prUrl: ref.task.prUrl ?? gate.pull!.html_url } }, gate.pull!)) === "requested"; const prArg = ref.task.prUrl ? "" : `, pr_url: ${gate.pull?.html_url ?? `PR #${n}`}`; await sendToSession(db, s.id, `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}). Если работа закончена — update_task(status: review${prArg}); если нет — продолжай.`); return true; } /** * PEP-196: the safety net for {@link wakeOnGreen}. A check report arrives once; if the agent was busy * then, or its PR is not written on the task yet, it would sleep forever. Once a minute: every task in * work whose agent is idle, with an open PR (from the task or its branch `task/`) and all `peppa/*` * checks of the head green, is woken (once per commit). */ export async function wakeIdleOnGreen(db: Db, gitea: GiteaClient = giteaForBot()): Promise { let woke = 0; for (const t of await listTasks(db, { statuses: ["proposing", "in_progress"] })) { const [s] = await listSessions(db, { active: true, taskId: t.id }); if (!s || (s.status !== "idle" && s.status !== "waiting_input")) continue; const [p] = await db.select().from(projects).where(eq(projects.id, t.projectId)); if (!p || (await isProjectPaused(db, p.id))) continue; try { const n = taskPrNumber(p, t.prUrl); const key = `${p.key}-${t.number}`; const pull = n ? await gitea.getPullRequest(p.giteaOwner, p.giteaRepo, n) : ((await gitea.openPullForBranch(p.giteaOwner, p.giteaRepo, `task/${key.toLowerCase()}`)) ?? (await gitea.openPullForBranch(p.giteaOwner, p.giteaRepo, `task/${key}`))); if (!pull || pull.state !== "open") continue; if ((await getSetting(db, wokeKey(t.id))) === pull.head.sha) continue; const st = await gitea.combinedStatus(p.giteaOwner, p.giteaRepo, pull.head.sha); const ours = (st.statuses ?? []).filter((x) => x.context.startsWith("peppa/")); if (!ours.length || ours.some((x) => x.status !== "success")) continue; const ref = await taskForCheck(db, p, pull.head.ref, pull.number); if (ref && ref.task.id === t.id && (await wakeOnGreen(db, ref, { sha: pull.head.sha, branch: pull.head.ref, prNumber: pull.number }, gitea))) woke++; } catch {} } return woke; } export interface CheckOutcome { task: string | null; /** What Peppa did: nothing, told the agent, restarted it, stopped it and told the superadmin, reset the counter. */ action: "none" | "agent" | "restarted" | "admin" | "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") { await wakeOnGreen(db, ref, r).catch(() => {}); 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)); await clearPlatformDelay(db, { projectId: project.id, taskId: ref.task.id }, "ci"); return { task: ref.key, action: "green" }; } if (r.state !== "failure" && r.state !== "error") return { task: ref.key, action: "none" }; // PEP-174: on pause the red check is recorded, but no agent is started and nobody is asked. if (await isProjectPaused(db, project.id)) 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); // PEP-150: red checks are not a product decision — the owner is not asked. The superadmin // is told once at the threshold while the agent goes on, and once more when it is stopped. if (attempts >= CI_STOP_ATTEMPTS && !newRun) return { task: ref.key, action: "none" }; if (attempts >= MAX_CI_ATTEMPTS && newRun) { const stop = attempts >= CI_STOP_ATTEMPTS; await platformDelay(db, { projectId: project.id, taskId: ref.task.id, sessionId }, { reason: "ci", state: stop ? "stopped" : "red", exhausted: stop, details: `${m("❌ {key}: проверки не проходят {n} раза подряд — агент не справился сам. Не прошла «{check}».", { key: ref.key, n: attempts, check: r.check })}${link ? `\n${m("Подробности: {url}", { url: link })}` : ""}${stop ? "" : `\n${m("Агент продолжает чинить, предел — {max} попыток.", { max: CI_STOP_ATTEMPTS })}`}`, }); if (stop) { if (sessionId) { await sendToSession(db, sessionId, `Проверки PR ${ref.key} красные ${attempts} раз подряд — это предел, администратор платформы уже знает. Не пушь новых попыток и не спрашивай PM: закончи ход и жди.`).catch(() => {}); } return { task: ref.key, action: "admin" }; } } const text = [ `❌ CI по ${ref.key}: упала проверка «${r.check}» (коммит ${r.sha.slice(0, 7)}, попытка ${attempts} из ${CI_STOP_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, env: payload.env === "staging" || payload.env === "prod" ? payload.env : "preview", 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"> { // PEP-296: a pull request of another repository is not «no PR» — accepting on it would close the story unmerged. if (foreignPrUrl(ref.project, ref.task.prUrl)) throw new PeppaError(m("Принять не удалось: {reason}", { reason: m("ссылка на результат ведёт не в код проекта") })); 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 superadmin 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) { // PEP-150: not the owner's to judge — the superadmin is asked (once per head commit). const { pipelineGuard } = await import("./pipeline-guard.ts"); await pipelineGuard(db, ref, gate.pull, changes); return { merged: false, reason: m("изменение конвейера требует ревью PM") }; } await mergeOrCloseEmpty(ref, gate.pull, gitea); return { merged: true }; }