// 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 { asIs, m } from "@peppa/shared/i18n"; import { alertAdmins, ciLane, logEvent, clearPlatformDelay, deleteSetting, getAutonomy, getPlatformDelay, getSession, getSetting, giteaForBot, isWaitingForCapacity, listPlatformDelays, listSessions, listTasks, pendingSessionQuestions, peppaCommit, PeppaError, platformDelay, prGate, savePlatformDelay, setSetting, taskPrNumber, type ChecksQueueState, type GiteaClient, type PlatformDelay, type Question, type TaskRef, } from "@peppa/core"; import { checkRuns, settings, type Db, keyPrefix } from "@peppa/db"; import { and, eq, gt, ne } from "drizzle-orm"; import { ensureCiRunner } from "./ci.ts"; 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; /** PEP-233: not the queue — no workflow in the head, it stands longer than `ORPHAN_AFTER_MS`, or (PEP-255) its own repo has no executor; its own delay is set. */ orphan?: boolean; /** PEP-248: which own delay is set (not the queue), since when (ms) and the last reminder window. */ own?: OwnKind; ownSince?: number; ownWin?: number; /** PEP-248: how many times the executor was registered again for the project's code for this head, and when last (ms). */ reconnected?: number; reconnectedAt?: number; } /** PEP-248: `not_taken` — the job waits while the executor starts other projects' jobs: it is not connected to this code. */ export type StuckCause = "job_failed" | "queue" | "no_job" | "no_workflow" | "not_taken"; type OwnKind = "no_workflow" | "not_taken" | "no_runner" | "old"; /** PEP-233: the workflow the template (and `peppa ci connect`) puts into a project. */ const CI_WORKFLOW = ".gitea/workflows/ci.yml"; /** PEP-233: a head waiting longer than this is an abandoned story, not the queue. */ const ORPHAN_AFTER_MS = 2 * 24 * 3600_000; /** 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; /** PEP-248: a head standing with its own delay — reminded every two hours; one older than two days — once a day. */ const OWN_REPEAT_MS: Record = { no_workflow: QUEUE_REPEAT_MS, not_taken: QUEUE_REPEAT_MS, no_runner: QUEUE_REPEAT_MS, old: 24 * 3600_000 }; /** * PEP-248: the executor took jobs of other projects after this head had waited past the threshold — * reports of their checks first came in later than that (the executor takes jobs in order, so the * queue in front of this job is gone). Reports of the same project don't count: its code shares the cause. */ async function executorBusyElsewhere(db: Db, projectId: number, after: number): Promise { const [row] = await db .select({ id: checkRuns.id }) .from(checkRuns) .where(and(ne(checkRuns.projectId, projectId), eq(checkRuns.source, "report"), gt(checkRuns.createdAt, new Date(after)))) .limit(1); return !!row; } /** 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, busyElsewhere: () => Promise): 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"; // PEP-248: the job waits for an executor — the queue only if the executor is not busy with newer jobs elsewhere. if (others.some((x) => x.status === "pending")) return (await busyElsewhere()) ? "not_taken" : "queue"; // PEP-233: nothing to run in this head — no job will ever come (Gitea unreachable → unknown, as before). const wf = await gitea.fileText(o, r, CI_WORKFLOW, sha).catch(() => ""); return wf == null ? "no_workflow" : "no_job"; } const causeText = (c: StuckCause | undefined) => c === "job_failed" ? m("задание упало до проверок (сбой связи на сервере)") : c === "queue" ? m("очередь заданий растёт, исполнитель не успевает") : c === "no_workflow" ? m("в изменениях нет описания проверок") : c === "not_taken" ? m("исполнитель берёт задания других проектов, а этого — нет: он не подключён к коду проекта") : m("исполнитель не взял задание или вебхук не дошёл"); interface OwnCtx { t: { id: number; projectId: number }; ref: TaskRef; sha: string; session: { id: number } | null; own: OwnKind; cause: StuckCause; now: number; log: Log; } /** * PEP-233/248: a head that stands but is not the queue — its own delay line, one message on the * head (and on each change of the reason), a reminder to the superadmin while it stands. A job the * executor does not take: the executor is registered for the project's code again (twice per head). */ async function ownDelay(db: Db, c: OwnCtx, w: ChecksWait): Promise { const { t, ref, sha, session, own, cause, now, log } = c; let note = ""; if (own === "not_taken" && (w.reconnected ?? 0) < REOPEN_MAX && now - (w.reconnectedAt ?? 0) >= REOPEN_GAP_MS) { const error = await ensureCiRunner(db, ref.project).then( () => null, (e: Error) => String(e?.message ?? e).split("\n")[0]!, ); w = { ...w, reconnected: (w.reconnected ?? 0) + 1, reconnectedAt: now }; await logEvent(db, { projectId: t.projectId, taskId: t.id, sessionId: session?.id ?? null, type: "checks_runner_reconnected", payload: { sha, attempt: w.reconnected, ok: !error, error } }).catch(() => {}); note = error ? m("Подключить исполнитель заново не удалось: {error}.", { error: asIs(error) }) : m("FORGE подключила исполнитель к коду проекта заново."); log(`${ref.key}: the checks job is not taken while the executor works for other projects — executor registered again (${w.reconnected}/${REOPEN_MAX})${error ? `: ${error}` : ""}`); } const why = own === "old" ? m("ждёт больше двух суток") : own === "no_runner" ? m("у кода проекта нет своего исполнителя проверок") : causeText(cause); const tail = `${note ? ` ${note}` : ""}${own === "not_taken" ? `\npeppa ci connect ${ref.project.key}` : ""}`; // Records written before PEP-248 (or by PEP-255's no-executor path) have `orphan` without `own`: the same delay, no second message. const was = w.own ?? (w.orphan ? (cause === "no_workflow" ? "no_workflow" : own === "no_runner" ? "no_runner" : "old") : undefined); if (was !== own) { w = { ...w, orphan: true, own, ownSince: now, ownWin: 0 }; const state = own === "not_taken" ? `not_taken:${sha}` : own === "no_runner" ? `norunner:${sha}` : `orphan:${sha}`; const alertKey = own === "not_taken" ? `checks-own:${t.id}:${sha}:not_taken` : `checks-orphan:${t.id}:${sha}`; await platformDelay(db, { projectId: t.projectId, taskId: t.id, sessionId: session?.id ?? null }, { reason: "checks", state, details: `${m("⏳ Проверки задачи {key} не стартуют, в очередь не считается:", { key: ref.key })} ${why}${tail}`, alertKey, now: new Date(now), log }); if (session && !w.told && cause === "not_taken") { await sendToSession(db, session.id, `Проверки PR ${ref.key} ещё не стартовали: исполнитель проверок не берёт задания этого кода, FORGE его переподключает, администратор знает. Не пушь пустых коммитов и не спрашивай PM — закончи ход и жди: FORGE разбудит тебя, когда проверки пройдут.`).then(() => (w = { ...w, told: true }), () => {}); } if (session && !w.told && cause === "no_workflow") { await sendToSession(db, session.id, `Проверки PR ${ref.key} не стартуют: в головном коммите нет ${CI_WORKFLOW}. Обнови ветку от основной (merge или rebase на свежую основную ветку) и запушь — проверки пойдут сами.`).then(() => (w = { ...w, told: true }), () => {}); } log(`${ref.key}: checks never start (${own}) — not counted as the queue`); return w; } w = { ...w, orphan: true, own, ownSince: w.ownSince ?? now }; const win = Math.floor((now - w.ownSince!) / OWN_REPEAT_MS[own]); if (win > (w.ownWin ?? 0)) { // PEP-248: it still stands — the superadmin hears of it again (once per window). w = { ...w, ownWin: win }; const hours = Math.max(1, Math.round((now - w.since) / 3600_000)); await alertAdmins(db, `checks-own:${t.id}:${sha}:${own}:w${win}`, `${m("⏳ Проверки задачи {key} не стартуют уже {hours} ч:", { key: ref.key, hours })} ${why}${tail}`, log); } return w; } 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; orphans: 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 orphans = 0; let oldest = now; const causes = new Map(); const stuckKeys: string[] = []; // PEP-255: who waits for a stuck queue. A project waits when a head of its own stands; a whole lane // (executor registration) stands only when every head on it stands and they belong to at least two // projects — one project's stuck job says nothing about the executor (23.11: PCHK-3 stood while // the platform's checks on the same runner ran). const stuckProjects = new Set(); const laneHeads = new Map; total: number; stuck: number }>(); const countHead = (lane: string, projectId: number, isStuck: boolean) => { const h = laneHeads.get(lane) ?? { projects: new Set(), total: 0, stuck: 0 }; h.projects.add(projectId); h.total++; if (isStuck) h.stuck++; laneHeads.set(lane, h); }; 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); const prev = await getSetting(db, waitKey(t.id)); if (!gate) { seen.add(t.id); // Gitea can't be asked: what is known stays as it is // PEP-248: a head that stood in the queue still stands — the queue episode (and its reminders) goes on. if (prev?.stuck && !prev.orphan) { stuck++; oldest = Math.min(oldest, prev.since); causes.set(prev.cause ?? "no_job", (causes.get(prev.cause ?? "no_job") ?? 0) + 1); stuckKeys.push(ref.key); } continue; } const pull = gate.pull; if (!pull || pull.merged || pull.state !== "open" || !gate.summary || gate.summary.state === "not_configured") continue; seen.add(t.id); const lane = ciLane(ref.project); 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") { const gc = o.gitea ?? giteaForBot(); const late = !w.stuck && now - w.since >= o.stuckMin * 60_000; if (late || w.stuck) { // PEP-205: why it stands; a job that fell before the checks is started again by reopening the PR. const cause = await stuckCause(gc, ref.project.giteaOwner, ref.project.giteaRepo, sha, () => executorBusyElsewhere(db, t.projectId, w.since + o.stuckMin * 60_000)); // PEP-233: no workflow, or standing for days — not the queue: its own delay, the queue does not stand for it. // PEP-248: nor a job the executor does not take while it takes other projects' jobs. // PEP-255: no job at all in a repo with its own registration — that repo has no executor; nobody else waits for it. const noRunner = cause === "no_job" && lane !== "bot"; const own: OwnKind | null = cause === "no_workflow" ? "no_workflow" : noRunner ? "no_runner" : now - w.since >= ORPHAN_AFTER_MS ? "old" : cause === "not_taken" ? "not_taken" : null; const wasOwn = !!w.orphan; w = { ...w, stuck: true, cause }; if (own) { await ownDelay(db, { t: { id: t.id, projectId: t.projectId }, ref, sha, session, own, cause, now, log }, w).then((x) => (w = x)); orphans++; await setSetting(db, waitKey(t.id), w); continue; } if (w.orphan) w = { ...w, orphan: false, own: undefined, ownSince: undefined, ownWin: undefined }; if (late || wasOwn) { // Back from its own delay into the queue too: the delay line and the message say the queue now. 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} ещё не стартовали: очередь на стороне FORGE, администратор уже знает. Не пушь пустых коммитов для перезапуска и не спрашивай PM — закончи ход и жди: FORGE разбудит тебя, когда проверки пройдут.`).then(() => (w = { ...w, told: true }), () => {}); } } if (cause === "job_failed" && (w.reopened ?? 0) < REOPEN_MAX && now - (w.reopenedAt ?? 0) >= REOPEN_GAP_MS) { const done = await gc.closePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, pull.number).then(() => gc.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++; stuckProjects.add(t.projectId); countHead(lane, t.projectId, true); oldest = Math.min(oldest, w.since); causes.set(cause, (causes.get(cause) ?? 0) + 1); stuckKeys.push(ref.key); } else countHead(lane, t.projectId, false); await setSetting(db, waitKey(t.id), w); continue; } countHead(lane, t.projectId, false); // 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, orphans }; } const queue = (await getSetting(db, QUEUE)) ?? { since: now }; const win = Math.floor((now - queue.since) / QUEUE_REPEAT_MS); const repeat = !fresh.length && win > (queue.win ?? 0); const standing = [...laneHeads].filter(([, h]) => h.stuck === h.total && h.projects.size >= 2).map(([l]) => l).sort(); const held = [...stuckProjects].sort((a, b) => a - b); const record = (w: number | undefined): ChecksQueueState => ({ since: queue.since, win: w ?? 0, lanes: standing, projects: held }); 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, record(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)) || String(queue.lanes?.join()) !== standing.join() || String(queue.projects?.join()) !== held.join()) { await setSetting(db, QUEUE, record(queue.win)); } return { stuck, orphans }; } // ── 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, "Сбой запуска, из-за которого ты остановился, исправлен в новой версии FORGE. Продолжай работу."); 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. // PEP-247: or it waits for a free agent (the capacity queue starts it, PEP-182). if (ref.task.status !== "in_progress" || live.some((s) => s.status === "running") || (await isWaitingForCapacity(db, ref.task.id))) 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 }); } } }