// PEP-158: an update of the product that did not come up (health check failed, the previous // version is back) goes to the agent of the story whose changes were in it — like red checks // (ci-feedback.ts): a message with the reason and the log tail to the live agent, otherwise the // story goes back to work with a new one. The owner sees only the delay line on that story; // the superadmin hears at the same thresholds as with checks. import { asIs, m } from "@peppa/shared/i18n"; import { getPlatformDelay, listSessions, logEvent, platformDelay, resolveTask, runLink, taskForCheck, type Project, type TaskRef } from "@peppa/core"; import type { releases, Db } from "@peppa/db"; import { CI_STOP_ATTEMPTS, MAX_CI_ATTEMPTS } from "./ci-feedback.ts"; import { moveTask } from "./flow.ts"; import { sendToSession } from "./sessions.ts"; type Release = typeof releases.$inferSelect; const LOG_LINES = 100; const tail = (log: string | null | undefined) => (log ?? "").trimEnd().split("\n").slice(-LOG_LINES).join("\n"); /** A story the owner took off work (backlog) or one waiting for their approval is left alone. */ const RETURNABLE = ["proposing", "in_progress", "review", "blocked", "done"]; const ENV_NAME: Record = { preview: "превью PR", staging: "staging", prod: "прод" }; export interface DeployReturn { task: string; /** Told the live agent, started a new one, stopped at the limit, the same version reported again, could not hand it over. */ action: "agent" | "restarted" | "stopped" | "none" | "failed"; attempts: number; } /** The story a failed version goes back to: the one with a live agent, otherwise the newest. */ async function storyOf(db: Db, project: Project, rel: Release): Promise<{ ref: TaskRef; sessionId: number | null } | null> { const refs: TaskRef[] = []; if (rel.env === "preview") { const ref = await taskForCheck(db, project, null, rel.prNumber).catch(() => null); if (ref) refs.push(ref); } else { for (const key of rel.tasks) { const ref = await resolveTask(db, key).catch(() => null); if (ref && ref.project.id === project.id) refs.push(ref); } } const fit = refs.filter((r) => !r.task.archivedAt && RETURNABLE.includes(r.task.status)).sort((a, b) => b.task.number - a.task.number); for (const ref of fit) { const [s] = await listSessions(db, { active: true, taskId: ref.task.id }); if (s) return { ref, sessionId: s.id }; } return fit[0] ? { ref: fit[0], sessionId: null } : null; } /** * Hands a failed (or rolled back) release to the agent of its story. `head` is the superadmin's * line about the version. Returns null when there is nobody to hand it to — the caller tells * the superadmin right away. */ export async function returnFailedRelease(db: Db, project: Project, rel: Release, head: string): Promise { const found = await storyOf(db, project, rel); if (!found) return null; const { ref, sessionId } = found; const scope = { projectId: project.id, taskId: ref.task.id, sessionId }; const state = `${rel.env}:${rel.sha}`; const prev = await getPlatformDelay(db, scope, "deploy"); // The same version reported twice is one attempt. if (prev?.state === state) return { task: ref.key, action: "none", attempts: prev.attempts }; // Versions in a row: a healthy one of the environment removes the record. const attempts = (prev?.attempts ?? 0) + 1; const stop = attempts >= CI_STOP_ATTEMPTS; const link = runLink(rel.runUrl); const why = `${head}\n${m("Причина: {reason}", { reason: rel.reason ? asIs(rel.reason) : m("неизвестна") })}${link ? `\n${m("Подробности: {url}", { url: link })}` : ""}`; const done = async (action: DeployReturn["action"]): Promise => { await logEvent(db, { projectId: project.id, taskId: ref.task.id, sessionId, type: "deploy_returned", payload: { env: rel.env, sha: rel.sha, status: rel.status, attempts, action } }).catch(() => null); return { task: ref.key, action, attempts }; }; if (stop) { await platformDelay(db, scope, { reason: "deploy", state: `${rel.env}:stopped`, exhausted: true, details: `${why}\n${m("{key}: версия не обновилась {n} раз подряд — агент не справился сам и остановлен.", { key: ref.key, n: attempts })}`, }); // The limit was reached before: the agent has been told already. if (prev?.exhausted) return done("none"); if (sessionId) { await sendToSession(db, sessionId, `Обновление версии продукта с изменениями ${ref.key} не поднялось ${attempts} раз подряд — это предел, администратор платформы уже знает. Не пушь новых попыток и не спрашивай PM: закончи ход и жди.`).catch(() => {}); } return done("stopped"); } const merged = ref.task.status === "done"; const text = [ `❌ Обновление версии продукта (${ENV_NAME[rel.env]}) с изменениями ${ref.key} не поднялось: ${rel.status === "rolled_back" ? "проверка здоровья не прошла, возвращена прежняя версия" : "выкладка упала"} (коммит ${rel.sha.slice(0, 7)}, попытка ${attempts} из ${CI_STOP_ATTEMPTS}).${link ? ` Лог: ${link}` : ""}`, `Причина: ${rel.reason ?? "неизвестна"}`, rel.logTail ? `Последние строки лога:\n${tail(rel.logTail)}` : "Лога в отчёте нет — открой ссылку.", `Повтор той же сборки даст тот же результат — найди и почини причину. Проверь локально: docker build ., запуск образа с PORT, curl по адресу проверки здоровья (deploy.health в .peppa/project.json).${ merged || rel.env !== "preview" ? ` Если PR ${ref.key} уже смержен — сделай исправление в новой ветке от свежей основной и открой новый PR (update_task с новым pr_url).` : " Запушь исправление в ту же ветку." } PM об этом не спрашивай: владелец проекта видит только строку задержки.`, ].join("\n\n"); let action: DeployReturn["action"]; let failure: unknown = null; try { if (sessionId) { await sendToSession(db, sessionId, text); // The work is not done: a story that went to review or was accepted goes back. if (ref.task.status !== "in_progress" && ref.task.status !== "proposing") await moveTask(db, ref, "in_progress"); action = "agent"; } else { await moveTask(db, ref, "in_progress", { prompt: text }); action = "restarted"; } } catch (e) { failure = e; action = "failed"; } // After the move: the sweep takes delays off accepted stories. const warn = attempts === MAX_CI_ATTEMPTS; await platformDelay(db, scope, { reason: "deploy", state, quiet: !failure && !warn, details: failure ? `${why}\n${m("Вернуть агенту {key} не удалось: {error}", { key: ref.key, error: asIs((failure as Error).message) })}` : `${why}\n${m("{key}: версия не обновляется {n} раза подряд — агент не справился сам.", { key: ref.key, n: attempts })}\n${m("Агент продолжает чинить, предел — {max} попыток.", { max: CI_STOP_ATTEMPTS })}`, }); return done(action); }