peppa/packages/runner/src/platform-delays.ts

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

// 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 {
clearPlatformDelay,
deleteSetting,
getAutonomy,
getPlatformDelay,
getSession,
getSetting,
giteaForBot,
listPlatformDelays,
listSessions,
listTasks,
pendingSessionQuestions,
PeppaError,
platformDelay,
prGate,
savePlatformDelay,
setSetting,
taskPrNumber,
type GiteaClient,
type PlatformDelay,
type Question,
} from "@peppa/core";
import { settings, type Db } 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 { 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<boolean> {
const hint = await getSetting<LimitHint>(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;
}
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<number>();
const fresh: Array<{ projectId: number; taskId: number; key: string; sessionId: number | null }> = [];
let stuck = 0;
let oldest = now;
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<ChecksWait>(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) {
stuck++;
oldest = Math.min(oldest, w.since);
}
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(like(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 };
}
if (fresh.length) {
// One message per queue episode (from the first stuck story until none is left).
const queue = (await getSetting<{ since: number }>(db, QUEUE)) ?? { since: now };
await setSetting(db, QUEUE, queue);
const details = `${m("⏳ Очередь проверок: {n} ждут, старшему {min} мин.", { n: stuck, min: Math.round((now - oldest) / 60_000) })}\n${fresh.map((f) => f.key).join(", ")}`;
for (const f of fresh) await platformDelay(db, f, { reason: "checks", details, alertKey: `checks:${queue.since}`, now: new Date(now), log });
log(`checks queue: ${stuck} waiting, oldest ${Math.round((now - oldest) / 60_000)} min`);
}
return { stuck };
}
// ── 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<PlatformDelay | null> {
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 } = {}): Promise<void> {
const log = o.log ?? (() => {});
const now = (o.now ?? new Date()).getTime();
for (const d of await listPlatformDelays(db)) {
try {
await sweep(db, d, now, log);
} 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) {
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 });
if (d.reason === "agent") {
if (live.some((s) => ["running", "idle", "waiting_input"].includes(s.status))) 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 });
}
}
}