peppa/packages/runner/src/stuck-tasks.ts

326 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.

// PEP-198 → PEP-209: a stuck story — in work, no agent working on it — is healed by the platform
// itself instead of being only noticed. Why it got stuck (18.11 on the live system): long-lived
// agents lost their MCP `peppa` server (it does not reconnect), so `update_task(status: review)`
// never ran; the fallback `call.ts` from a worktree had no .env; the merge webhook got lost.
//
// The healing (`stuckTaskTick`, every watchdog tick, `PEPPA_STUCK_TASKS=off`):
// - the result is found by the story's `pr_url` or by its branch `task/<key>` (merged ones too);
// - merged → the story is done (like the merge webhook);
// - green checks, no conflict → the platform moves the story to review, no turn of the agent;
// - a conflict, red checks, a closed or missing result → the agent is relaunched as a NEW process
// (a new process brings the MCP back) with the exact reason;
// - checks still running or not started → not ours (the checks queue, PEP-150/205): wait.
// Retries 5 min, 15 min, 1 h, then every 2 h; the 4th failure → one message to the superadmin and
// the card says «нужен администратор». The count lives in `stuck.heal:<taskId>` while the story
// stays in work: the delay card itself leaves whenever the agent works again (sweep).
import {
checksQueueStanding,
clearPlatformDelay,
deleteSetting,
getPlatformDelay,
getSetting,
giteaForBot,
isWaitingForCapacity,
listPlatformDelays,
listProjects,
listSessions,
listTasks,
pausedProjectIds,
pendingQuestions,
pendingReview,
platformDelay,
resolveRunnerSettings,
prGate,
queuedItems,
setSetting,
taskHoldReason,
taskPrNumber,
updateTask,
type GiteaClient,
type GiteaPull,
type SessionView,
type TaskRef,
} from "@peppa/core";
import { settings, type Db, keyPrefix } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
import { like } from "drizzle-orm";
import { closeMergedStory } from "./gitea-events.ts";
import { REVIEW_WANTED_PREFIX } from "./review-wanted-state.ts";
import { platformToReview } from "./review-wanted.ts";
import { startTaskOnRunner } from "./runners.ts";
import { killRunner, resumeSession, resolveTaskById } from "./sessions.ts";
import { patchWatch } from "./recovery.ts";
import { conflictStep, getConflictStep } from "./conflict-step.ts";
type Log = (m: string) => void;
/** A story is looked at once nothing has happened on it for this long. */
export const STUCK_IDLE_MS = 30 * 60_000;
/** Pause after attempt 1, 2, 3, 4… in minutes (the last one repeats). */
export const STUCK_RETRY_MIN = [5, 15, 60, 120];
/** Attempts before the superadmin is asked to look. */
export const STUCK_MAX_ATTEMPTS = 4;
/**
* PEP-246: a due attempt waits for the standing checks queue at most this long (min), then the
* agent is relaunched anyway — PEP-217 stood for days while the count never moved.
*/
export const STUCK_QUEUE_WAIT_MIN = 120;
export interface StuckHeal {
attempts: number;
/** When the last attempt was made and when the next one is due (ms). */
at: number;
nextAt: number;
/** What was done last (for the superadmin). */
action: string;
}
const HEAL_PREFIX = "stuck.heal:";
const healKey = (taskId: number) => `${HEAL_PREFIX}${taskId}`;
export const getStuckHeal = (db: Db, taskId: number) => getSetting<StuckHeal>(db, healKey(taskId));
export const clearStuckHeal = (db: Db, taskId: number) => deleteSetting(db, healKey(taskId));
/** What the result of a story says. */
export type Diagnosis =
| { kind: "merged"; pull: GiteaPull }
| { kind: "review"; pull: GiteaPull }
/**
* Not the platform's to heal right now (checks running, Gitea unreachable, the checks queue).
* `held`: what the agent would be asked if the wait were over (the checks queue holds a rebase).
*/
| { kind: "wait"; why: string; held?: AgentDiagnosis }
/** Only the agent can do it: `agent` is told exactly what, `reason` is for the superadmin. */
| AgentDiagnosis;
/** `conflict`: the result conflicts with the main branch — that is `conflictStep`'s (PEP-269), not a relaunch. */
type AgentDiagnosis = { kind: "agent"; reason: string; agent: string; pull: GiteaPull | null; conflict?: boolean };
const branchRe = (key: string) => new RegExp(`^task/${key.replace(/[^A-Za-z0-9-]/g, "")}(?![0-9])`, "i");
/** Finds the story's result (by `pr_url`, else by its branch) and says what it needs. */
export async function diagnose(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<Diagnosis> {
const { giteaOwner: o, giteaRepo: r } = ref.project;
const n = taskPrNumber(ref.project, ref.task.prUrl);
let pull: GiteaPull | null | undefined = n ? await gitea.getPullRequest(o, r, n).catch(() => undefined) : null;
if (pull === null) pull = await gitea.pullForBranch(o, r, branchRe(ref.key)).catch(() => undefined);
if (pull === undefined) return { kind: "wait", why: "gitea" };
if (!pull) {
return {
kind: "agent",
reason: m("результата работы нет"),
agent: `У стори ${ref.key} нет PR. Если работа сделана — запушь ветку task/${ref.key.toLowerCase()}, открой PR (peppa.open_pull_request) и вызови update_task(status: review, pr_url). Если не сделана — продолжай по tasks.md.`,
pull: null,
};
}
if (pull.merged) return { kind: "merged", pull };
if (pull.state !== "open") {
return {
kind: "agent",
reason: m("результат закрыт без принятия"),
agent: `PR #${pull.number} стори ${ref.key} закрыт без мержа. Открой PR заново из ветки ${pull.head.ref} (peppa.open_pull_request) и вызови update_task(status: review, pr_url).`,
pull,
};
}
// The result found by the branch becomes the story's: the gate, the card and the merge read it.
if (ref.task.prUrl !== pull.html_url) {
await updateTask(db, ref, { prUrl: pull.html_url });
ref.task = { ...ref.task, prUrl: pull.html_url };
}
const gate = await prGate(ref, gitea).catch(() => null);
if (!gate) return { kind: "wait", why: "gitea" };
if (gate.ok || gate.behind) return { kind: "review", pull };
if (gate.summary?.state === "failure") {
const list = gate.summary.failed.map((f) => f.check).join(", ");
return {
kind: "agent",
reason: m("проверки не пройдены ({list})", { list }),
agent: `Проверки PR #${pull.number} стори ${ref.key} красные (${list}). Почини, прогони проверки локально (bash .gitea/peppa-check.sh <проверка>), запушь в ту же ветку и после зелёных проверок вызови update_task(status: review).`,
pull,
};
}
if (pull.mergeable === false) {
const conflict: AgentDiagnosis = {
kind: "agent",
reason: m("изменения конфликтуют с основной версией кода"),
agent: `PR #${pull.number} стори ${ref.key} конфликтует с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок вызови update_task(status: review).`,
pull,
conflict: true,
};
// PEP-205: no rebase while the checks queue stands — every push queues new checks.
if (await checksQueueStanding(db, ref.project)) return { kind: "wait", why: "checks queue", held: conflict };
return conflict;
}
return { kind: "wait", why: "checks running" };
}
/**
* Relaunches the story's agent as a new process with `text` (only a new process brings a lost MCP
* server back; typing into the old one would not). No session yet — a new agent starts.
*/
export async function restartAgent(db: Db, ref: TaskRef, s: SessionView | null, text: string): Promise<void> {
const prompt = `FORGE перезапустила тебя: стори ${ref.key} стояла в работе без движения.\n${text}\nЕсли MCP peppa недоступен — запасной путь: node packages/mcp/scripts/call.ts <инструмент> '<json>' из рабочей копии FORGE.`;
if (!s) {
await startTaskOnRunner(db, ref, { prompt });
return;
}
await killRunner(s);
await patchWatch(db, s, { restarts: [], restartAt: undefined, restartReason: undefined });
await resumeSession(db, s.id, { prompt });
}
/**
* PEP-209: the agent would run in a working copy another agent of the project works in right now
* (workspace «shared» — QLFW had 8–10 agents switching each other's branches). One agent per copy:
* the healing waits its turn. Idle agents don't touch git; a separate host has its own clone.
*/
export async function sharedCopyBusy(db: Db, ref: TaskRef, s: SessionView | null): Promise<boolean> {
if (s?.hostId) return false;
const rs = s ? null : await resolveRunnerSettings(db, ref.project.id, ref.task.id);
const shared = s ? !s.workspacePath : rs!.workspace !== "worktree" && rs!.isolation === "none" && !rs!.hosts.length;
if (!shared) return false;
return (await listSessions(db, { active: true, projectId: ref.project.id })).some((x) => x.id !== s?.id && !x.workspacePath && !x.hostId && WORKING.includes(x.status));
}
const WORKING = ["starting", "running"];
const STOPPED = ["idle", "waiting_input", "done", "failed"];
/** Delays other than `stuck` whose own path still works on the story. */
const OTHER_PATHS = ["agent", "limit", "checks", "start", "switch", "turn", "accept", "ci"];
export async function stuckTaskTick(db: Db, o: { now?: Date; log?: Log; gitea?: GiteaClient } = {}): Promise<number> {
if (process.env.PEPPA_STUCK_TASKS === "off") return 0;
const log = o.log ?? (() => {});
const now = (o.now ?? new Date()).getTime();
const paused = await pausedProjectIds(db);
const delays = await listPlatformDelays(db);
const inWork = new Set<number>();
let acted = 0;
for (const project of await listProjects(db)) {
if (paused.has(project.id)) continue;
for (const task of await listTasks(db, { projectId: project.id, statuses: ["in_progress"] })) {
inWork.add(task.id);
const ref: TaskRef = { project, task, key: formatTaskKey(project.key, task.number) };
try {
if (await healOne(db, ref, delays, now, o.gitea, log)) acted++;
} catch (e) {
log(`${ref.key}: stuck healing: ${(e as Error).message}`);
}
}
}
// The count is per stay in work: a story that left work starts afresh next time.
for (const row of await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, `${HEAL_PREFIX}`))) {
const id = Number(row.key.slice(HEAL_PREFIX.length));
if (!inWork.has(id) && !(await resolveTaskById(db, id).then((r) => r.task.status === "in_progress" && paused.has(r.project.id), () => false))) await deleteSetting(db, row.key);
}
return acted;
}
async function healOne(db: Db, ref: TaskRef, delays: Awaited<ReturnType<typeof listPlatformDelays>>, now: number, gitea: GiteaClient | undefined, log: Log): Promise<boolean> {
const scope = { projectId: ref.project.id, taskId: ref.task.id };
// Another path of the platform is on it (a planned restart, a limit, the checks queue…).
if (delays.some((d) => d.taskId === ref.task.id && OTHER_PATHS.includes(d.reason) && !d.exhausted)) return false;
// The platform moves it already: the reviewer agent, or review on green (PEP-205).
if ((await pendingReview(db, ref.task.id)) || (await getSetting(db, `${REVIEW_WANTED_PREFIX}${ref.task.id}`))) return false;
const [s] = (await listSessions(db, { taskId: ref.task.id })).sort((a, b) => b.id - a.id);
if (s && !STOPPED.includes(s.status)) return false;
// PEP-247: no agent was ever started — unless it waits for a runner or for a free agent (PEP-182).
if (!s && ((await queuedItems(db, { taskId: ref.task.id })).length || (await isWaitingForCapacity(db, ref.task.id)))) return false;
// PEP-247: a lawful reason (no working subscription, the budget spent) is no delay: the card shows it.
if (await taskHoldReason(db, ref.project.id, ref.task.id, new Date(now))) {
if (await getPlatformDelay(db, scope, "stuck")) await clearPlatformDelay(db, scope, "stuck");
return false;
}
// PEP-269: a conflict with the main branch is its own step (one request to the agent, then a person).
if (await getConflictStep(db, ref.task.id)) {
if (await getPlatformDelay(db, scope, "stuck")) await clearPlatformDelay(db, scope, "stuck");
return false;
}
// The agent waits for a person's answer: that is not stuck.
if ((await pendingQuestions(db, ref.project.id)).some((q) => q.taskId === ref.task.id && q.kind !== "attention")) return false;
const heal = await getStuckHeal(db, ref.task.id);
const since = s ? (s.lastActivityAt ?? s.endedAt ?? s.startedAt).getTime() : ref.task.updatedAt.getTime();
if (!heal && now - since < STUCK_IDLE_MS) return false;
const card = await getPlatformDelay(db, scope, "stuck");
if (heal && heal.nextAt > now) {
// Waiting for the next attempt: the owner still sees when it comes (the sweep took the card while the agent worked).
if (!card) await platformDelay(db, scope, { reason: "stuck", state: "retrying", quiet: true, attempts: heal.attempts, retryAt: heal.nextAt, details: heal.action, action: heal.action, now: new Date(now), log });
return false;
}
if (card?.exhausted) return false; // the superadmin decides (buttons), nothing more by itself
let d = await diagnose(db, ref, gitea);
let forced = false;
if (d.kind === "wait") {
if (!heal) return false;
// PEP-246: a due attempt is not lost silently. The checks queue holds it for a while, then it goes.
if (d.held && now - heal.nextAt >= STUCK_QUEUE_WAIT_MIN * 60_000) {
log(`${ref.key}: stuck — the checks queue held the attempt for ${Math.round((now - heal.nextAt) / 60_000)} min, relaunching anyway`);
d = d.held;
forced = true;
} else {
const at = now + STUCK_RETRY_MIN[0]! * 60_000;
if (!card || card.state !== "waiting" || card.retryAt == null || card.retryAt <= now) {
// glossary-ignore: сообщение суперадмину
const details = m("⏳ {key}: попытка {n} ждёт ({why}), проверим снова в ближайшие минуты", { key: ref.key, n: heal.attempts + 1, why: d.why });
await platformDelay(db, scope, { reason: "stuck", state: "waiting", quiet: true, attempts: heal.attempts, retryAt: at, details, action: heal.action, now: new Date(now), log });
}
log(`${ref.key}: stuck — attempt ${heal.attempts + 1} is due but waits (${d.why})`);
return false;
}
}
if (d.kind === "merged") {
await closeMergedStory(db, ref, d.pull.number, null, gitea);
await clearStuckHeal(db, ref.task.id);
log(`${ref.key}: stuck — its result is merged, story done`);
return true;
}
if (d.kind === "review") {
const r = await platformToReview(db, ref, d.pull.head.sha, "stuck_to_review");
await clearStuckHeal(db, ref.task.id);
log(`${ref.key}: stuck — checks green, no conflict: ${r === "reviewer" ? "the reviewer agent takes it" : "moved to review by the platform"}`);
return true;
}
if (d.kind === "agent" && d.conflict && d.pull) {
const r = await conflictStep(db, ref, d.pull, { now: new Date(now), log, force: forced });
if (r !== "held") {
await clearStuckHeal(db, ref.task.id);
if (card) await clearPlatformDelay(db, scope, "stuck");
}
log(`${ref.key}: stuck — a conflict with the main branch, the conflict step: ${r}`);
return r !== "held";
}
// PEP-247: no agent ever ran and there is no result yet — the agent simply starts the story.
if (!s && !d.pull) {
d.reason = m("агент по задаче ни разу не запускался");
d.agent = `Агент по стори ${ref.key} ещё не запускался, хотя она «В работе». Начни работу по правилам: get_task, затем proposal или apply.`;
}
const attempts = heal?.attempts ?? 0;
const idleH = Math.max(1, Math.round((now - since) / 3_600_000));
if (attempts >= STUCK_MAX_ATTEMPTS) {
// glossary-ignore: сообщение суперадмину
const details = `${m("⏳ {key} не движется: {reason}. Попыток: {n}, агента перезапускали, не помогло.", { key: ref.key, reason: d.reason, n: attempts })}`;
await platformDelay(db, scope, { reason: "stuck", state: "admin", exhausted: true, attempts, details, action: heal?.action ?? d.reason, buttons: true, now: new Date(now), log });
log(`${ref.key}: stuck — ${attempts} attempts failed, the superadmin is asked`);
return true;
}
if (await sharedCopyBusy(db, ref, s)) {
// Not an attempt: the story waits for the shared working copy, the owner sees when it is tried again.
const at = now + STUCK_RETRY_MIN[0]! * 60_000;
if (heal) await setSetting(db, healKey(ref.task.id), { ...heal, nextAt: at });
await platformDelay(db, scope, { reason: "stuck", state: "queued", quiet: true, attempts: attempts, retryAt: at, details: m("⏳ {key}: ждёт, пока освободится общая рабочая копия проекта", { key: ref.key }), action: d.reason, now: new Date(now), log });
log(`${ref.key}: stuck (${d.reason}) — the shared working copy is busy, waits its turn`);
return false;
}
let action: string = d.reason;
try {
await restartAgent(db, ref, s, d.agent);
} catch (e) {
action = `${d.reason}; ${m("агент не перезапустился: {error}", { error: (e as Error).message })}`;
}
const next = attempts + 1;
const nextAt = now + STUCK_RETRY_MIN[Math.min(next - 1, STUCK_RETRY_MIN.length - 1)]! * 60_000;
await setSetting(db, healKey(ref.task.id), { attempts: next, at: now, nextAt, action } satisfies StuckHeal);
// glossary-ignore: сообщение суперадмину
const details = m("⏳ {key} не движется {h} ч: {reason}. Агент перезапущен с причиной (попытка {n} из {max}).", { key: ref.key, h: idleH, reason: action, n: next, max: STUCK_MAX_ATTEMPTS });
await platformDelay(db, scope, { reason: "stuck", state: "retrying", quiet: true, attempts: next, retryAt: nextAt, details, action, now: new Date(now), log });
log(`${ref.key}: stuck (${d.reason}) — agent relaunched, attempt ${next}/${STUCK_MAX_ATTEMPTS}`);
return true;
}