PEP-158: a failed product update goes back to the story's agent with the reason and the log
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
1bce775b14
commit
38da8ee85a
@ -61,6 +61,7 @@
|
||||
- **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:<taskId>` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts`
|
||||
- **Мерж только со свежим main внутри (PEP-127)**: `prGate` закрыт с `behind: true`, если ветка открытого PR не содержит голову основной (`pullBehind`: `merge_base` ≠ `base.sha` из ответа Gitea); `reviewGate` агента `behind` пропускает. Обновляет Пеппа — `GiteaClient.updatePullBranch` (`POST /pulls/{n}/update`, merge), раз на head SHA (`updateSha` в `review.hold` / `accept.pending` / `autonomy.merge`), потом ждёт проверок нового коммита: `reviewCardTick`, `pendingAcceptTick`, `autoMergeReviews`. `deferAccept` запоминает «Принять» при конфликте, отставшей ветке и идущих проверках; красные — отказ с причиной
|
||||
- **Сбои не идут пользователю (PEP-150)**: блокер не про продукт (упал/завис агент, оборвался ход, лимит, проверки не стартуют или красные, агент не запустился, не обновилась версия, приёмка не доведена) владельцу не шлём. Единая функция `platformDelay(db, {projectId, taskId?, sessionId?}, {reason, details, state?, exhausted?, quiet?, alertKey?, error?, ttlMin?})` (core/platform-delay.ts; строка `settings` `platform.delay:t<taskId>|p<projectId>:<reason>`, причины `agent|turn|limit|checks|ci|start|switch|deploy|accept`): считает попытки и паузу (`DELAY_RETRY_MIN` 1,5,15,60), суперадмину — одно сообщение (`alertAdmins`: Telegram, push, «Все события»), снова — только при смене `state` или `exhausted`; `quiet` — молчать до исчерпания (запланированный перезапуск); `alertKey` — одно сообщение на несколько задач (лимит подписки, очередь проверок); `error` → Bugsink. `sessionDelay` — то же от сессии: строка только у задачи в работе, иначе просто сообщение суперадмину. Владелец видит `PLATFORM_DELAY_LABEL` в шапке задачи (`taskDelayed`; в «Продакте» — `STORY_PRODUCT_TEXT.delayed`) и на карточке доски (`delayedTaskIds`); суперадмин — блок «Задержки на стороне Peppa FACTORY» на Главной (`platformDelayOverview`, `components/PlatformDelays.tsx`). Снимают: место, где причина прошла (`clearPlatformDelay`), и сверка `platformDelayTick` (runner/platform-delays.ts, тик вачдога): задача ушла в done/архив/бэклог, истёк `until`, у задачи снова работающий агент, лимит прошёл; она же повторяет — «продолжай» после оборванного хода (до `TURN_RETRY_MAX` 3), запуск агента (`startDelay`, до `START_RETRY_MAX` 5; проект с pick=auto повторяет диспетчер). **Зависшие проверки**: `checksQueueTick` (раз в минуту рядом с `pollChecks`; порог `checksStuckMin` в `platform.watchdog`, 15, 0 — выкл; память `checks.wait:<taskId>`, эпизод очереди `checks.queue`): у головы открытого PR нет статусов `peppa/*` дольше порога → задержка, агенту один раз «жди, тебя разбудят», суперадмину одно «Очередь проверок: N ждут, старшему M мин»; статусы появились — снято, все зелёные — агент разбужен. **Красные проверки**: на `MAX_CI_ATTEMPTS` (3) — суперадмину, агент продолжает; на `CI_STOP_ATTEMPTS` (6) — агент остановлен, действие `admin`. **Лимит** (runner/limit-delay.ts — лёгкий модуль, его грузит хук): `limitDelay` — задержка + раз на окно вопрос владельцу «Добавить подписку / Подождать» (`limit.hint:<projectId>`; ответ агенту не уходит, закрывается сам в `limitOver`). Приёмка не доведена (конфликт 3 раза / 24 ч) — суперадмину, а задача возвращается в обычный путь через `review.hold`. Новый путь, который сообщает о сбое, — через `platformDelay`/`sessionDelay`, а не `raiseSessionQuestion(…, "attention")`. В тестах суперадмин с Telegram — `superadmin()` из helpers.ts (возвращает чтение его сообщений). **Guard конвейера** (runner/pipeline-guard.ts `pipelineGuard`; зовут `autoMergeTask` и `autoCloseReviews`): PR меняет `.gitea/`, `checks` или `deploy` → вопрос суперадмину в платформенном проекте (`PEPPA_PLATFORM_KEY`, как запрос подписки PEP-116) с ключом задачи и проектом, варианты `GUARD_ACCEPT` / `GUARD_RETURN`, раз на головной коммит и не больше одного открытого на задачу (`guard.task:<taskId>`, `guard.question:<qid>`); `onGuardAnswer`: «Принять» = `acceptStory`, иное — задача в работу с указанием агенту; владельцу ничего. Тест `platform-delays.test.ts`
|
||||
- **Неудачная версия — агенту (PEP-158)**: `rolled_back`/`failed` в `notifyRelease` идёт в `returnFailedRelease` (runner/deploy-feedback.ts): задача версии (preview — задача PR, иначе `releases.tasks`; одна — с живым агентом, иначе с наибольшим номером; не архив, не бэклог; принятая `done` возвращается в работу) получает причину и хвост лога — живому агенту `sendToSession`, иначе `moveTask(in_progress, { prompt })`. Счётчик — `attempts` задержки `platform.delay:t<taskId>:deploy` (состояние `<env>:<sha>`, повтор отчёта не считается): 3-я неудача подряд (`MAX_CI_ATTEMPTS`) — одно сообщение суперадмину, 6-я (`CI_STOP_ATTEMPTS`) — агенту «остановись», суперадмину «попытки исчерпаны» (`<env>:stopped`). Вернуть некому — суперадмину сразу, задержка на проекте (PEP-150). Здоровая версия окружения снимает задержки `deploy` со всех задач проекта; `ensureProductLinkTask` (PEP-145) ждёт, пока версию для проверки чинит агент задачи. Владельцу — только строка задержки. Тест `deploy-feedback.test.ts`
|
||||
- **«Готова к ревью» только когда можно смержить (PEP-127)**: `reviewGate` (flow.ts) при ошибке Gitea закрыт (`GATE_UNKNOWN_REASON`). Сообщение «готова к ревью» из Stop-хука и ревьюера идёт только через `sendReviewCard` (core/review-card.ts): `prGate` ok в момент отправки → вопрос `attention`; иначе придерживается в `settings` `review.hold:<taskId>` (`{text, at, rebaseSha}`), событие `awaiting_checks`. `reviewCardTick` (runner/review-card.ts, вачдог раз в минуту рядом с `reviewTick`): придержанное → отправить при зелёном гейте; конфликт → `requestRebase` один раз на head SHA; открытое сообщение у PM и PR стал в конфликте → ответ system `REVIEW_REVOKED_ANSWER`, rebase, после возврата в ревью — новое сообщение. Новый путь, который шлёт PM «Принять», — только через `sendReviewCard`. `mock-gitea.down = true` — 500 на всё
|
||||
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
|
||||
- **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние)
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
## 1. Возврат неудачной версии агенту
|
||||
|
||||
- [ ] 1.1 `runner/deploy-feedback.ts`: `returnFailedRelease` — выбор задачи, счётчик в задержке `deploy`, текст агенту с причиной и логом, живому агенту сообщением, иначе возврат в работу
|
||||
- [ ] 1.2 Пределы: 3-я неудача — сообщение суперадмину, 6-я — агенту «остановись», суперадмину «попытки исчерпаны»; не удалось вернуть — суперадмину сразу
|
||||
- [ ] 1.3 `notifyRelease`: неудачная версия идёт через `returnFailedRelease`, некому — прежнее сообщение суперадмину; здоровая версия снимает задержки `deploy` окружения со всех задач проекта
|
||||
- [ ] 1.4 `ensureProductLinkTask` не заводит системную задачу, пока версию для проверки чинит агент задачи
|
||||
- [x] 1.1 `runner/deploy-feedback.ts`: `returnFailedRelease` — выбор задачи, счётчик в задержке `deploy`, текст агенту с причиной и логом, живому агенту сообщением, иначе возврат в работу
|
||||
- [x] 1.2 Пределы: 3-я неудача — сообщение суперадмину, 6-я — агенту «остановись», суперадмину «попытки исчерпаны»; не удалось вернуть — суперадмину сразу
|
||||
- [x] 1.3 `notifyRelease`: неудачная версия идёт через `returnFailedRelease`, некому — прежнее сообщение суперадмину; здоровая версия снимает задержки `deploy` окружения со всех задач проекта
|
||||
- [x] 1.4 `ensureProductLinkTask` не заводит системную задачу, пока версию для проверки чинит агент задачи
|
||||
|
||||
## 2. Тексты и тесты
|
||||
|
||||
- [ ] 2.1 Переводы новых текстов суперадмину (en, kk)
|
||||
- [ ] 2.2 Тест `deploy-feedback.test.ts` по сценариям спеки; правка `platform-delays.test.ts`
|
||||
- [x] 2.1 Переводы новых текстов суперадмину (en, kk)
|
||||
- [x] 2.2 Тест `deploy-feedback.test.ts` по сценариям спеки; правка `platform-delays.test.ts`
|
||||
- [ ] 2.3 AGENTS.md, память проекта, полный прогон проверок
|
||||
|
||||
124
packages/runner/src/deploy-feedback.ts
Normal file
124
packages/runner/src/deploy-feedback.ts
Normal file
@ -0,0 +1,124 @@
|
||||
// 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<Release["env"], string> = { 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<DeployReturn | null> {
|
||||
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<DeployReturn> => {
|
||||
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);
|
||||
}
|
||||
@ -3,7 +3,7 @@
|
||||
// here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a
|
||||
// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API).
|
||||
import { asIs, m } from "@peppa/shared/i18n";
|
||||
import { clearPlatformDelay, getPlatformDelay, platformDelay, taskForCheck, answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question, platformFailure, isProjectPaused } from "@peppa/core";
|
||||
import { clearPlatformDelay, listPlatformDelays, platformDelay, taskForCheck, answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question, platformFailure, isProjectPaused } from "@peppa/core";
|
||||
import { projects, questions, releases, settings, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { deployPlatform, isPlatform } from "./platform-release.ts";
|
||||
@ -114,10 +114,14 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
|
||||
|
||||
async function notifyRelease(db: Db, project: Project, rel: Release) {
|
||||
if (rel.status === "healthy") {
|
||||
// PEP-150: a healthy version of the same environment ends the delay of a failed one.
|
||||
// PEP-150/158: a healthy version of the same environment ends the delay of a failed one —
|
||||
// on the project and on the stories whose agents were fixing it (a preview: its own story).
|
||||
const ref = rel.env === "preview" ? await taskForCheck(db, project, null, rel.prNumber).catch(() => null) : null;
|
||||
const scope = { projectId: project.id, taskId: ref?.task.id ?? null };
|
||||
if (ref || (await getPlatformDelay(db, scope, "deploy"))?.state.startsWith(`${rel.env}:`)) await clearPlatformDelay(db, scope, "deploy");
|
||||
for (const d of await listPlatformDelays(db)) {
|
||||
if (d.projectId !== project.id || d.reason !== "deploy") continue;
|
||||
if (rel.env === "preview" ? !ref || d.taskId !== ref.task.id : !d.state.startsWith(`${rel.env}:`)) continue;
|
||||
await clearPlatformDelay(db, { projectId: project.id, taskId: d.taskId }, "deploy");
|
||||
}
|
||||
}
|
||||
const tasks = rel.tasks.join(", ");
|
||||
const v = { project: asIs(project.name), sha: short(rel.sha), tasks };
|
||||
@ -127,10 +131,12 @@ async function notifyRelease(db: Db, project: Project, rel: Release) {
|
||||
rel.status === "rolled_back"
|
||||
? m("❌ {project}: обновление {sha} ({env}) не прошло проверку — возвращена прежняя версия {prev}.", { ...v, env: rel.env, prev: short(rel.previousSha) })
|
||||
: m("❌ {project}: обновление {sha} ({env}) не прошло проверку.", { ...v, env: rel.env });
|
||||
// PEP-150: a failed update is not the owner's to fix — the superadmin gets one message per
|
||||
// failed version; the story of a preview shows the delay line until a healthy one comes.
|
||||
const ref = rel.env === "preview" ? await taskForCheck(db, project, null, rel.prNumber).catch(() => null) : null;
|
||||
await platformDelay(db, { projectId: project.id, taskId: ref?.task.id ?? null }, {
|
||||
// PEP-158: the version goes back to the agent of the story whose changes were in it; the
|
||||
// owner sees the delay line on that story, the superadmin hears at the limits.
|
||||
const { returnFailedRelease } = await import("./deploy-feedback.ts");
|
||||
if (await returnFailedRelease(db, project, rel, head)) return;
|
||||
// PEP-150: nobody to hand it to — the superadmin gets one message per failed version.
|
||||
await platformDelay(db, { projectId: project.id, taskId: null }, {
|
||||
reason: "deploy",
|
||||
state: `${rel.env}:${rel.sha}`,
|
||||
exhausted: true,
|
||||
|
||||
@ -20,6 +20,7 @@ export * from "./feedback.ts";
|
||||
export * from "./triage.ts";
|
||||
export * from "./ci-feedback.ts";
|
||||
export * from "./deploy.ts";
|
||||
export * from "./deploy-feedback.ts";
|
||||
export * from "./product-link.ts";
|
||||
export * from "./platform-release.ts";
|
||||
export * from "./platform-build.ts";
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
getProductLinkState,
|
||||
getPublishChoice,
|
||||
getSetting,
|
||||
listPlatformDelays,
|
||||
listProjects,
|
||||
logEvent,
|
||||
openProductLinkTask,
|
||||
@ -69,6 +70,8 @@ export async function productLinkTick(db: Db, o: ProductLinkTickOptions = {}): P
|
||||
export async function ensureProductLinkTask(db: Db, project: Project, o: ProductLinkTickOptions = {}): Promise<string | null> {
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
if (await openProductLinkTask(db, project.id)) return null;
|
||||
// PEP-158: the failed version to check is with the agent of its story already.
|
||||
if ((await listPlatformDelays(db)).some((d) => d.projectId === project.id && d.taskId != null && d.reason === "deploy" && !d.exhausted && d.state.startsWith("staging:"))) return null;
|
||||
const state = await getProductLinkState(db, project.id);
|
||||
if (state && now - state.at < minGapMs()) return null;
|
||||
const recent = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(10);
|
||||
|
||||
@ -136,6 +136,9 @@ export const runner: Dict = {
|
||||
"(неактуально: в версии для проверки появились новые изменения)": "(no longer relevant: the version for review has new changes)",
|
||||
"❌ {project}: обновление {sha} ({env}) не прошло проверку — возвращена прежняя версия {prev}.": "❌ {project}: update {sha} ({env}) did not pass the check — the previous version {prev} is back.",
|
||||
"❌ {project}: обновление {sha} ({env}) не прошло проверку.": "❌ {project}: update {sha} ({env}) did not pass the check.",
|
||||
"{key}: версия не обновилась {n} раз подряд — агент не справился сам и остановлен.": "{key}: the version failed to update {n} times in a row — the agent could not fix it and was stopped.",
|
||||
"{key}: версия не обновляется {n} раза подряд — агент не справился сам.": "{key}: the version has failed to update {n} times in a row — the agent could not fix it.",
|
||||
"Вернуть агенту {key} не удалось: {error}": "Could not hand it back to the agent of {key}: {error}",
|
||||
"Причина: {reason}": "Reason: {reason}",
|
||||
неизвестна: "unknown",
|
||||
"✅ {project}: staging обновлён — {sha} · стори: {tasks}{host}\nВыкатить этот релиз в прод?":
|
||||
|
||||
@ -105,6 +105,9 @@ export const runner: Dict = {
|
||||
"(неактуально: в версии для проверки появились новые изменения)": "(өзекті емес: тексеруге арналған нұсқада жаңа өзгерістер бар)",
|
||||
"❌ {project}: обновление {sha} ({env}) не прошло проверку — возвращена прежняя версия {prev}.": "❌ {project}: {sha} жаңартуы ({env}) тексерістен өтпеді — алдыңғы {prev} нұсқасы қайтарылды.",
|
||||
"❌ {project}: обновление {sha} ({env}) не прошло проверку.": "❌ {project}: {sha} жаңартуы ({env}) тексерістен өтпеді.",
|
||||
"{key}: версия не обновилась {n} раз подряд — агент не справился сам и остановлен.": "{key}: нұсқа қатарынан {n} рет жаңартылмады — агент өзі түзете алмады және тоқтатылды.",
|
||||
"{key}: версия не обновляется {n} раза подряд — агент не справился сам.": "{key}: нұсқа қатарынан {n} рет жаңартылмай жатыр — агент өзі түзете алмады.",
|
||||
"Вернуть агенту {key} не удалось: {error}": "{key} агентіне қайтару мүмкін болмады: {error}",
|
||||
"Причина: {reason}": "Себебі: {reason}",
|
||||
"неизвестна": "белгісіз",
|
||||
"✅ {project}: staging обновлён — {sha} · стори: {tasks}{host}\nВыкатить этот релиз в прод?": "✅ {project}: staging жаңартылды — {sha} · стори: {tasks}{host}\nБұл релизді продқа шығару керек пе?",
|
||||
|
||||
159
packages/testkit/test/deploy-feedback.test.ts
Normal file
159
packages/testkit/test/deploy-feedback.test.ts
Normal file
@ -0,0 +1,159 @@
|
||||
// PEP-158, spec delivery-pipeline «Проверка здоровья и откат»: an update of the product that
|
||||
// did not come up goes back to the agent of its story with the reason and the log; the owner
|
||||
// gets nothing but the delay line, the superadmin hears at the limits.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { core, db, project, runner, setDefaultOwner, teardown, type TestProject } from "./helpers.ts";
|
||||
import { questions, telegramOutbox, users } from "@peppa/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
const OWNER_CHAT = 9201;
|
||||
const ADMIN_CHAT = 9202;
|
||||
const REASON = "healthz не ответил за 2 минуты";
|
||||
const LOG = "Error: listen EADDRINUSE: address already in use :::3000";
|
||||
|
||||
before(async () => {
|
||||
const owner = await core.upsertUserFromGitea(db, { id: 9201, login: "mock-owner-deploy" }, { access_token: "x" });
|
||||
const admin = await core.upsertUserFromGitea(db, { id: 9202, login: "mock-admin-deploy" }, { access_token: "x" });
|
||||
await db.update(users).set({ telegramChatId: OWNER_CHAT, telegramUserId: OWNER_CHAT }).where(eq(users.id, owner.id));
|
||||
await db.update(users).set({ telegramChatId: ADMIN_CHAT, telegramUserId: ADMIN_CHAT }).where(eq(users.id, admin.id));
|
||||
await core.setPlatformAdmins(db, ["mock-admin-deploy"]);
|
||||
setDefaultOwner(owner.id);
|
||||
});
|
||||
after(teardown);
|
||||
|
||||
const sentTo = async (chat: number) => (await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, chat))).map((r) => String(r.params.text));
|
||||
/** What the owner was asked or told about the failed version (the agent's own turn ends are not it). */
|
||||
const ownerHeard = async (projectId: number) => {
|
||||
const about = (t: string) => /healthz|EADDRINUSE|не прошло проверку|не обновил/.test(t);
|
||||
const qs = (await db.select().from(questions).where(eq(questions.projectId, projectId))).filter((q) => about(q.text));
|
||||
return qs.length + (await sentTo(OWNER_CHAT)).filter(about).length;
|
||||
};
|
||||
const adminHeard = async (key: string) => (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(key));
|
||||
|
||||
async function story(turns: Parameters<typeof project>[0]["turns"], status: "in_progress" | "done" | "backlog" = "in_progress") {
|
||||
const tp = await project({ turns });
|
||||
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status });
|
||||
const proj = await core.getProject(db, tp.key);
|
||||
const rel = (sha: string, status: "rolled_back" | "healthy" | "failed", o: { env?: "staging" | "prod"; tasks?: boolean } = {}) =>
|
||||
runner.recordRelease(db, proj, {
|
||||
env: o.env ?? "staging",
|
||||
sha,
|
||||
previousSha: "a1b2c3d4",
|
||||
image: null,
|
||||
host: `${proj.slug}-staging.test`,
|
||||
prNumber: null,
|
||||
status,
|
||||
reason: status === "healthy" ? null : REASON,
|
||||
runUrl: null,
|
||||
commits: o.tasks === false ? [] : [`Merge pull request 'x' from task/${tp.taskKey} into main`],
|
||||
logTail: status === "healthy" ? null : `step 1\n${LOG}`,
|
||||
});
|
||||
const id = (await tp.task()).id;
|
||||
return { tp, proj, rel, id, scope: { projectId: proj.id, taskId: id } };
|
||||
}
|
||||
const stopAll = async (_tp: TestProject, projectId: number) => {
|
||||
for (const s of await core.listSessions(db, { active: true, projectId })) await runner.stopSession(db, s.id);
|
||||
};
|
||||
const said = (tp: TestProject, text: string) => tp.log().some((e) => JSON.stringify(e).includes(text));
|
||||
|
||||
describe("Проверка здоровья и откат", () => {
|
||||
test("Неудачный релиз: работающий агент получает причину и лог, владелец и суперадмин — ничего", async () => {
|
||||
const s = await story([[{ say: "Работаю." }], [{ say: "Чиню." }], [{ say: "Чиню." }]]);
|
||||
await s.tp.start();
|
||||
await s.tp.waitLog("turn 0", (e) => e.ev === "prompt");
|
||||
await s.rel("d4e5f6a7", "rolled_back");
|
||||
await s.tp.waitLog("the agent got the reason", (e) => JSON.stringify(e).includes(REASON));
|
||||
assert.ok(said(s.tp, "EADDRINUSE"), "the log tail is in the message");
|
||||
assert.equal((await s.tp.task()).status, "in_progress");
|
||||
assert.equal(await core.taskDelayed(db, s.id), true, "the story shows the delay line");
|
||||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||||
assert.equal((await adminHeard(s.proj.name)).length, 0, "the first failure is the agent's to fix");
|
||||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 1);
|
||||
|
||||
// The same version reported again is not another attempt.
|
||||
await s.rel("d4e5f6a7", "rolled_back");
|
||||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 1);
|
||||
await stopAll(s.tp, s.proj.id);
|
||||
});
|
||||
|
||||
test("Следующая версия здорова: задержка снята, счётчик попыток начинается заново", async () => {
|
||||
const s = await story([[{ say: "Работаю." }], [{ say: "Чиню." }], [{ say: "Чиню." }], [{ say: "Чиню." }]]);
|
||||
await s.tp.start();
|
||||
await s.tp.waitLog("turn 0", (e) => e.ev === "prompt");
|
||||
await s.rel("11111111", "rolled_back");
|
||||
await s.rel("22222222", "failed");
|
||||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 2);
|
||||
await s.rel("33333333", "healthy", { env: "prod" });
|
||||
assert.equal(await core.taskDelayed(db, s.id), true, "another environment does not lift it");
|
||||
await s.rel("33333333", "healthy");
|
||||
assert.equal(await core.taskDelayed(db, s.id), false);
|
||||
await s.rel("44444444", "rolled_back");
|
||||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 1);
|
||||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||||
await stopAll(s.tp, s.proj.id);
|
||||
await core.clearPlatformDelay(db, s.scope);
|
||||
});
|
||||
|
||||
test("Агента нет — принятая задача возвращается в работу с новым агентом", async () => {
|
||||
const s = await story([[{ say: "Чиню." }]], "done");
|
||||
const out = await s.rel("d4e5f6a7", "rolled_back");
|
||||
assert.equal(out.status, "rolled_back");
|
||||
await s.tp.waitLog("a new agent got the reason", (e) => JSON.stringify(e).includes(REASON));
|
||||
assert.ok(said(s.tp, "EADDRINUSE"));
|
||||
assert.ok(said(s.tp, "новой ветке"), "the result is merged: a new branch and a new result");
|
||||
assert.equal((await s.tp.task()).status, "in_progress");
|
||||
assert.equal(await core.taskDelayed(db, s.id), true);
|
||||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||||
assert.equal((await adminHeard(s.proj.name)).length, 0);
|
||||
// PEP-145: the system story is not filed while the agent of the story is on it.
|
||||
assert.equal(await runner.ensureProductLinkTask(db, s.proj), null);
|
||||
await stopAll(s.tp, s.proj.id);
|
||||
});
|
||||
|
||||
test("Три и шесть неудачных релизов подряд: суперадмин — на пределах, агент остановлен", async () => {
|
||||
const s = await story(Array.from({ length: 9 }, () => [{ say: "Чиню." }]));
|
||||
await s.tp.start();
|
||||
await s.tp.waitLog("turn 0", (e) => e.ev === "prompt");
|
||||
const mine = () => adminHeard(s.tp.taskKey);
|
||||
await s.rel("00000001", "rolled_back");
|
||||
await s.rel("00000002", "rolled_back");
|
||||
assert.equal((await mine()).length, 0);
|
||||
await s.rel("00000003", "rolled_back");
|
||||
assert.equal((await mine()).length, 1, "three in a row: the superadmin is told once");
|
||||
assert.match((await mine())[0]!, /healthz не ответил/);
|
||||
assert.match((await mine())[0]!, /Агент продолжает чинить/);
|
||||
await s.rel("00000004", "rolled_back");
|
||||
await s.rel("00000005", "rolled_back");
|
||||
assert.equal((await mine()).length, 1, "retries are not news");
|
||||
await s.rel("00000006", "rolled_back");
|
||||
assert.equal((await mine()).length, 2);
|
||||
assert.match((await mine())[1]!, /остановлен/);
|
||||
assert.match((await mine())[1]!, /больше не пробует/);
|
||||
await s.tp.waitLog("the agent is told to stop", (e) => JSON.stringify(e).includes("это предел"));
|
||||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.exhausted, true);
|
||||
await s.rel("00000007", "rolled_back");
|
||||
assert.equal((await mine()).length, 2, "after the limit nothing new");
|
||||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||||
await s.rel("00000008", "healthy");
|
||||
assert.equal(await core.taskDelayed(db, s.id), false);
|
||||
await stopAll(s.tp, s.proj.id);
|
||||
});
|
||||
|
||||
test("Вернуть некому: суперадмин получает одно сообщение сразу", async () => {
|
||||
// No stories in the version; and a story the owner took off work is left alone.
|
||||
for (const s of [await story([]), await story([], "backlog")]) {
|
||||
await s.rel("d4e5f6a7", "rolled_back", { tasks: (await s.tp.task()).status === "backlog" });
|
||||
const mine = (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(s.proj.name) && t.includes("не прошло проверку"));
|
||||
assert.equal(mine.length, 1);
|
||||
assert.match(mine[0]!, /healthz не ответил/);
|
||||
assert.equal(await core.taskDelayed(db, s.id), false);
|
||||
assert.equal((await core.platformDelayOverview(db)).some((d) => d.projectId === s.proj.id && d.reason === "deploy" && d.taskId == null), true);
|
||||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||||
assert.equal((await s.tp.task()).status === "backlog" || (await core.listSessions(db, { active: true, projectId: s.proj.id })).length === 0, true);
|
||||
await s.rel("e5f6a7b8", "healthy");
|
||||
assert.equal((await core.platformDelayOverview(db)).some((d) => d.projectId === s.proj.id && d.reason === "deploy"), false);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user