peppa/packages/runner/src/watchdog.ts
Асель 14916079bc PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens,
  sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage
- PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM:
  extend x2 / remove limit / stop), start/resume guard, budget on the story card
- PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner
  hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics
- PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered,
  /journal for superadmins, project journal tab, authors in the story feed
- Migration 0007_usage_audit; OpenSpec changes archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:52:13 +05:00

240 lines
12 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 { runnerTick } from "./runners.ts";
import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
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 { resumeSession } from "./sessions.ts";
import { getSubscription, isUsable } from "@peppa/core";
import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
import { monitorTick } from "./monitor.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
import { budgetTick } from "./budgets.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;
}
// 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");
}
// Screen hash per session, kept across ticks.
const lastScreen = new Map<number, string>();
const limitAlerted = new Set<string>();
const thresholdSeen = new Set<string>();
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 ?? (() => {});
for (const s of await listSessions(db, { active: true })) {
try {
await checkSession(db, s, opts, log);
} catch (e) {
log(`session #${s.id}: ${(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}`));
// 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.
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}`));
}
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, 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(s.tmuxName))) {
log(`${label}: tmux session gone`);
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
await logSessionEvent(db, s, "tmux_gone");
await raiseSessionQuestion(db, s, "attention", `Сессия ${s.taskKey ?? s.id} пропала (tmux-сессии больше нет).`);
return;
}
const pane = await tmux.paneState(s.tmuxName);
if (pane.dead) {
const ok = pane.exitStatus === 0;
log(`${label}: claude exited with ${pane.exitStatus}`);
const tail = screenTail(await tmux.capturePane(s.tmuxName, 200), 15);
await updateSession(db, s.id, { status: ok ? "done" : "failed", endedAt: new Date() });
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
if (!ok) {
await raiseSessionQuestion(db, s, "attention", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`);
}
await tmux.killSession(s.tmuxName).catch(() => {});
return;
}
const screen = await tmux.capturePane(s.tmuxName);
const hash = createHash("sha1").update(screen).digest("hex");
const now = (opts.now ?? new Date()).getTime();
let last = s.lastActivityAt?.getTime() ?? now;
if (lastScreen.get(s.id) !== hash) {
last = now;
lastScreen.set(s.id, hash);
await updateSession(db, s.id, {
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" && !limitAlerted.has(`${s.id}:${s.generation}`)) {
limitAlerted.add(`${s.id}:${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() && !thresholdSeen.has(`${s.id}:${s.generation}`) && usageWarning(screen)) {
thresholdSeen.add(`${s.id}:${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`);
}
}
if (s.status === "running" && now - last > opts.stallMs) {
log(`${label}: stalled`);
await updateSession(db, s.id, { 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<void> {
const log = opts.log ?? (() => {});
log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`);
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));
}
}
/**
* 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: "нет свободной подписки" });
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(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
if (alive) {
await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${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"}`);
}