// PEP-150: a blocker that is not about the product (a crashed or stalled agent, a usage limit, // checks that don't start, a failed update of the product, an error of the platform itself) is // not the owner's business. The story is marked «задержка на нашей стороне» — one line in its // header and on its board card — the platform retries by itself, and the superadmin gets ONE // message with the details: again only when the state changed or the attempts ran out. import { platformZone } from "@peppa/shared/time"; import { projects, settings, tasks, type Db, keyPrefix } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { m as tr } from "@peppa/shared/i18n"; import { inArray, like } from "drizzle-orm"; import { logEvent } from "./audit.ts"; import { reportPlatformError } from "./error-report.ts"; import { alertAdmins, peppaCommit } from "./monitor.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; export type DelayReason = /** The agent crashed, vanished, stalled or could not be restarted. */ | "agent" /** The agent's turn broke with an error. */ | "turn" /** Usage limit, no spare subscription. */ | "limit" /** The checks of the result's head commit don't start. */ | "checks" /** Red checks several times in a row. */ | "ci" /** An agent could not be started on the story. */ | "start" /** The agent can't move on to the story (its working copy is not clean). */ | "switch" /** An update of the product failed or was rolled back. */ | "deploy" /** An accept could not be carried through. */ | "accept" /** PEP-198: the story is in work, its agent has been idle over an hour, the checks are green — nobody moves it. */ | "stuck" /** PEP-269: the result conflicts with the main branch and the agent could not resolve it. */ | "conflict" /** PEP-265: the agent's CLI waits on a question of its own at the start (trust, model, sign-in) — no action. */ | "hang"; export interface DelayScope { projectId: number; taskId?: number | null; sessionId?: number | null; } export interface PlatformDelay { projectId: number; taskId: number | null; sessionId: number | null; reason: DelayReason; /** When the delay began and when it was last reported (ms). */ since: number; at: number; /** How many times it was reported (= attempts made so far). */ attempts: number; state: string; /** No automatic attempts are left: a person has to look. */ exhausted: boolean; /** The state the superadmin was last told about (null — not told yet). */ alertedState: string | null; alertedExhausted: boolean; /** When the platform tries again (ms); null — nothing to retry. */ retryAt: number | null; /** The delay is forgotten by itself after this (ms). */ until: number | null; /** For the superadmin: what happened. */ details: string; /** PEP-209: the platform's commit the delay was recorded on — a fix released since makes an exhausted card stale. */ commit?: string | null; /** PEP-209: what the platform did on the last attempt (the superadmin's card). */ action?: string | null; } export interface DelayReport { reason: DelayReason; /** The whole message for the superadmin. */ details: string; /** A change of it sends the superadmin one more message. */ state?: string; exhausted?: boolean; /** Nothing to the superadmin until the attempts run out (a planned automatic restart). */ quiet?: boolean; /** Several stories behind one cause (a limited subscription, the checks queue) → one message. */ alertKey?: string; /** An error of the platform itself: also to Bugsink. */ error?: unknown; /** The stopped agent's session: the superadmin's Telegram message gets «Перезапустить» / «Остановить». */ resume?: number; /** Forget the delay this many minutes after the last report. */ ttlMin?: number; /** PEP-209: own retry schedule in minutes (the last one repeats) instead of `DELAY_RETRY_MIN`. */ retryMin?: number[]; /** PEP-209: the attempt count kept by the caller (else the previous one + 1). */ attempts?: number; /** PEP-209: what was done on this attempt. */ action?: string; /** PEP-209: the next attempt at this time (ms) instead of the schedule. */ retryAt?: number; /** PEP-209: the superadmin's message gets «Перезапустить» / «Перевести на ревью» / «Закрыть». */ buttons?: boolean; now?: Date; log?: (m: string) => void; } /** What the owner sees on the story instead of a message. */ export const PLATFORM_DELAY_LABEL = tr("Небольшая задержка на нашей стороне, от вас ничего не нужно"); /** Pause before retry 1, 2, 3… in minutes (the last one repeats). */ export const DELAY_RETRY_MIN = [1, 5, 15, 60]; /** Buttons the bot understands (`s::resume|stop`) under a message about a stopped agent. */ const sessionButtons = (sessionId?: number): Record => sessionId == null ? {} : { reply_markup: { inline_keyboard: [[{ text: tr("🔁 Перезапустить"), callback_data: `s:${sessionId}:resume` }, { text: tr("⏹ Остановить"), callback_data: `s:${sessionId}:stop` }]] } }; /** PEP-209: the delay card's buttons for the superadmin: `pd:::r|v|x` (bot). */ export const delayCallback = (scope: DelayScope, reason: DelayReason, action: DelayAction) => `pd:${scopeKey(scope)}:${reason}:${action === "restart" ? "r" : action === "review" ? "v" : "x"}`; export type DelayAction = "restart" | "review" | "close"; /** `pd:t12:stuck:v` → what to do with which delay; null — not a delay button. */ export function parseDelayCallback(data: string): { scope: { taskId: number | null; projectId: number | null }; reason: DelayReason; action: DelayAction } | null { const mm = data.match(/^pd:([tp])(\d+):([a-z]+):([rvx])$/); if (!mm || !(mm[3]! in DELAY_REASON_NAMES)) return null; const id = Number(mm[2]); return { scope: mm[1] === "t" ? { taskId: id, projectId: null } : { taskId: null, projectId: id }, reason: mm[3] as DelayReason, action: mm[4] === "r" ? "restart" : mm[4] === "v" ? "review" : "close" }; } const delayButtons = (scope: DelayScope, reason: DelayReason): Record => ({ reply_markup: { inline_keyboard: [ [{ text: tr("🔁 Перезапустить"), callback_data: delayCallback(scope, reason, "restart") }], ...(scope.taskId != null ? [[{ text: tr("📤 Перевести на ревью"), callback_data: delayCallback(scope, reason, "review") }]] : []), [{ text: tr("✖️ Закрыть"), callback_data: delayCallback(scope, reason, "close") }], ], }, }); const PREFIX = "platform.delay:"; const scopeKey = (s: DelayScope) => (s.taskId != null ? `t${s.taskId}` : `p${s.projectId}`); const key = (s: DelayScope, reason: DelayReason) => `${PREFIX}${scopeKey(s)}:${reason}`; export const getPlatformDelay = (db: Db, scope: DelayScope, reason: DelayReason) => getSetting(db, key(scope, reason)); /** * Records a delay on the platform's side (or one more attempt of an open one) and decides * whether the superadmin hears about it. Never throws: it is called from failure paths. */ export async function platformDelay(db: Db, scope: DelayScope, r: DelayReport): Promise { try { const now = (r.now ?? new Date()).getTime(); const k = key(scope, r.reason); const prev = await getSetting(db, k); const attempts = r.attempts ?? (prev?.attempts ?? 0) + 1; const exhausted = !!r.exhausted; const schedule = r.retryMin?.length ? r.retryMin : DELAY_RETRY_MIN; const rec: PlatformDelay = { projectId: scope.projectId, taskId: scope.taskId ?? null, sessionId: scope.sessionId ?? prev?.sessionId ?? null, reason: r.reason, since: prev?.since ?? now, at: now, attempts, state: r.state ?? "open", exhausted, alertedState: prev?.alertedState ?? null, alertedExhausted: prev?.alertedExhausted ?? false, retryAt: exhausted ? null : r.retryAt ?? now + schedule[Math.min(Math.max(attempts, 1) - 1, schedule.length - 1)]! * 60_000, until: r.ttlMin ? now + r.ttlMin * 60_000 : null, details: r.details, commit: peppaCommit(), action: r.action ?? null, }; const alert = exhausted ? !rec.alertedExhausted || rec.alertedState !== rec.state : !r.quiet && rec.alertedState !== rec.state; if (alert) { rec.alertedState = rec.state; rec.alertedExhausted = exhausted; } await setSetting(db, k, rec); if (!prev || alert) { await logEvent(db, { projectId: rec.projectId, taskId: rec.taskId, sessionId: rec.sessionId, type: "platform_delay", payload: { reason: rec.reason, state: rec.state, attempts, exhausted, details: rec.details.slice(0, 2000) } }); } if (alert) { const tail = exhausted ? `\n${tr("Сама FORGE больше не пробует — посмотрите.")}` : ""; await alertAdmins(db, `delay:${r.alertKey ?? `${scopeKey(scope)}:${r.reason}:${rec.since}`}:${rec.state}${exhausted ? ":x" : ""}`, `${r.details}${tail}`, r.log ?? (() => {}), r.buttons ? delayButtons(scope, r.reason) : sessionButtons(r.resume)); } if (r.error) await reportPlatformError(db, r.error, { service: "watchdog", where: `delay:${r.reason}` }); return rec; } catch (e) { r.log?.(`platform delay (${r.reason}): ${(e as Error).message}`); return null; } } /** The cause is gone: the line leaves the story. `reason` omitted — every delay of the scope. */ export async function clearPlatformDelay(db: Db, scope: DelayScope, reason?: DelayReason): Promise { const rows = reason ? [{ key: key(scope, reason), value: await getSetting(db, key(scope, reason)) }].filter((r) => r.value) : await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}${scopeKey(scope)}:`)); for (const row of rows) { const d = row.value as PlatformDelay; await deleteSetting(db, row.key); await logEvent(db, { projectId: d.projectId, taskId: d.taskId, sessionId: d.sessionId, type: "platform_delay_cleared", payload: { reason: d.reason, attempts: d.attempts, minutes: Math.round((Date.now() - d.since) / 60_000) } }).catch(() => null); } return rows.length; } /** Every open delay, oldest first. */ export async function listPlatformDelays(db: Db): Promise { const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}`)); return rows.map((r) => r.value as PlatformDelay).sort((a, b) => a.since - b.since); } /** Ids of the stories that show the delay line. */ export async function delayedTaskIds(db: Db): Promise> { return new Set((await listPlatformDelays(db)).map((d) => d.taskId).filter((id): id is number => id != null)); } export async function taskDelayed(db: Db, taskId: number): Promise { return (await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, `${PREFIX}t${taskId}:`))).length > 0; } export const savePlatformDelay = (db: Db, d: PlatformDelay) => setSetting(db, key(d, d.reason), d); /** Task statuses in which a stopped agent holds the story up. */ const AT_WORK = ["proposing", "in_progress"]; /** * A delay caused by an agent's session. A story at work gets the delay line; a session without * a story (or whose story is not at work) holds nobody up — the superadmin is just told once. */ export async function sessionDelay( db: Db, s: { id: number; projectId: number; taskId: number | null; taskStatus?: string | null; generation: number }, r: DelayReport, ): Promise { if (s.taskId != null && s.taskStatus && AT_WORK.includes(s.taskStatus)) return platformDelay(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id }, r); try { if (!r.quiet) await alertAdmins(db, `delay:s${s.id}:g${s.generation}:${r.reason}:${r.state ?? "open"}`, r.details, r.log ?? (() => {}), sessionButtons(r.resume)); if (r.error) await reportPlatformError(db, r.error, { service: "watchdog", where: `delay:${r.reason}` }); } catch (e) { r.log?.(`platform delay (${r.reason}): ${(e as Error).message}`); } return null; } /** For the superadmin's list: what holds things up. */ export const DELAY_REASON_NAMES: Record = { agent: tr("агент остановился"), turn: tr("ход агента оборвался"), limit: tr("лимит подписки"), checks: tr("проверки не стартуют"), ci: tr("проверки не проходят"), start: tr("агент не запустился"), switch: tr("агент не может взять задачу"), deploy: tr("версия продукта не обновилась"), accept: tr("приёмка не доведена"), stuck: tr("задача не движется"), conflict: tr("изменения расходятся с основной версией"), hang: tr("агент завис на старте"), }; export interface DelayView extends PlatformDelay { /** «PEP-42» for a story, the project's key otherwise. */ key: string; title: string | null; url: string; } /** PEP-150: the open delays with their stories — the superadmin's block on the home page. */ export async function platformDelayOverview(db: Db): Promise { const list = await listPlatformDelays(db); if (!list.length) return []; const ps = await db.select({ id: projects.id, key: projects.key }).from(projects).where(inArray(projects.id, [...new Set(list.map((d) => d.projectId))])); const taskIds = [...new Set(list.map((d) => d.taskId).filter((id): id is number => id != null))]; const ts = taskIds.length ? await db.select({ id: tasks.id, number: tasks.number, title: tasks.title }).from(tasks).where(inArray(tasks.id, taskIds)) : []; return list.flatMap((d) => { const p = ps.find((x) => x.id === d.projectId); if (!p) return []; const t = d.taskId != null ? ts.find((x) => x.id === d.taskId) : null; const key = t ? formatTaskKey(p.key, t.number) : p.key; return [{ ...d, key, title: t?.title ?? null, url: t ? `/t/${key}` : `/p/${p.key}` }]; }); } /** PEP-209: the owner's one line on a delayed story — what to expect, never the terminal's text. */ export async function taskDelayLine(db: Db, taskId: number, o: { now?: Date; timeZone?: string } = {}): Promise { const list = (await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}t${taskId}:`))).map((r) => r.value as PlatformDelay); if (!list.length) return null; if (list.some((d) => d.exhausted)) return tr("Нужен администратор, мы ему сообщили"); const now = (o.now ?? new Date()).getTime(); const next = list.map((d) => d.retryAt).filter((x): x is number => x != null && x > now - 60_000).sort((a, b) => a - b)[0]; // PEP-268: a failure of the platform itself — the story keeps all its attempts and goes on by itself. const platform = list.some((d) => d.state === "platform"); if (next == null) return platform ? tr("Сбой на нашей стороне, чиним — задача продолжится сама") : tr("Задерживается на нашей стороне, мы этим занимаемся"); const tz = o.timeZone ?? platformZone(); const time = new Intl.DateTimeFormat("ru-RU", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(Math.max(next, now))); const day = (t: number) => new Intl.DateTimeFormat("en-CA", { timeZone: tz }).format(new Date(t)); if (platform) return day(next) !== day(now) ? tr("Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}", { time }) : tr("Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}", { time }); if (day(next) !== day(now)) return tr("Задерживается на нашей стороне. Следующая попытка завтра в {time}", { time }); return tr("Задерживается на нашей стороне. Следующая попытка в {time}", { time }); } /** PEP-209: the superadmin's home line — how many delays, how many need a person. */ export async function platformDelayCounts(db: Db): Promise<{ total: number; admin: number }> { const list = await listPlatformDelays(db); return { total: list.length, admin: list.filter((d) => d.exhausted).length }; }