// PEP-150: what the platform does about its own delays (core/platform-delay.ts) — retries, // the checks queue, the one question a usage limit leaves to the owner, and the sweep that // takes the delay line off a story once the cause is gone. import { m } from "@peppa/shared/i18n"; import { alertAdmins, logEvent, clearPlatformDelay, deleteSetting, getAutonomy, getPlatformDelay, getSession, getSetting, giteaForBot, listPlatformDelays, listSessions, listTasks, pendingSessionQuestions, peppaCommit, PeppaError, platformDelay, prGate, savePlatformDelay, setSetting, taskPrNumber, type GiteaClient, type PlatformDelay, type Question, type TaskRef, } from "@peppa/core"; import { settings, type Db, keyPrefix } from "@peppa/db"; import { like } from "drizzle-orm"; import { wakeOnGreen } from "./ci-feedback.ts"; import { moveTask } from "./flow.ts"; import { LIMIT_REQUEST, limitHintKey, limitOver, TURN_RETRY_MAX, type LimitHint } from "./limit-delay.ts"; import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts"; import { restartAgent, sharedCopyBusy } from "./stuck-tasks.ts"; import { requestFromLimitAnswer } from "./subscription-request.ts"; type Log = (m: string) => void; // ── usage limit: the owner's answer ──────────────────────────────────────────────── /** The owner's answer is theirs to act on: nothing is typed to the agent. */ async function onLimitHintAnswer(db: Db, q: Question, answer: string): Promise { const hint = await getSetting(db, limitHintKey(q.projectId)); if (!hint || hint.questionId !== q.id) return false; await setSetting(db, limitHintKey(q.projectId), { ...hint, questionId: null }); if (answer.trim() === LIMIT_REQUEST) await requestFromLimitAnswer(db, q.projectId); return true; } onAnswer(onLimitHintAnswer); // ── checks that don't start ──────────────────────────────────────────────────────── interface ChecksWait { sha: string; /** When this head was first seen without any check status (ms). */ since: number; stuck: boolean; /** The agent was told to wait and is woken once the checks are green. */ told: boolean; /** PEP-205: what the head's other statuses say — the job fell before the checks / the queue grows / nobody took the job. */ cause?: StuckCause; /** PEP-205: how many times Peppa reopened the PR to start the job again for this head, and when last (ms). */ reopened?: number; reopenedAt?: number; } export type StuckCause = "job_failed" | "queue" | "no_job"; /** PEP-205: reopening a PR re-runs a workflow that fell before the checks (DNS hiccup on `git clone`): twice per head, 10 min apart. */ const REOPEN_MAX = 2; const REOPEN_GAP_MS = 10 * 60_000; /** PEP-205: the superadmin is reminded of a standing queue every two hours. */ const QUEUE_REPEAT_MS = 2 * 3600_000; /** What the head's non-`peppa/*` statuses (the Actions run itself) say about why no check reported. */ async function stuckCause(gitea: GiteaClient, o: string, r: string, sha: string): Promise { const st = await gitea.combinedStatus(o, r, sha).catch(() => null); const others = (st?.statuses ?? []).filter((x) => !x.context.startsWith("peppa/")); if (others.some((x) => x.status === "failure" || x.status === "error")) return "job_failed"; if (others.some((x) => x.status === "pending")) return "queue"; return "no_job"; } const causeText = (c: StuckCause | undefined) => c === "job_failed" ? m("задание упало до проверок (сбой связи на сервере)") : c === "queue" ? m("очередь заданий растёт, исполнитель не успевает") : m("исполнитель не взял задание или вебхук не дошёл"); const WAIT_PREFIX = "checks.wait:"; const waitKey = (taskId: number) => `${WAIT_PREFIX}${taskId}`; const QUEUE = "checks.queue"; async function dropWait(db: Db, projectId: number, taskId: number, w: ChecksWait | null) { if (!w) return; await deleteSetting(db, waitKey(taskId)); if (w.stuck) await clearPlatformDelay(db, { projectId, taskId }, "checks"); } /** * The head commit of a story's open result has no `peppa/*` status for longer than * `stuckMin`: the checks queue is stuck on the platform's side. The story gets the delay * line, its agent is told to wait (once), the superadmin gets one message for the whole * queue. Statuses appeared → the delay is lifted; all green → the agent is woken. */ export async function checksQueueTick(db: Db, o: { stuckMin: number; now?: Date; gitea?: GiteaClient; log?: Log }): Promise<{ stuck: number }> { const log = o.log ?? (() => {}); const now = (o.now ?? new Date()).getTime(); const seen = new Set(); const fresh: Array<{ projectId: number; taskId: number; key: string; sessionId: number | null }> = []; let stuck = 0; let oldest = now; const causes = new Map(); const stuckKeys: string[] = []; if (o.stuckMin > 0) { for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) { if (!t.prUrl) continue; const ref = await resolveTaskById(db, t.id).catch(() => null); if (!ref || !taskPrNumber(ref.project, t.prUrl)) continue; const gate = await prGate(ref, o.gitea ?? giteaForBot()).catch(() => null); if (!gate) { seen.add(t.id); // Gitea can't be asked: what is known stays as it is continue; } const prev = await getSetting(db, waitKey(t.id)); const pull = gate.pull; if (!pull || pull.merged || pull.state !== "open" || !gate.summary || gate.summary.state === "not_configured") continue; seen.add(t.id); const sha = pull.head.sha; let w: ChecksWait = prev && prev.sha === sha ? prev : { sha, since: now, stuck: false, told: false }; if (prev && prev.sha !== sha && prev.stuck) await clearPlatformDelay(db, { projectId: t.projectId, taskId: t.id }, "checks"); const session = (await listSessions(db, { active: true, taskId: t.id }))[0] ?? null; if (gate.summary.state === "none") { if (!w.stuck && now - w.since >= o.stuckMin * 60_000) { w = { ...w, stuck: true }; fresh.push({ projectId: t.projectId, taskId: t.id, key: ref.key, sessionId: session?.id ?? null }); if (session && !w.told) { await sendToSession(db, session.id, `Проверки PR ${ref.key} ещё не стартовали: очередь на стороне Пеппы, администратор уже знает. Не пушь пустых коммитов для перезапуска и не спрашивай PM — закончи ход и жди: Пеппа разбудит тебя, когда проверки пройдут.`).then(() => (w = { ...w, told: true }), () => {}); } } if (w.stuck) { // PEP-205: why it stands; a job that fell before the checks is started again by reopening the PR. const gt = o.gitea ?? giteaForBot(); const cause = await stuckCause(gt, ref.project.giteaOwner, ref.project.giteaRepo, sha); w = { ...w, cause }; if (cause === "job_failed" && (w.reopened ?? 0) < REOPEN_MAX && now - (w.reopenedAt ?? 0) >= REOPEN_GAP_MS) { const done = await gt.closePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, pull.number).then(() => gt.reopenPullRequest(ref.project.giteaOwner, ref.project.giteaRepo, pull.number)).then(() => true, () => false); w = { ...w, reopened: (w.reopened ?? 0) + (done ? 1 : 0), reopenedAt: now }; if (done) await logEvent(db, { projectId: t.projectId, taskId: t.id, sessionId: session?.id ?? null, type: "checks_job_restarted", payload: { sha, attempt: w.reopened } }).catch(() => {}); log(`${ref.key}: checks job fell before the checks — PR reopened (${w.reopened}/${REOPEN_MAX})`); } stuck++; oldest = Math.min(oldest, w.since); causes.set(cause, (causes.get(cause) ?? 0) + 1); stuckKeys.push(ref.key); } await setSetting(db, waitKey(t.id), w); continue; } // The checks run (or have finished): no delay any more. if (w.stuck) { await clearPlatformDelay(db, { projectId: t.projectId, taskId: t.id }, "checks"); w = { ...w, stuck: false }; log(`${ref.key}: checks started`); } if (!w.told || gate.summary.state === "failure") { // Nobody waits to be woken; red checks reach the agent through CI feedback. if (prev) await deleteSetting(db, waitKey(t.id)); continue; } if (gate.summary.state === "success") { // PEP-149 wakes the agent on green (once per commit) — the same call, in case the report was lost. const woke = await wakeOnGreen(db, ref, { sha, branch: pull.head.ref, prNumber: pull.number }, o.gitea ?? giteaForBot()).catch(() => false); // Still in its turn: the next pass tries again; nobody to wake (or woken) — forgotten. if (woke || !session || session.status === "idle" || session.status === "waiting_input" || t.status !== "in_progress") await deleteSetting(db, waitKey(t.id)); else await setSetting(db, waitKey(t.id), w); continue; } await setSetting(db, waitKey(t.id), w); } } // Stories that left work/review or lost their result: nothing to wait for. for (const row of await db.select().from(settings).where(keyPrefix(settings.key, `${WAIT_PREFIX}`))) { const taskId = Number(row.key.slice(WAIT_PREFIX.length)); if (seen.has(taskId)) continue; const ref = await resolveTaskById(db, taskId).catch(() => null); await deleteSetting(db, row.key); if (ref && (row.value as ChecksWait).stuck) await clearPlatformDelay(db, { projectId: ref.project.id, taskId }, "checks"); } if (!stuck) { await deleteSetting(db, QUEUE); return { stuck }; } const queue = (await getSetting<{ since: number; win?: number }>(db, QUEUE)) ?? { since: now }; const win = Math.floor((now - queue.since) / QUEUE_REPEAT_MS); const repeat = !fresh.length && win > (queue.win ?? 0); if (fresh.length || repeat) { // One message per queue episode (from the first stuck story until none is left), repeated every two hours while it stands. await setSetting(db, QUEUE, { since: queue.since, win }); const why = [...causes.keys()].map((c) => causeText(c)).join("; "); const keys = stuckKeys.join(", "); const details = `${m("⏳ Очередь проверок: {n} ждут, старшему {min} мин.", { n: stuck, min: Math.round((now - oldest) / 60_000) })} ${why}${keys ? `\n${keys}` : ""}`; if (fresh.length) for (const f of fresh) await platformDelay(db, f, { reason: "checks", details, alertKey: `checks:${queue.since}`, now: new Date(now), log }); else await alertAdmins(db, `checks:${queue.since}:w${win}`, details, log); log(`checks queue: ${stuck} waiting, oldest ${Math.round((now - oldest) / 60_000)} min`); } else if (!(await getSetting(db, QUEUE))) await setSetting(db, QUEUE, { since: queue.since, win: 0 }); return { stuck }; } // ── stale cards ──────────────────────────────────────────────────────────────────── const STALE_AFTER_RELEASE: PlatformDelay["reason"][] = ["agent", "start", "turn"]; async function retryAfterRelease(db: Db, ref: TaskRef, log: Log): Promise { const [s] = (await listSessions(db, { taskId: ref.task.id })).sort((a, b) => b.id - a.id); try { if (ref.task.status === "backlog") await moveTask(db, ref, "in_progress"); else if (!s || !["running", "starting"].includes(s.status)) await restartAgent(db, ref, s ?? null, "Сбой запуска, из-за которого ты остановился, исправлен в новой версии Пеппы. Продолжай работу."); await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s?.id ?? null, type: "delay_stale_restarted", payload: {} }).catch(() => {}); log(`${ref.key}: a stale delay card (older platform version) — closed, agent restarted`); } catch (e) { log(`${ref.key}: stale delay card closed, restart failed: ${(e as Error).message}`); } } // ── retries and the sweep ────────────────────────────────────────────────────────── /** Attempts to start an agent on a story before the superadmin is told it's over. */ export const START_RETRY_MAX = 5; /** A story could not get an agent: the delay line, a retry by schedule, the superadmin once. */ export async function startDelay(db: Db, scope: { projectId: number; taskId: number }, details: string, error: unknown, o: { now?: Date; log?: Log } = {}): Promise { const prev = await getPlatformDelay(db, scope, "start"); const exhausted = (prev?.attempts ?? 0) + 1 >= START_RETRY_MAX; return platformDelay(db, scope, { reason: "start", details, state: exhausted ? "stopped" : "retrying", exhausted, error: error instanceof PeppaError ? undefined : error, now: o.now, log: o.log }); } /** * Every open delay is looked at: gone causes take the line off the story, due retries are made. * The watchdog calls this every tick. */ export async function platformDelayTick(db: Db, o: { now?: Date; log?: Log; commit?: string | null } = {}): Promise { const log = o.log ?? (() => {}); const now = (o.now ?? new Date()).getTime(); const commit = o.commit !== undefined ? o.commit : peppaCommit(); for (const d of await listPlatformDelays(db)) { try { await sweep(db, d, now, log, commit); } catch (e) { log(`platform delay ${d.reason} (#${d.taskId ?? `p${d.projectId}`}): ${(e as Error).message}`); } } } async function sweep(db: Db, d: PlatformDelay, now: number, log: Log, commit: string | null) { const scope = { projectId: d.projectId, taskId: d.taskId }; const clear = () => clearPlatformDelay(db, scope, d.reason); if (d.until != null && d.until <= now) return void (await clear()); if (d.taskId == null) return; const ref = await resolveTaskById(db, d.taskId).catch(() => null); if (!ref || ref.task.archivedAt || ref.task.status === "done") return void (await clear()); if (ref.task.status === "backlog" && d.reason !== "start") return void (await clear()); const live = await listSessions(db, { active: true, taskId: d.taskId }); // PEP-209: an exhausted card about the agent's launch recorded on another version of the // platform — the error may be fixed since (Codex `danger-full-access`, `account/read failed`): // the card goes, the restart count is reset and the story is tried again. if (STALE_AFTER_RELEASE.includes(d.reason) && d.exhausted && commit && d.commit !== commit) { // One agent per shared working copy (PEP-209): the card stays until the copy is free. const [last] = (await listSessions(db, { taskId: ref.task.id })).sort((a, b) => b.id - a.id); if (await sharedCopyBusy(db, ref, last ?? null)) return; await clear(); await retryAfterRelease(db, ref, log); return; } if (d.reason === "agent") { if (live.some((s) => ["running", "idle", "waiting_input"].includes(s.status))) await clear(); return; } if (d.reason === "stuck") { // PEP-198: over once the story left work or its agent is working again. if (ref.task.status !== "in_progress" || live.some((s) => s.status === "running")) await clear(); return; } if (d.reason === "limit") { if (!live.some((s) => s.status === "rate_limited")) await limitOver(db, { id: d.sessionId ?? 0, projectId: d.projectId, taskId: d.taskId }); return; } if (d.reason === "turn") { if (d.exhausted || d.retryAt == null || d.retryAt > now || d.sessionId == null) return; const s = live.find((x) => x.id === d.sessionId); await savePlatformDelay(db, { ...d, retryAt: null }); if (!s || s.status !== "waiting_input" || (await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) return; await sendToSession(db, s.id, "Ход оборвался из-за ошибки на стороне сервиса, не из-за твоей работы. Продолжай с того места, где остановился.").catch(() => {}); log(`${ref.key}: turn broke, agent told to continue (${d.attempts}/${TURN_RETRY_MAX})`); return; } if (d.reason === "start") { if (live.length || ref.task.status !== "backlog") return void (await clear()); // A project that takes stories by itself is retried by its dispatcher. if (d.exhausted || d.retryAt == null || d.retryAt > now || (await getAutonomy(db, d.projectId)).pick === "auto") return; try { await moveTask(db, ref, "in_progress"); await clear(); log(`${ref.key}: agent started on retry ${d.attempts}`); } catch (e) { const fresh = await resolveTaskById(db, d.taskId).catch(() => null); if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {}); await startDelay(db, { projectId: d.projectId, taskId: d.taskId }, m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }), e, { now: new Date(now), log }); } } }