// PEP-28: watchdog 2.0 — the watchdog fixes what it can by itself (restarts a crashed or // stalled runner within a limit), reminds about unanswered questions and escalates them, // and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env. import { asIs, m } from "@peppa/shared/i18n"; import { and, eq, gte, inArray, isNull, sql } from "drizzle-orm"; import { alertAdmins, deleteSetting, deliverToUser, getBudgetState, getSession, getSetting, listSessions, logSessionEvent, pendingSessionQuestions, PeppaError, questionIsFreeText, projectAudience, raiseSessionQuestion, platformFailure, touchQuestion, clearPlatformDelay, sessionDelay, sendProjectMessage, setSetting, updateSession, type SessionView, getIntakeState, isProjectPaused, pausedProjectIds, } from "@peppa/core"; import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { killRunner, resumeSession, stopSession } from "./sessions.ts"; import * as tmux from "./tmux.ts"; export interface WatchdogSettings { /** Automatic restarts of one runner within the window; 0 = off. */ restartMax: number; restartWindowMin: number; /** Pause before restart attempt 1, 2, 3… (the last one repeats). */ restartDelaysMin: number[]; /** A stalled runner whose alert got no answer this long is restarted; 0 = never. */ stallRestartMin: number; /** A reminder about an unanswered question after this (PEP-173: 4 h); 0 = off. */ remindMin: number; /** How many reminders one question gets (PEP-173: one — no nagging). */ remindMax: number; /** Reminders go only in working time (PEP-173): hours [workFrom, workTo) on workDays (1 = Mon … 7 = Sun), platform time zone. */ workFrom: number; workTo: number; workDays: number[]; /** Then the platform admins hear about it; 0 = off. */ escalateMin: number; /** A story runner in waiting_input with nothing asked is stopped after this; 0 = never. */ idleStopHours: number; /** PEP-150: checks of a result's head commit that have not started for this long are a delay; 0 = off. */ checksStuckMin: number; } export const WATCHDOG_DEFAULTS: WatchdogSettings = { restartMax: 3, restartWindowMin: 24 * 60, restartDelaysMin: [1, 5, 15], stallRestartMin: 60, remindMin: 240, remindMax: 1, workFrom: 9, workTo: 19, workDays: [1, 2, 3, 4, 5], // Stuck questions are on the superadmin's dashboard (PEP-167) — no extra message by default. escalateMin: 0, idleStopHours: 24, checksStuckMin: 15, }; const KEY = "platform.watchdog"; const envName = (k: string) => `PEPPA_WATCHDOG_${k.replace(/[A-Z]/g, (c) => `_${c}`).toUpperCase()}`; function parseValue(k: keyof WatchdogSettings, v: string): number | number[] { if (k === "restartDelaysMin" || k === "workDays") { const list = v.split(",").map((x) => Number(x.trim())); if (!list.length || list.some((n) => !Number.isFinite(n) || n < 0)) throw new PeppaError(m("{key}: список минут через запятую, напр. 1,5,15", { key: k })); return list; } const n = Number(v); if (!Number.isFinite(n) || n < 0) throw new PeppaError(m("{key}: нужно число ≥ 0", { key: k })); return n; } /** Defaults ← env `PEPPA_WATCHDOG_*` ← `platform.watchdog`. */ export async function getWatchdogSettings(db: Db): Promise { const out: WatchdogSettings = { ...WATCHDOG_DEFAULTS, restartDelaysMin: [...WATCHDOG_DEFAULTS.restartDelaysMin], workDays: [...WATCHDOG_DEFAULTS.workDays] }; for (const k of Object.keys(out) as (keyof WatchdogSettings)[]) { const v = process.env[envName(k)]; if (v) (out as any)[k] = parseValue(k, v); } return { ...out, ...((await getSetting>(db, KEY)) ?? {}) }; } /** `peppa platform watchdog key=value…` / `reset`. */ export async function setWatchdogSettings(db: Db, pairs: string[]): Promise { if (pairs.length === 1 && pairs[0] === "reset") { await deleteSetting(db, KEY); return getWatchdogSettings(db); } const cur = (await getSetting>(db, KEY)) ?? {}; for (const p of pairs) { const [k, v] = p.split("="); if (!k || v === undefined || !(k in WATCHDOG_DEFAULTS)) throw new PeppaError(m("неизвестная настройка «{name}»; есть: {keys}", { name: p, keys: Object.keys(WATCHDOG_DEFAULTS).join(", ") })); if (v === "-") delete (cur as any)[k]; else (cur as any)[k] = parseValue(k as keyof WatchdogSettings, v); } await setSetting(db, KEY, cur); return getWatchdogSettings(db); } // ── runner state ────────────────────────────────────────────────────────────────── /** Merges into `sessions.watch_state` (and into the view in hand). */ export async function patchWatch(db: Db, s: SessionView, patch: Partial, extra: Parameters[2] = {}): Promise { const next: WatchState = { ...(s.watchState ?? {}), ...patch }; for (const k of Object.keys(next) as (keyof WatchState)[]) if (next[k] === undefined) delete next[k]; s.watchState = next; await updateSession(db, s.id, { ...extra, watchState: next }); } // ── automatic restarts ──────────────────────────────────────────────────────────── const RESTARTABLE_TASK = ["proposing", "in_progress"]; /** Why the runner may not be restarted automatically (null = it may). */ async function restartBlocker(db: Db, s: SessionView, cfg: WatchdogSettings, now: number): Promise { if (cfg.restartMax <= 0) return m("выключен"); if (!s.taskId || !s.taskStatus || !RESTARTABLE_TASK.includes(s.taskStatus)) return m("задача не в работе"); if (s.status === "rate_limited" || s.resumeAt) return m("лимит"); if (await getBudgetState(db, s.taskId)) return m("бюджет"); const recent = restartsInWindow(s, cfg, now); if (recent.length >= cfg.restartMax) return cfg.restartWindowMin % 60 === 0 ? m("авто-перезапуски исчерпаны ({max} за {n} ч)", { max: cfg.restartMax, n: cfg.restartWindowMin / 60 }) : m("авто-перезапуски исчерпаны ({max} за {n} мин)", { max: cfg.restartMax, n: cfg.restartWindowMin }); return null; } const restartsInWindow = (s: SessionView, cfg: WatchdogSettings, now: number) => (s.watchState?.restarts ?? []).filter((t) => now - t < cfg.restartWindowMin * 60_000); /** * The agent process died (non-zero exit) or its tmux session is gone. A story at work gets * a planned restart after a pause instead of a question; otherwise the PM is asked as before. * Returns true when a restart was planned. */ export async function onRunnerCrash( db: Db, s: SessionView, reason: "crash" | "gone", alert: string, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }, ): Promise { const now = o.now.getTime(); const blocker = await restartBlocker(db, s, o.cfg, now); if (!blocker) { const n = restartsInWindow(s, o.cfg, now).length; const delays = o.cfg.restartDelaysMin.length ? o.cfg.restartDelaysMin : [0]; const at = now + delays[Math.min(n, delays.length - 1)]! * 60_000; await patchWatch(db, s, { restartAt: at, restartReason: reason }, { status: "failed", endedAt: o.now }); await logSessionEvent(db, s, "restart_planned", { reason, attempt: n + 1, of: o.cfg.restartMax, at: new Date(at).toISOString() }); o.log(`#${s.id} ${s.taskKey ?? ""}: ${reason}, restart ${n + 1}/${o.cfg.restartMax} at ${new Date(at).toISOString()}`); // PEP-150: the story shows the delay line; the superadmin hears only if the restarts run out. await sessionDelay(db, s, { reason: "agent", state: "restart", quiet: true, details: alert, now: o.now, log: o.log }); return true; } await updateSession(db, s.id, { status: "failed", endedAt: o.now }); // PEP-150: nothing to the owner — the superadmin gets one message, the story the delay line. await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: `${alert}\n\n${m("Сам не перезапустится: {reason}.", { reason: blocker })}`, now: o.now, log: o.log }); return false; } /** Planned restarts that are due (`failed` runners with `watch_state.restartAt`). */ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { const rows = await db .select({ id: sessions.id }) .from(sessions) .where(and(eq(sessions.status, "failed"), sql`json_extract(${sessions.watchState}, '$.restartAt') is not null`)); for (const { id } of rows) { const s = await getSession(db, id); const ws = s.watchState ?? {}; if (ws.restartAt == null || ws.restartAt > o.now.getTime()) continue; // PEP-174: a project on pause keeps its planned restart until «Продолжить». if (await isProjectPaused(db, s.projectId)) continue; const clear = { restartAt: undefined, restartReason: undefined }; // The PM may have started another runner for the story, or moved it on. const other = s.taskId ? (await listSessions(db, { active: true, taskId: s.taskId })).length : 0; const blocker = other ? m("задачу уже ведёт другой агент") : await restartBlocker(db, s, o.cfg, o.now.getTime()); if (blocker) { await patchWatch(db, s, clear); await logSessionEvent(db, s, "restart_skipped", { why: blocker }); if (!other && s.taskStatus && RESTARTABLE_TASK.includes(s.taskStatus)) await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: агент остановился с ошибкой, сам не перезапустился: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log }); continue; } const restarts = [...restartsInWindow(s, o.cfg, o.now.getTime()), o.now.getTime()]; await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined }); try { await resumeSession(db, s.id, { prompt: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`, }); await logSessionEvent(db, s, "auto_restarted", { reason: ws.restartReason, attempt: restarts.length, of: o.cfg.restartMax }); o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`); if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent"); } catch (e) { await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message }); // PEP-150: a failed restart is an attempt — the next one follows the same schedule; the // superadmin is told once the attempts have run out. The error itself goes to Bugsink. const fresh = await getSession(db, s.id).catch(() => s); const left = fresh.status === "failed" && !(await restartBlocker(db, s, o.cfg, o.now.getTime())); if (left) { const delays = o.cfg.restartDelaysMin.length ? o.cfg.restartDelaysMin : [0]; await patchWatch(db, s, { restartAt: o.now.getTime() + delays[Math.min(restarts.length, delays.length - 1)]! * 60_000, restartReason: ws.restartReason }); } await sessionDelay(db, s, { reason: "agent", state: left ? "restart" : "down", quiet: left, exhausted: !left, resume: s.id, details: m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }), error: e, now: o.now, log: o.log, }); } } } /** * The PM did not react to a stall alert for `stallRestartMin`: kill the stuck agent and * restart it now (counts against the restart limit). Returns true when it did. */ export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { const at = s.watchState?.stallAlertAt; if (!at || o.cfg.stallRestartMin <= 0 || o.now.getTime() - at < o.cfg.stallRestartMin * 60_000) return false; const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime()); if (blocker) { await patchWatch(db, s, { stallAlertAt: undefined }); await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker }); await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: работа зависла, сам не перезапустится: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log }); return false; } await killRunner(s).catch(() => {}); await patchWatch(db, s, { stallAlertAt: undefined, restartAt: o.now.getTime(), restartReason: "stall" }, { status: "failed", endedAt: o.now }); await logSessionEvent(db, s, "restart_planned", { reason: "stall", attempt: restartsInWindow(s, o.cfg, o.now.getTime()).length + 1, of: o.cfg.restartMax }); await restartTick(db, o); return true; } // ── reminders and escalation ────────────────────────────────────────────────────── const REMIND_KINDS = ["question", "permission", "approval"] as const; const KIND_RU: Record = { question: m("Вопрос"), permission: m("Разрешение"), approval: m("Одобрение плана") }; /** * Unanswered questions: reminders to the project's people after `remindMin` and 2×, then the * platform admins after `escalateMin`. `questions.reminders` is claimed atomically, so every * message goes out once whoever ticks. Only questions of the last day (no flood of old ones). */ /** PEP-173: is it working time in the platform's time zone (PEPPA_TZ, else this machine's)? */ export function inWorkingTime(now: Date, cfg: Pick): boolean { const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now); const hour = Number(parts.find((x) => x.type === "hour")?.value ?? 0); const day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(parts.find((x) => x.type === "weekday")?.value ?? "") + 1; return cfg.workDays.includes(day) && hour >= cfg.workFrom && hour < cfg.workTo; } export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { const { remindMin, escalateMin } = o.cfg; if (remindMin <= 0 && escalateMin <= 0) return 0; const now = o.now.getTime(); const rows = await db .select({ q: questions, projectKey: projects.key, taskNumber: tasks.number }) .from(questions) .innerJoin(projects, eq(questions.projectId, projects.id)) .leftJoin(tasks, eq(questions.taskId, tasks.id)) .where(and(isNull(questions.answeredAt), inArray(questions.kind, [...REMIND_KINDS]), gestDay(now))); let sent = 0; const paused = await pausedProjectIds(db); for (const { q, projectKey, taskNumber } of rows) { // PEP-174: a project on pause sends no reminders (nor escalations). if (paused.has(q.projectId)) continue; // PEP-87: the analyst's questions close themselves at their deadline (PEP-84) — no nagging. if (q.taskId && (await getIntakeState(db, q.taskId))?.questionId === q.id) continue; const age = now - q.createdAt.getTime(); const ageMin = Math.round(age / 60_000); const n = q.reminders; const escalate = escalateMin > 0 && n < 3 && age >= escalateMin * 60_000; // PEP-173: one reminder (remindMax), not before remindMin, and only in working time — outside // it the reminder waits for the morning. const remind = !escalate && remindMin > 0 && n < o.cfg.remindMax && age >= (n + 1) * remindMin * 60_000 && inWorkingTime(o.now, o.cfg); if (!escalate && !remind) continue; const next = escalate ? 3 : n + 1; const [claimed] = await db .update(questions) .set({ reminders: next }) .where(and(eq(questions.id, q.id), eq(questions.reminders, n), isNull(questions.answeredAt))) .returning({ id: questions.id }); if (!claimed) continue; const where = taskNumber != null ? formatTaskKey(projectKey, taskNumber) : projectKey; const url = taskNumber != null ? `/t/${where}` : "/"; const short = q.text.length > 300 ? `${q.text.slice(0, 300)}…` : q.text; // PEP-139/140: an agent's own question is free text — the reminder keeps it as written. const body = questionIsFreeText(q) ? asIs(short) : short; if (escalate) { await alertAdmins(db, `esc:q${q.id}`, `${m("🚨 {where}: {kind} #{id} без ответа {min} мин — агент ждёт.", { where, kind: KIND_RU[q.kind]?.toLowerCase() ?? "вопрос", id: q.id, min: ageMin })}\n\n${body}`, o.log); } else { // PEP-151: in the chat a reminder refreshes the question's message, it is not a new one. await touchQuestion(db, q.id, now); for (const u of await projectAudience(db, q.projectId)) { const text = `${m("⏰ {where}: {kind} #{id} ждёт ответа {min} мин.", { where, kind: KIND_RU[q.kind] ?? "Вопрос", id: q.id, min: ageMin })}\n\n${body}`; const r = await deliverToUser(db, u, { event: "questions", projectId: q.projectId, dedupeKey: `remind:q${q.id}:${next}:${u.telegramChatId}`, pushKey: `remind:q${q.id}:${next}:u${u.id}`, telegram: { params: { text } }, push: { title: m("Ждёт ответа: {where}", { where }), body: body.slice(0, 200), url, tag: `remind:q${q.id}` }, now: o.now, }); if (r.telegram || r.push) sent++; } } o.log(`question #${q.id}: ${escalate ? "escalated to admins" : `reminder ${next}`} (${ageMin} min)`); } return sent; } const gestDay = (now: number) => gte(questions.createdAt, new Date(now - 24 * 60 * 60_000)); // ── idle runners ────────────────────────────────────────────────────────────────── /** A story runner in waiting_input with nothing asked for `idleStopHours` is stopped (resumable). */ export async function idleStopTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { if (o.cfg.idleStopHours <= 0) return 0; let stopped = 0; for (const s of await listSessions(db, { active: true })) { // PEP-149: an agent that ended its turn without a question is `idle` while its story is in work. const turnOver = s.status === "waiting_input" || (s.status === "idle" && ["proposing", "in_progress"].includes(s.taskStatus ?? "")); if (!turnOver || !s.taskId || !s.lastActivityAt) continue; const idleMs = o.now.getTime() - s.lastActivityAt.getTime(); if (idleMs < o.cfg.idleStopHours * 3600_000) continue; if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) continue; await stopSession(db, s.id); await logSessionEvent(db, s, "idle_stopped", { idleHours: Math.round(idleMs / 3600_000) }); const who = s.taskKey ?? m("Агент №{id}", { id: s.id }); await sendProjectMessage( db, s.projectId, m("💤 {who}: агент ждал {n} ч без вопросов — остановлен. Чтобы он продолжил, нажмите «Продолжить» на странице задачи.", { who, n: Math.round(idleMs / 3600_000) }), `idle-stop:s${s.id}:${s.generation}`, { title: m("Агент остановлен: {who}", { who }), url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}` }, ); o.log(`#${s.id} ${s.taskKey ?? ""}: idle ${Math.round(idleMs / 3600_000)}h in waiting_input, stopped`); stopped++; } return stopped; }