peppa/packages/runner/src/flow.ts
2026-11-15 14:47:50 +05:00

163 lines
8.6 KiB
TypeScript

// PM-side moves on the task board and review acceptance (web and Telegram use these).
import { m } from "@peppa/shared/i18n";
import { releaseIntake } from "./intake.ts";
import { answerQuestion, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
import { tasks, projects, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { eq } from "drizzle-orm";
import { assertBudgetOpen, stopSession, type StartOptions } from "./sessions.ts";
import { cleanupWorktree, releaseRunner, runnerFollowsQueue, startTaskOnRunner } from "./runners.ts";
import { mergeTaskPr } from "./ci-feedback.ts";
import { syncWorkspace } from "./workspace-sync.ts";
import { closeLinkedIssue } from "./gitea-events.ts";
import type { GiteaClient } from "@peppa/core";
import { isRunnerClient, runnerCall } from "./runner-client.ts";
export type BoardColumn = "backlog" | "in_progress" | "review" | "done";
/** Which board column a task status belongs to. */
export function columnOf(status: string): BoardColumn {
if (status === "backlog") return "backlog";
if (status === "review") return "review";
if (status === "done") return "done";
return "in_progress"; // proposing, awaiting_approval, in_progress, blocked
}
async function activeSessions(db: Db, taskId: number) {
return (await listSessions(db, { active: true, taskId }));
}
/**
* Review gate (PEP-57): the task's PR head must have green checks and no conflicts. Fails
* open when Gitea can't be reached — merging is gated again on "Accept".
*/
export async function reviewGate(ref: TaskRef): Promise<string | null> {
const gate = await prGate(ref).catch(() => null);
return gate && !gate.ok ? gate.reason ?? m("проверки не пройдены") : null;
}
/**
* Moves a task card. Into "in progress": status in_progress and an agent session is
* started unless one is running. Into "review": only past the CI gate. Into
* "backlog"/"done": active sessions are stopped.
*/
export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}, gitea?: GiteaClient): Promise<{ started?: number; runner?: number; queued?: boolean; stopped: number }> {
// PEP-21: the whole move runs in the runner service (one at a time per story).
if (isRunnerClient()) return runnerCall(db, "move", { task: ref.key, to, start }, { key: `task:${ref.task.id}` });
const from = columnOf(ref.task.status);
let stopped = 0;
if (to === "in_progress") {
// PEP-84: the PM took the story before the roles finished — they let it go.
await releaseIntake(db, ref.task.id);
if ((await activeSessions(db, ref.task.id)).length === 0) await assertBudgetOpen(db, ref.task.id);
if (from !== "in_progress") await updateTask(db, ref, { status: "in_progress" });
// PEP-10: by the runner settings — a new runner, or a free/queued runner of the project.
if ((await activeSessions(db, ref.task.id)).length === 0 && (await queuedItems(db, { taskId: ref.task.id })).length === 0) {
return { ...(await startTaskOnRunner(db, ref, start)), stopped };
}
return { stopped };
}
if (to === "review" && from !== "review") {
const reason = await reviewGate(ref);
if (reason) throw new PeppaError(m("{key} нельзя в ревью: {reason}", { key: ref.key, reason }));
}
const release: number[] = [];
if (to === "backlog" || to === "done") {
await dropQueuedTask(db, ref.task.id);
for (const s of await activeSessions(db, ref.task.id)) {
// PEP-10: a queue runner is released on "done" and takes its next story.
if (to === "done" && (await runnerFollowsQueue(db, s))) {
release.push(s.id);
continue;
}
await stopSession(db, s.id);
stopped++;
}
}
// Fresh status: a webhook (PEP-46) may have finished the story since `ref` was read.
const [now] = to === "done" ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, ref.task.id)) : [];
if (from !== to || ref.task.status !== to) await updateTask(db, ref, { status: to });
// PEP-46: a finished story closes the Gitea issue it came from.
if (to === "done" && now && now.status !== "done") await closeLinkedIssue(ref, gitea);
for (const id of release) await releaseRunner(db, id, ref.task.id);
return { stopped };
}
/**
* PEP-34: archive a story (hidden from the board, dispatcher and epic progress) or restore it.
* Its agents stop: nobody should work on an invisible card; a story at work goes back to the
* backlog first.
*/
export async function archiveTask(db: Db, ref: TaskRef, archived: boolean): Promise<{ stopped: number }> {
if (isRunnerClient()) return runnerCall(db, "archive", { task: ref.key, archived }, { key: `task:${ref.task.id}` });
let stopped = 0;
if (archived) {
for (const s of await activeSessions(db, ref.task.id)) {
await stopSession(db, s.id);
stopped++;
}
if (columnOf(ref.task.status) === "in_progress") await updateTask(db, ref, { status: "backlog" });
}
await setTaskArchived(db, ref, archived);
return { stopped };
}
/** PEP-34: board order within the story's column (= priority for the dispatcher). */
export async function reorderBoardTask(db: Db, ref: TaskRef, r: ReorderTo) {
if (ref.task.archivedAt) throw new PeppaError(m("{key} в архиве", { key: ref.key }));
return reorderTask(db, ref, r, columnOf);
}
/**
* "Accept" on a ready-for-review message: the task's PR is merged (green checks, no
* conflicts — otherwise nothing changes and the PM sees why; Gitea deletes the branch),
* task done, session stopped, the working copy fast-forwarded to main.
*/
export async function acceptTask(db: Db, questionId: number, via: NonNullable<Question["answeredVia"]>, answer = m("✅ Принято")): Promise<TaskRef> {
const q = await getQuestion(db, questionId);
if (isRunnerClient()) {
const r = await runnerCall<{ key: string }>(db, "accept", { questionId, via, answer }, { key: q.taskId ? `task:${q.taskId}` : null });
return resolveTask(db, r.key);
}
if (!q.taskId) throw new PeppaError(m("Вопрос не привязан к стори"));
if (q.answeredAt) throw new PeppaError(m("Уже отвечено ({via}): {answer}", { via: q.answeredVia, answer: q.answer }));
const [t] = await db
.select({ key: projects.key, number: tasks.number })
.from(tasks)
.innerJoin(projects, eq(tasks.projectId, projects.id))
.where(eq(tasks.id, q.taskId));
const ref = await resolveTask(db, formatTaskKey(t!.key, t!.number));
if (ref.task.status !== "review") throw new PeppaError(m("{key} не в ревью (сейчас {status})", { key: ref.key, status: ref.task.status }));
await mergeTaskPr(ref);
// The merge webhook (PEP-46) may have closed the question and the story already.
await answerQuestion(db, q.id, answer, via).catch(() => {});
await moveTask(db, ref, "done");
// PEP-27: the story's finished runners leave their worktrees right away (if nothing is lost).
for (const s of await listSessions(db, { taskId: ref.task.id })) if (s.workspacePath && ["done", "failed"].includes(s.status)) await cleanupWorktree(db, s).catch(() => {});
// PEP-25: the merged main lands in the working copy (best effort, never fails the accept).
await syncWorkspace(db, ref).catch(() => {});
return ref;
}
/**
* «Принять и смержить» on the story page (PEP-32): the open ready-for-review message is
* accepted like in the bot; without one the same steps run by hand (gate, merge, done, sync).
*/
export async function acceptStory(db: Db, ref: TaskRef, via: NonNullable<Question["answeredVia"]> = "web"): Promise<TaskRef> {
if (isRunnerClient()) return resolveTask(db, (await runnerCall<{ key: string }>(db, "acceptStory", { task: ref.key, via }, { key: `task:${ref.task.id}` })).key);
if (ref.task.status !== "review") throw new PeppaError(m("{key} не в ревью (сейчас {status})", { key: ref.key, status: ref.task.status }));
const [open] = (await pendingQuestions(db, ref.project.id)).filter((q) => q.taskId === ref.task.id && q.kind === "attention").slice(-1);
if (open) return acceptTask(db, open.id, via);
await mergeTaskPr(ref);
await moveTask(db, ref, "done");
await syncWorkspace(db, ref).catch(() => {});
return ref;
}
/** True when an "attention" question is the ready-for-review message of its task. */
export async function isReviewQuestion(db: Db, q: Question): Promise<boolean> {
if (q.kind !== "attention" || !q.taskId || q.answeredAt) return false;
const [t] = await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId));
return t?.status === "review";
}