peppa/packages/runner/src/watchdog.ts

342 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 { asIs, m } from "@peppa/shared/i18n";
import { runnerTick } from "./runners.ts";
import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
platformDigestTick,
recheckPlatformChannel,
pruneAttachments,
pruneChats,
syncChats,
getBudgetState,
runAsActor,
expireSessionQuestions,
listSessions,
logSessionEvent,
pendingSessionQuestions,
raiseSessionQuestion,
updateSession,
type SessionView,
expireLoans,
subscriptionWarnTick,
warnLastSubscription,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, recordLimit } from "./limits.ts";
import { killRunner, resumeSession } from "./sessions.ts";
import { hostTick } from "./hosts.ts";
import { getSubscription, isUsable, reportPlatformError } from "@peppa/core";
import { earlyRotationEnabled, 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 { pendingAcceptTick } from "./accept-pending.ts";
import { reviewCardTick } from "./review-card.ts";
import { intakeTick } from "./intake.ts";
import { storyRefineTick } from "./story-refine.ts";
import { analystChatTick } from "./analyst-chat.ts";
import { productReviewTick } from "./product-review.ts";
import { feedbackTick } from "./feedback.ts";
import { productRedeployTick } from "./deploy.ts";
import { productLinkTick } from "./product-link.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").
/** 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<void> {
// 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<void> {
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) {
failed(db, log, `session #${s.id}`)(e);
}
}
// PEP-28: planned automatic restarts, reminders/escalation, runners waiting for nobody.
await restartTick(db, { now, cfg, log }).catch(failed(db, log, "restarts"));
await remindTick(db, { now, cfg, log }).catch(failed(db, log, "reminders"));
await idleStopTick(db, { now, cfg, log }).catch(failed(db, log, "idle"));
// Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup.
await runnerTick(db, { log }).catch(failed(db, log, "runners"));
// PEP-40: runner hosts — online/offline, load, versions (once a minute each).
await hostTick(db, { now: opts.now, log }).catch(failed(db, log, "hosts"));
// Story budgets (PEP-43): over the limit → pause and ask the PM.
await budgetTick(db, { now: opts.now, log }).catch(failed(db, log, "budgets"));
// PEP-107: lent subscriptions go back on time; a project down to its last subscription near the limit is warned.
await expireLoans(db, opts.now ?? new Date()).catch(failed(db, log, "subscription loans"));
await subscriptionWarnTick(db, opts.now ?? new Date()).catch(failed(db, log, "subscription warnings"));
// 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(failed(db, log, "intake"));
// PEP-115: a comment on a backlog story — the analyst reworks the story.
await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine"));
// PEP-127: accepts remembered over a conflict — merge and close once the agent has rebased.
await pendingAcceptTick(db, { now: opts.now, log }).catch(failed(db, log, "pending accepts"));
// PEP-145: a project whose product does not open by a link gets a story for that, first in the
// backlog — before the dispatcher looks; «Показывать всем: сам» is carried through.
await productLinkTick(db, { now: opts.now, log }).catch(failed(db, log, "product link"));
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
// PEP-110: the analyst answers people in the projects' discussions.
await analystChatTick(db, { log }).catch(failed(db, log, "analyst chat"));
// PEP-112: changed secrets restart the deployed product; the product agent accepts each deploy.
await productRedeployTick(db, { now: opts.now, log }).catch(failed(db, log, "secrets redeploy"));
await productReviewTick(db, { log }).catch(failed(db, log, "product review"));
// PEP-143: users' reports about Peppa — the feedback agent analyses, superadmins decide.
await feedbackTick(db, { now: opts.now, log }).catch(failed(db, log, "feedback"));
// Errors of running products (PEP-58): Bugsink poll + incident policies.
await incidentTick(db, { now: opts.now, log }).catch(failed(db, log, "incidents"));
// Daily digest at each user's time (PEP-29); a no-op outside their window.
await digestTick(db, { now: opts.now, log }).catch(failed(db, log, "digest"));
// 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(failed(db, log, "platform channel"));
await platformBuildTick(db, { now: opts.now, log }).catch(failed(db, log, "platform build"));
await platformDigestTick(db, { now: opts.now, log }).catch(failed(db, log, "platform digest"));
// PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour.
await syncChats(db, { now: opts.now }).catch(failed(db, log, "chats"));
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(failed(db, log, "chats prune"));
// PEP-159: files that were chosen but never sent.
await pruneAttachments(db).then((n) => n && log(`attachments: pruned ${n}`)).catch(failed(db, log, "attachments prune"));
}
}
let lastChatPrune = 0;
/** A part of the watchdog failed: log it and send it to Bugsink (PEP-91). */
function failed(db: Db, log: (m: string) => void, where: string) {
return (e: unknown) => {
log(`${where}: ${(e as Error)?.message ?? e}`);
void reportPlatformError(db, e, { service: "watchdog", where });
};
}
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: m("нет свободной подписки") });
}
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", m("Агент {key} неожиданно перестал работать.", { key: s.taskKey ?? s.id }), { 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", `${m("{where}: работа оборвалась с ошибкой (код {code}).", { where: s.taskKey ?? m("Агент #{id}", { id: s.id }), code: pane.exitStatus })}\n\n${asIs(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 } : {}),
});
}
// PEP-166: banners already on screen when this generation started are history (a resumed
// conversation after a switch shows the old account's limit) — count them, don't act on them.
// Only a resumed Claude conversation replays history (a fresh start and Codex — which starts
// over on another subscription — begin with a clean screen, and Codex has no limit hook).
const replays = s.provider !== "codex" && s.generation > 1;
const banners = limitLines(screen).length;
if (!replays) {
if (s.watchState?.limitBase) await patchWatch(db, s, { limitBase: 0 });
s = { ...s, watchState: { ...s.watchState, limitBase: 0 } };
} else if (s.watchState?.limitBaseGen !== s.generation) {
await patchWatch(db, s, { limitBaseGen: s.generation, limitBase: banners });
s = { ...s, watchState: { ...s.watchState, limitBaseGen: s.generation, limitBase: banners } };
} else if (banners < (s.watchState?.limitBase ?? 0)) {
await patchWatch(db, s, { limitBase: banners });
s = { ...s, watchState: { ...s.watchState, limitBase: banners } };
}
const fresh = freshLimitLine(screen, s.watchState?.limitBase ?? 0);
// Fallback for limits that don't come through the StopFailure hook.
if (fresh && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) {
await patchWatch(db, s, { limitGen: s.generation });
const line = fresh;
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 });
const spare = await planRotation(db, s, "threshold", new Date(now));
if (spare && earlyRotationEnabled()) {
await updateSession(db, s.id, { rotateReason: "threshold" });
log(`${label}: near the usage limit, will switch subscription at the turn end`);
} else if (!spare) {
// PEP-107: nowhere to go — warn the project now, before the limit stops its agents.
await warnLastSubscription(db, s.subscriptionId, new Date(now)).catch(failed(db, log, "subscription warning"));
}
}
// 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",
`${m("{who}: ничего не происходит {n} мин — похоже, работа зависла.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), n: Math.round((now - last) / 60000) })}\n\n${asIs(tail)}`,
);
}
}
}
let lastCiPoll = 0;
export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise<void> {
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(failed(db, log, "tick failed"));
// Heartbeat and the check on the bot and the web (PEP-20).
await monitorTick(db, { log }).catch(failed(db, log, "monitor failed"));
// 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(failed(db, log, "ci poll failed"));
// Reviews whose MCP process died before running them (PEP-26).
await reviewTick(db, log).catch(failed(db, log, "review tick failed"));
// PEP-127: held or stale ready-for-review messages — send when mergeable, rebase on a conflict.
await reviewCardTick(db, { log }).catch(failed(db, log, "review cards failed"));
}
// Daily copy of the SQLite database (PEP-36); a no-op until a day has passed.
await backupDb(db, { log }).catch(failed(db, log, "backup failed"));
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<boolean> {
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: m("нет свободной подписки") });
const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
await raiseSessionQuestion(db, s, "attention", `${m("{who}: лимит, свободных подписок нет — продолжит в {time} сам.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), time: at })}\n${ADD_SUBSCRIPTION_HINT}`);
}
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, m("(лимит сброшен — агент продолжил сам)"));
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"}`);
}