peppa/packages/runner/src/accept-pending.ts
2026-11-16 23:13:34 +05:00

112 lines
6.9 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-127: «Принять» remembered over a conflict is carried through by the watchdog — the agent
// rebases (flow.ts `deferAccept`), and once the story is back in review with green checks the PR
// is merged and the story closed. The PM hears when it closed, or once if it could not be done.
import { alertAdmins, getReviewHold, platformDelay, setReviewHold, answerQuestion, askPm, clearPendingAccept, productLookLine, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef, isProjectPaused } from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { asIs, m } from "@peppa/shared/i18n";
import { and, eq, isNull } from "drizzle-orm";
import { notifyPm } from "./autonomy.ts";
import { mergeOrCloseEmpty } from "./ci-feedback.ts";
import { moveTask, requestRebase } from "./flow.ts";
import { cleanupWorktree } from "./runners.ts";
import { resolveTaskById } from "./sessions.ts";
import { syncWorkspace } from "./workspace-sync.ts";
/** Rebase requests per accept before the PM is told it did not work out. */
export const ACCEPT_MAX_REBASES = 3;
const waitMs = () => (Number(process.env.PEPPA_ACCEPT_WAIT_HOURS) || 24) * 3_600_000;
export interface PendingAcceptTickOptions {
now?: Date;
gitea?: GiteaClient;
log?: (m: string) => void;
}
export async function pendingAcceptTick(db: Db, opts: PendingAcceptTickOptions = {}): Promise<void> {
const log = opts.log ?? (() => {});
const now = (opts.now ?? new Date()).getTime();
for (const [taskId, state] of await listPendingAccepts(db)) {
try {
await carry(db, taskId, state, now, opts.gitea, log);
} catch (e) {
log(`pending accept #${taskId}: ${(e as Error).message}`);
}
}
}
async function carry(db: Db, taskId: number, state: PendingAccept, now: number, client: GiteaClient | undefined, log: (m: string) => void) {
const ref = await resolveTaskById(db, taskId).catch(() => null);
// The PM took the story away (backlog, archive) or it is done already: nothing to carry.
if (!ref || ref.task.archivedAt || !["review", "in_progress", "proposing"].includes(ref.task.status)) {
await clearPendingAccept(db, taskId);
return;
}
// PEP-174: on pause nothing is merged; the accept is carried through after «Продолжить».
if (await isProjectPaused(db, ref.project.id)) return;
const hours = Math.round(waitMs() / 3_600_000);
if (now - state.at > waitMs()) return fail(db, ref, m("агент не обновил изменения за {hours} ч", { hours }), true, log);
if (!taskPrNumber(ref.project, ref.task.prUrl)) {
if (ref.task.status === "review") await finish(db, ref, log);
return;
}
const gitea = client ?? giteaForBot();
const gate = await prGate(ref, gitea); // Gitea down → the next tick tries again
const pull = gate.pull;
if (!pull) return;
if (pull.merged) return finish(db, ref, log);
if (pull.state !== "open") return fail(db, ref, m("результат был закрыт и не попал в продукт"), false, log);
// Merged only from review: the agent says itself that the rebase is finished.
if (ref.task.status !== "review") return;
if (gate.ok) {
await mergeOrCloseEmpty(ref, pull, gitea);
return finish(db, ref, log);
}
if (gate.behind) {
// The main branch moved on: Peppa updates the PR branch itself (once per head) and waits for its checks.
if (state.updateSha === pull.head.sha) return;
await setPendingAccept(db, taskId, { ...state, updateSha: pull.head.sha });
await gitea.updatePullBranch(ref.project.giteaOwner, ref.project.giteaRepo, pull.number);
log(`${ref.key}: accepted, behind the main branch — PR branch updated`);
return;
}
if (pull.mergeable !== false) return; // checks are running or red — CI feedback handles red
if (state.rebases >= ACCEPT_MAX_REBASES) {
return fail(db, ref, m("изменения несколько раз подряд разошлись с основной версией"), true, log);
}
await setPendingAccept(db, taskId, { ...state, rebases: state.rebases + 1 });
await requestRebase(db, ref);
log(`${ref.key}: accepted, conflicts again — rebase ${state.rebases + 1}/${ACCEPT_MAX_REBASES}`);
}
/** Merged: the story is closed like on «Принять», the PM is told. */
async function finish(db: Db, ref: TaskRef, log: (m: string) => void) {
await clearPendingAccept(db, ref.task.id);
const open = await db.select().from(questions).where(and(eq(questions.taskId, ref.task.id), isNull(questions.answeredAt)));
for (const q of open) await answerQuestion(db, q.id, m("✅ Принято"), "system").catch(() => {});
await moveTask(db, ref, "done");
for (const s of await listSessions(db, { taskId: ref.task.id })) if (s.workspacePath && ["done", "failed"].includes(s.status)) await cleanupWorktree(db, s).catch(() => {});
await syncWorkspace(db, ref).catch(() => {});
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_completed", payload: { pr: ref.task.prUrl } });
await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: asIs(ref.task.title) })}${await productLookLine(db, ref.project.id)}`);
log(`${ref.key}: accepted story merged and closed`);
}
/**
* Could not be carried through: the accept is forgotten. PEP-150: the owner is not told — the
* superadmin gets one message. `again`: the story goes back to the usual way to the owner — a
* held «готова к ревью» that `reviewCardTick` sends once the result can be accepted (it asks
* for the rebase itself). Otherwise (the result was closed) the story shows the delay line.
*/
async function fail(db: Db, ref: TaskRef, why: string, again: boolean, log: (m: string) => void) {
await clearPendingAccept(db, ref.task.id);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_failed", payload: { why } });
const details = m("⚠️ {key} «{title}»: не получилось довести приёмку до конца — {why}.", { key: ref.key, title: asIs(ref.task.title), why });
if (again) {
if (ref.task.status === "review" && !(await getReviewHold(db, ref.task.id))) await setReviewHold(db, ref.task.id, { text: m("✅ Задача {key} готова к ревью", { key: ref.key }), at: Date.now() });
await alertAdmins(db, `delay:t${ref.task.id}:accept:${Date.now()}`, `${details}\n${m("Задача вернётся владельцу на приёмку, когда изменения можно будет принять.")}`, log);
} else {
await platformDelay(db, { projectId: ref.project.id, taskId: ref.task.id }, { reason: "accept", exhausted: true, details, log });
}
log(`${ref.key}: accepted story not merged — ${why}`);
}