peppa/packages/runner/src/watchdog.ts
peppa-bot 16f2004cd4
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 47с
peppa/build build: success за 32с
peppa/test test: success за 1536с
peppa-ci / ci (pull_request) Successful in 28m0s
Merge branch 'main' into task/pep-248
2026-11-25 18:36:47 +00:00

524 lines
31 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 { projectTrashTick } from "./project-trash.ts";
import { branchProtectionTick } from "./branch-protection.ts";
import { templateSyncTick } from "./template-sync.ts";
import { agentVersionsTick } from "./agent-versions.ts";
import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
platformDigestTick,
recheckPlatformChannel,
pruneAttachments,
pruneChats,
runRetention,
syncChats,
getBudgetState,
runAsActor,
expireSessionQuestions,
listSessions,
logSessionEvent,
pendingSessionQuestions,
clearPlatformDelay,
sessionDelay,
updateSession,
alertAdmins,
type SessionView,
expireLoans,
subscriptionWarnTick,
warnLastSubscription,
} from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { realpathSync } from "node:fs";
import * as tmux from "./tmux.ts";
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, LIMIT_SCREEN_RE, limitLines, recordLimit } from "./limits.ts";
import { limitDelay, limitOver } from "./limit-delay.ts";
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
import { readyDigestTick } from "./ready-digest.ts";
import { stuckTaskTick } from "./stuck-tasks.ts";
import { connectionCheckTick, connectionJournalTick, grantExpiryTick } from "@peppa/core";
import { domainGuardTick } from "./domain-guard.ts";
import { orphanContainersTick } from "./orphan-containers.ts";
import { removeContainer } from "./sandbox.ts";
import { edgeDnsTick } from "./edge-dns.ts";
import { actRunnerTick } from "./act-runner.ts";
import { reviewWantedTick } from "./review-wanted.ts";
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
import { hostTick } from "./hosts.ts";
import { smokeTick } from "./launch-smoke.ts";
import { acceptDigestTick, pruneAcceptFailures, getProjectPause, injectionDigestTick, getSubscription, isUsable, pausedProjectIds, reportPlatformError, setProjectPause } from "@peppa/core";
import { subscriptionRequestTick } from "./subscription-request.ts";
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, wakeIdleOnGreen } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
import { capacityQueueTick } from "./capacity-queue.ts";
import { pendingAcceptTick } from "./accept-pending.ts";
import { reviewCardTick } from "./review-card.ts";
import { conflictStepTick } from "./conflict-step.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 { pickQuestionTick } from "./pick-question.ts";
import { budgetTick } from "./budgets.ts";
import { getWatchdogSettings, idleStopTick, LOST_CONVERSATION_RE, onConversationLost, onLoginFailure, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
import { CODEX_LOGIN_FAIL_RE, codexModelMenu, codexTrustPrompt, dismissCodexMenu, dismissCodexTrust } from "./codex-screen.ts";
import { codexTrustRoots } from "./codex-trust.ts";
import { claudeCreditsDialog, dismissCreditsDialog } from "./claude-screen.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");
}
async function stopPausedSession(db: Db, s: SessionView): Promise<void> {
await stopSession(db, s.id);
const p = await getProjectPause(db, s.projectId);
if (p && !p.sessions.includes(s.id)) await setProjectPause(db, s.projectId, { ...p, sessions: [...p.sessions, s.id] });
}
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);
// PEP-174: an agent of a project on pause that is still alive (the stop at «Поставить на паузу»
// did not reach it) is stopped here; «Продолжить» resumes it.
const paused = await pausedProjectIds(db);
for (const s of await listSessions(db, { active: true })) {
if (paused.has(s.projectId)) {
await stopPausedSession(db, s).catch(failed(db, log, `pause #${s.id}`));
continue;
}
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"));
// PEP-266: after a deploy and hourly — every provider is started the real way and must commit a file.
await smokeTick(db, { now: opts.now, log }).catch(failed(db, log, "launch smoke"));
// 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.
// PEP-186: loans the superadmin gave on a request go back first — their agents move off them.
await subscriptionRequestTick(db, opts.now ?? new Date()).catch(failed(db, log, "subscription requests"));
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 / PEP-198: the analyst formulates new stories before the dispatcher sees them.
// PEP-163: deleted projects leave for good after their week.
await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash"));
// PEP-191: once a day the protection of every project's default branch is checked.
await branchProtectionTick(db, { now: opts.now, log }).catch(failed(db, log, "branch protection"));
// PEP-242: once an hour the template in Gitea is compared with template/ of the running commit.
await templateSyncTick(db, { now: opts.now, log }).catch(failed(db, log, "template sync"));
// PEP-267: once an hour the pinned agent CLI versions are compared with what runs.
await agentVersionsTick(db, { now: opts.now, log }).catch(failed(db, log, "agent versions"));
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"));
// PEP-182: stories waiting for room go first, before the dispatcher takes new ones.
await capacityQueueTick(db, { now: opts.now, log }).catch(failed(db, log, "capacity queue"));
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
// PEP-150: delays on the platform's side — due retries, and lines of delays that are over.
await platformDelayTick(db, { now: opts.now, log }).catch(failed(db, log, "platform delays"));
// PEP-185: ready backlog stories come to the people as «Взять в работу?».
await pickQuestionTick(db, { now: opts.now, log }).catch(failed(db, log, "pick question"));
// 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-231: the platform's and the products' addresses lead to the server's tunnel (every 5 min).
await edgeDnsTick(db, { now: opts.now, log }).catch(failed(db, log, "edge dns"));
// 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-187: once a day — suspicious requests to agents found in foreign texts.
await injectionDigestTick(db, { now: opts.now, log }).catch(failed(db, log, "injection 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"));
// PEP-220: work journals live a day; the tick is hourly, the vacuum once a day.
if (process.env.PEPPA_RETENTION !== "off") {
const daily = nowMs - lastRetentionDaily >= 86_400_000;
if (daily) lastRetentionDaily = nowMs;
await runRetention(db, { now: opts.now, daily }).then((r) => r.total && log(`retention: deleted ${r.total}`)).catch(failed(db, log, "retention"));
}
}
}
let lastChatPrune = 0;
let lastRetentionDaily = 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)) {
await limitOver(db, s);
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})`;
// One failed `has-session` under load is not proof: ask again before restarting the agent.
if (!(await tmux.hasSession(tmux.sessionPane(s))) && !(await new Promise((r) => setTimeout(r, 300)).then(() => tmux.hasSession(tmux.sessionPane(s))))) {
log(`${label}: tmux session gone`);
await logSessionEvent(db, s, "tmux_gone");
// PEP-244: the container does not depend on tmux — without this it keeps running unattended.
if (s.container) await removeContainer(s.host, s.container);
// 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 if (LIMIT_SCREEN_RE.test(tail)) {
// PEP-205: the CLI gave up on a usage limit — that is a limit, not a crash: another subscription
// or a pause until the reset, no automatic restart is spent.
const line = limitLines(tail).at(-1)!;
log(`${label}: usage limit (exited)`);
await logSessionEvent(db, s, "usage_limit", { line, exited: true });
const msg = await recordLimit(db, s, line, nowDate);
if (msg) await limitDelay(db, s, msg, { now: nowDate, log });
} else if (s.provider === "claude" && s.conversationId && LOST_CONVERSATION_RE.test(tail)) {
// PEP-227: the saved conversation is gone — resuming it again would fail the same way.
await onConversationLost(db, s, { now: nowDate, cfg, log });
} else if (s.provider === "codex" && CODEX_LOGIN_FAIL_RE.test(tail)) {
// PEP-205: «account/read failed … timed out» — the way to the provider hiccuped.
await onLoginFailure(db, s, tail, { now: nowDate, cfg, log });
} else {
// PEP-188: the CLI refused its arguments — three restarts would fail the same way.
const badArgs = s.provider === "codex" && pane.exitStatus === 2 && /unexpected argument|Usage: codex/i.test(tail);
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, noRestart: badArgs ? m("запуск агента отклонён — неверные параметры запуска") : undefined });
}
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-150: the agent moves again — the delay line leaves the story.
if (s.status === "stalled" && s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent");
}
// PEP-205: Codex's «Switch to <model>?» menu waits for a key and swallows whatever is typed next —
// answer «Keep current model» (the digit, then Enter if the menu is still there a tick later).
if (s.provider === "codex" && codexModelMenu(screen)) {
const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000;
if (again) await tmux.sendKeys(tmux.sessionPane(s), "Enter").catch(() => {});
else if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await logSessionEvent(db, s, "model_menu_dismissed", {});
await patchWatch(db, s, { menuAt: now });
}
// PEP-241: «Trust this folder?» waits for a key before the first turn — answer «Trust and continue»,
// only for the folder Peppa gave the agent (its worktree, the project's copy and their repository roots).
if (s.provider === "codex" && codexTrustPrompt(screen) && !(s.watchState?.menuAt && now - s.watchState.menuAt < 120_000)) {
const allowed = await agentFolders(db, s);
const res = await dismissCodexTrust(tmux.sessionPane(s), screen, allowed).catch(() => null);
if (res === "sent") await logSessionEvent(db, s, "trust_dismissed", {});
else if (res === "foreign") await logSessionEvent(db, s, "trust_foreign", { paths: codexTrustPrompt(screen)?.paths ?? [] });
await patchWatch(db, s, { menuAt: now });
}
// PEP-227: Claude's «<model> now uses usage credits» dialog waits for a choice — pick «Switch to Opus…»;
// without such a choice the superadmin hears once per generation.
if (s.provider === "claude") {
const dialog = claudeCreditsDialog(screen);
if (dialog?.digit) {
const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000;
if (!again && (await dismissCreditsDialog(tmux.sessionPane(s), screen).catch(() => false))) {
await logSessionEvent(db, s, "model_dialog_dismissed", { choice: dialog.digit });
await patchWatch(db, s, { menuAt: now });
}
} else if (dialog && s.watchState?.creditsAlertGen !== s.generation) {
await patchWatch(db, s, { creditsAlertGen: s.generation });
// glossary-ignore: сообщение мониторинга суперадмину — он меняет модель агентов
await alertAdmins(db, `delay:credits:${s.id}:${s.generation}`, m("{who}: агент ждёт на экране выбора модели — модель просит отдельные кредиты. Укажите агентам другую модель в настройках.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }) }), log);
}
}
// A start that got past the sign-in: earlier sign-in failures are over.
if (s.watchState?.loginFails && s.status === "running") await patchWatch(db, s, { loginFails: undefined });
// 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 limitDelay(db, s, msg, { now: new Date(now), log });
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);
// PEP-150: not the owner's to fix — the superadmin is told once, the story shows the delay line.
await sessionDelay(db, s, {
reason: "agent",
state: "stall",
details: `${m("{who}: ничего не происходит {n} мин — похоже, работа зависла.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), n: Math.round((now - last) / 60000) })}\n\n${asIs(tail)}`,
now: nowDate,
log,
});
}
}
}
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"));
await wakeIdleOnGreen(db).catch(failed(db, log, "wake on green failed"));
// PEP-205: stories whose agent asked for review while the checks ran — on green the platform moves them.
await reviewWantedTick(db, { log }).catch(failed(db, log, "review wanted 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"));
// PEP-269: a conflict with the main branch — resolved clears its step, an agent that failed goes to a person.
await conflictStepTick(db, { log }).catch(failed(db, log, "conflict step failed"));
// PEP-150: checks that have not started for too long — a delay, not a question to the owner.
await checksQueueTick(db, { stuckMin: (await getWatchdogSettings(db)).checksStuckMin, log }).catch(failed(db, log, "checks queue failed"));
// PEP-198: the analyst's evening digest of finished stories nobody waited for; stuck stories.
await readyDigestTick(db, { log }).catch(failed(db, log, "ready digest failed"));
await stuckTaskTick(db, { log }).catch(failed(db, log, "stuck tasks failed"));
// PEP-249: each connection's key is checked once a day; a key that stopped working — one message to its owner.
await connectionCheckTick(db).catch(failed(db, log, "connection check failed"));
// PEP-254: hourly — the connections journal chain is checked, a daily checkpoint goes outside the table.
await connectionJournalTick(db, { log }).catch(failed(db, log, "connection journal failed"));
// PEP-259: grants nobody used for the connection's threshold (72 h) are revoked; one summary a day.
await grantExpiryTick(db).catch(failed(db, log, "connection grants expiry failed"));
// PEP-209: one «Готово к приёмке» summary instead of many «готово» messages in Telegram.
await acceptDigestTick(db, { log }).catch(failed(db, log, "accept digest failed"));
await pruneAcceptFailures(db).catch(() => {});
// PEP-189: no container takes the platform's port or domain; the public address answers Peppa.
await domainGuardTick(db, { log }).catch(failed(db, log, "domain guard failed"));
// PEP-244: containers of agents whose session is over or gone (a deploy took the tmux server).
await orphanContainersTick(db, { log }).catch(failed(db, log, "orphan containers failed"));
// PEP-205: the checks executor is alive and takes jobs; otherwise it is restarted.
await actRunnerTick(db, { log }).catch(failed(db, log, "act runner guard 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 limitDelay(db, s, m("{who}: лимит, свободных подписок нет — продолжит в {time} сам.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), time: at }), { now, log });
}
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) {
// PEP-205: a menu left on Codex's screen would take the text as its answer.
if (s.provider === "codex") {
const screen = await tmux.capturePane(tmux.sessionPane(s)).catch(() => "");
if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await new Promise((r) => setTimeout(r, 300));
}
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 });
await limitOver(db, s);
log(`#${s.id} ${s.taskKey ?? ""}: limit reset, ${alive ? "nudged" : "relaunched"}`);
}
/** PEP-241: the folders Peppa gave this agent — its worktree, the project's copy and their repository roots. */
async function agentFolders(db: Db, s: SessionView): Promise<string[]> {
const [project] = await db.select({ path: projects.workspacePath }).from(projects).where(eq(projects.id, s.projectId));
const out = new Set<string>();
for (const p of [s.workspacePath, project?.path]) {
if (!p) continue;
out.add(p);
try {
const real = realpathSync(p);
for (const r of codexTrustRoots(real)) out.add(r);
} catch {
/* on a host the folder is not here */
}
}
return [...out];
}