// Watchdog: polls Peppa's tmux sessions, tracks activity, and alerts the PM when a // session dies, stalls, or hits a usage limit. Run under launchd with caffeinate. import { runnerTick } from "./runners.ts"; import { createHash } from "node:crypto"; import { backupDb, digestTick, platformDigestTick, recheckPlatformChannel, pruneChats, syncChats, getBudgetState, runAsActor, expireSessionQuestions, listSessions, logSessionEvent, pendingSessionQuestions, raiseSessionQuestion, updateSession, type SessionView, } from "@peppa/core"; import type { Db } from "@peppa/db"; import * as tmux from "./tmux.ts"; import { recordLimit } from "./limits.ts"; import { killRunner, resumeSession } from "./sessions.ts"; import { hostTick } from "./hosts.ts"; import { getSubscription, isUsable } from "@peppa/core"; import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts"; import { monitorTick } from "./monitor.ts"; import { platformBuildTick } from "./platform-build.ts"; import { incidentTick } from "./incidents.ts"; import { pollChecks } from "./ci-feedback.ts"; import { reviewTick } from "./reviewer.ts"; import { autonomyTick } from "./autonomy.ts"; import { intakeTick } from "./intake.ts"; import { budgetTick } from "./budgets.ts"; import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts"; import { serveRunnerCommands, type RunnerService } from "./runner-service.ts"; export interface WatchdogOptions { /** Current time (tests move it instead of waiting). */ now?: Date; intervalMs: number; /** A running session with an unchanged screen for this long is "stalled". */ stallMs: number; log?: (msg: string) => void; /** PEP-21: serve runner commands in this process (default true for runWatchdog). */ serveCommands?: boolean; } // Claude Code's limit banners ("…usage limit reached… resets 3pm", "You've hit your limit"). const LIMIT_RE = /(usage limit reached|limit reached.{0,40}reset|you've hit your (usage )?limit|out of extra usage)/i; /** Last non-empty screen lines — what the PM needs to see in an alert. */ function screenTail(screen: string, lines: number): string { return screen.split("\n").map((l) => l.trimEnd()).filter(Boolean).slice(-lines).join("\n"); } export async function tick(db: Db, opts: WatchdogOptions): Promise { // PEP-48: what the watchdog does is Peppa's own doing. return runAsActor({ kind: "system", channel: "watchdog" }, () => tickInner(db, opts)); } async function tickInner(db: Db, opts: WatchdogOptions): Promise { const log = opts.log ?? (() => {}); const now = opts.now ?? new Date(); // PEP-28: thresholds of the watchdog (platform.watchdog over env). const cfg = await getWatchdogSettings(db); for (const s of await listSessions(db, { active: true })) { try { await checkSession(db, s, opts, cfg, log); } catch (e) { log(`session #${s.id}: ${(e as Error).message}`); } } // PEP-28: planned automatic restarts, reminders/escalation, runners waiting for nobody. await restartTick(db, { now, cfg, log }).catch((e) => log(`restarts: ${(e as Error).message}`)); await remindTick(db, { now, cfg, log }).catch((e) => log(`reminders: ${(e as Error).message}`)); await idleStopTick(db, { now, cfg, log }).catch((e) => log(`idle: ${(e as Error).message}`)); // Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup. await runnerTick(db, { log }).catch((e) => log(`runners: ${(e as Error).message}`)); // PEP-40: runner hosts — online/offline, load, versions (once a minute each). await hostTick(db, { now: opts.now, log }).catch((e) => log(`hosts: ${(e as Error).message}`)); // Story budgets (PEP-43): over the limit → pause and ask the PM. await budgetTick(db, { now: opts.now, log }).catch((e) => log(`budgets: ${(e as Error).message}`)); // Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher. // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them. await intakeTick(db, { now: opts.now, log }).catch((e) => log(`intake: ${(e as Error).message}`)); await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`)); // Errors of running products (PEP-58): Bugsink poll + incident policies. await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`)); // Daily digest at each user's time (PEP-29); a no-op outside their window. await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`)); // PEP-60: platform channel — re-check a channel that isn't working yet, new builds, the // platform digest at its time. await recheckPlatformChannel(db, { now: opts.now, log }).catch((e) => log(`platform channel: ${(e as Error).message}`)); await platformBuildTick(db, { now: opts.now, log }).catch((e) => log(`platform build: ${(e as Error).message}`)); await platformDigestTick(db, { now: opts.now, log }).catch((e) => log(`platform digest: ${(e as Error).message}`)); // PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour. await syncChats(db, { now: opts.now }).catch((e) => log(`chats: ${(e as Error).message}`)); const nowMs = (opts.now ?? new Date()).getTime(); if (nowMs - lastChatPrune >= 3600_000) { lastChatPrune = nowMs; await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch((e) => log(`chats prune: ${(e as Error).message}`)); } } let lastChatPrune = 0; async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) { if (s.tmuxName.startsWith("pending-")) return; const nowDate = opts.now ?? new Date(); // Rate-limited runner: move it to a free subscription of its pool (PEP-39), else continue // it once its limit has reset (PEP-56), whether or not the agent process is still alive. if (s.status === "rate_limited" && s.resumeAt) { // PEP-43: a story paused by its budget waits for the PM, not for the limit reset. if (s.taskId && (await getBudgetState(db, s.taskId))) return; if (await rotateLimited(db, s, nowDate, log)) return; if (nowDate.getTime() >= s.resumeAt.getTime()) await resumeAfterLimit(db, s, nowDate, log); return; } // Near the limit: switch once the turn is over and nothing waits for the PM's answer. if (s.rotateReason === "threshold" && (s.status === "idle" || s.status === "waiting_input")) { const blocking = (await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention"); if (!blocking) { if (!(await tryRotate(db, s, "threshold", nowDate, log))) { await updateSession(db, s.id, { rotateReason: null }); await logSessionEvent(db, s, "rotation_skipped", { reason: "threshold", why: "нет свободной подписки" }); } return; } } const label = `#${s.id} ${s.taskKey ?? ""} (${s.tmuxName})`; if (!(await tmux.hasSession(tmux.sessionPane(s)))) { log(`${label}: tmux session gone`); await logSessionEvent(db, s, "tmux_gone"); // PEP-28: a story at work is restarted by itself (within the limit), else the PM is asked. await onRunnerCrash(db, s, "gone", `Сессия ${s.taskKey ?? s.id} пропала (tmux-сессии больше нет).`, { now: nowDate, cfg, log }); return; } const pane = await tmux.paneState(tmux.sessionPane(s)); if (pane.dead) { const ok = pane.exitStatus === 0; log(`${label}: claude exited with ${pane.exitStatus}`); const tail = screenTail(await tmux.capturePane(tmux.sessionPane(s), 200), 15); await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail }); await killRunner(s).catch(() => {}); if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() }); else await onRunnerCrash(db, s, "crash", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`, { now: nowDate, cfg, log }); return; } const screen = await tmux.capturePane(tmux.sessionPane(s)); const hash = createHash("sha1").update(screen).digest("hex"); const now = (opts.now ?? new Date()).getTime(); let last = s.lastActivityAt?.getTime() ?? now; // PEP-28: the screen hash lives in the DB — a restarted watchdog does not see "new activity". if (s.watchState?.screen !== hash) { last = now; await patchWatch(db, s, { screen: hash, stallAlertAt: undefined }, { lastActivityAt: new Date(now), ...(s.status === "stalled" ? { status: "running" as const } : {}), }); } // Fallback for limits that don't come through the StopFailure hook. if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) { await patchWatch(db, s, { limitGen: s.generation }); const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? ""; log(`${label}: usage limit`); await logSessionEvent(db, s, "usage_limit", { line }); const msg = await recordLimit(db, s, line, new Date(now)); if (msg) await raiseSessionQuestion(db, s, "attention", msg); return; } // PEP-39: the CLI warns the subscription is close to its limit — switch at the turn end. if (!s.rotateReason && s.subscriptionId != null && rotationEnabled() && s.watchState?.thresholdGen !== s.generation && usageWarning(screen)) { await patchWatch(db, s, { thresholdGen: s.generation }); const line = screen.split("\n").reverse().find((l) => usageWarning(l))?.trim() ?? ""; await logSessionEvent(db, s, "usage_threshold", { line }); if (await planRotation(db, s, "threshold", new Date(now))) { await updateSession(db, s.id, { rotateReason: "threshold" }); log(`${label}: near the usage limit, will switch subscription at the turn end`); } } // PEP-28: the stall alert went unanswered long enough — restart the runner. if (s.status === "stalled" && (await restartStalled(db, s, { now: nowDate, cfg, log }))) return; if (s.status === "running" && now - last > opts.stallMs) { log(`${label}: stalled`); await patchWatch(db, s, { stallAlertAt: now }, { status: "stalled" }); await logSessionEvent(db, s, "stalled", { idleMinutes: Math.round((now - last) / 60000) }); if ((await pendingSessionQuestions(db, s.id)).length === 0) { const tail = screenTail(screen, 12); await raiseSessionQuestion( db, s, "attention", `${s.taskKey ?? `Сессия ${s.id}`}: экран не меняется ${Math.round((now - last) / 60000)} мин — похоже, зависла.\n\n${tail}`, ); } } } let lastCiPoll = 0; export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise { const log = opts.log ?? (() => {}); log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`); // PEP-21: the runner service — web, bot and the remote MCP hand their runner commands here. let service: RunnerService | null = null; if (opts.serveCommands !== false) { service = await serveRunnerCommands(db, { log }).catch((e) => { log(`runner service not started: ${(e as Error).message}`); return null; }); } while (!signal?.aborted) { await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); // Heartbeat and the check on the bot and the web (PEP-20). await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`)); // CI results lost on the way (PEP-57): poll commit statuses about once a minute. if (Date.now() - lastCiPoll >= 60_000) { lastCiPoll = Date.now(); await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`)); // Reviews whose MCP process died before running them (PEP-26). await reviewTick(db, log).catch((e) => log(`review tick failed: ${(e as Error).message}`)); } // Daily copy of the SQLite database (PEP-36); a no-op until a day has passed. await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`)); await new Promise((r) => setTimeout(r, opts.intervalMs)); } await service?.stop(); } /** * PEP-39: a rate-limited runner whose subscription is still limited moves to another usable * subscription of its pool. Asked for by recordLimit (`rotate_reason`), or a subscription * freed up while it waits. Nowhere to go after a planned switch → tell the PM it waits. */ async function rotateLimited(db: Db, s: SessionView, now: Date, log: (m: string) => void): Promise { if (s.subscriptionId == null) return false; const sub = await getSubscription(db, s.subscriptionId).catch(() => null); if (!s.rotateReason && sub && isUsable(sub, now)) return false; if (await tryRotate(db, s, "limit", now, log)) return true; if (s.rotateReason) { await updateSession(db, s.id, { rotateReason: null }); await logSessionEvent(db, s, "rotation_skipped", { reason: "limit", why: "нет свободной подписки" }); const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }); await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Раннер ${s.id}`}: лимит, свободных подписок в пуле нет — продолжит в ${at} сам.`); } return false; } /** The limit has reset: nudge the live agent, or relaunch it with its conversation. */ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: string) => void) { const day = now.toLocaleDateString("sv-SE"); const counters = { resumeAt: null, limitResumes: (s.limitResumesDay === day ? s.limitResumes : 0) + 1, limitResumesDay: day, limitResumedAt: now, }; // The limit message gets closed (Telegram shows it as resolved) — no new ping for the PM. await expireSessionQuestions(db, s.id, "(лимит сброшен — раннер продолжил сам)"); const alive = (await tmux.hasSession(tmux.sessionPane(s))) && !(await tmux.paneState(tmux.sessionPane(s))).dead; if (alive) { await tmux.sendText(tmux.sessionPane(s), `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "стори"} с того места, где остановился (tasks.md).`); await updateSession(db, s.id, { ...counters, status: "running", lastActivityAt: now }); } else { await updateSession(db, s.id, counters); await resumeSession(db, s.id); } await logSessionEvent(db, s, "limit_resumed", { alive, n: counters.limitResumes }); log(`#${s.id} ${s.taskKey ?? ""}: limit reset, ${alive ? "nudged" : "relaunched"}`); }