// 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 { addStoryComment, approveProposal, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, clearCapacityWait, isWaitingForCapacity, 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, sendToSession, 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. Closed * when Gitea can't be asked (PEP-127): the PM never gets a story that may not be mergeable. */ export async function reviewGate(ref: TaskRef): Promise { const gate = await prGate(ref).catch(() => null); if (!gate) return GATE_UNKNOWN_REASON; // A branch that is only behind the base is updated by Peppa itself before the PM hears (PEP-127). return gate.ok || gate.behind ? null : gate.reason ?? m("проверки не пройдены"); } /** * 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; waiting?: boolean; stopped: number }> { // PEP-174: a project on pause takes no story into work. if (to === "in_progress") await assertProjectActive(db, ref.project.id); // 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; // PEP-197: a person moved the card — that is the decision on a «Предложено» story. if (ref.task.proposed) { await approveProposal(db, ref.task.id); ref.task = { ...ref.task, proposed: false }; } 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. // PEP-182: a story waiting for a free agent keeps its place — `capacityQueueTick` starts it. if ((await activeSessions(db, ref.task.id)).length === 0 && (await queuedItems(db, { taskId: ref.task.id })).length === 0 && !(await isWaitingForCapacity(db, ref.task.id))) { 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); await clearCapacityWait(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) { await clearCapacityWait(db, ref.task.id); 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); } /** The agent of the story rebases its PR onto the fresh main branch (live runner or a new one); the story goes back to work. */ export async function requestRebase(db: Db, ref: TaskRef) { const text = `Пеппа не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review).`; const session = (await activeSessions(db, ref.task.id))[0]; if (session) { await sendToSession(db, session.id, text).catch(() => {}); await moveTask(db, ref, "in_progress"); } else { await moveTask(db, ref, "in_progress", { prompt: text }); } } /** A story reference from «Принять»; `pending` — accepted, Peppa carries it to the merge itself (PEP-127). */ export type AcceptResult = TaskRef & { pending?: boolean }; /** * PEP-127: the PR can't be merged right now → the accept is remembered instead of failing, and * `pendingAcceptTick` merges and closes the story once it is in review, up to date and green. * A conflict: the agent rebases. Behind the base: Peppa updates the branch (Gitea) and waits for * the checks of the new head. Checks still running: wait. Red checks are not deferred. * False — mergeable now (or no PR, or Gitea can't be asked): accept the usual way. */ async function deferAccept(db: Db, ref: TaskRef, via: string): Promise { const gate = await prGate(ref).catch(() => null); const pull = gate?.pull; if (!gate || gate.ok || !pull || pull.merged || pull.state !== "open") return false; // Red checks are refused with the reason, as before (spec delivery-pipeline): the agent fixes them first. if (gate.summary?.state === "failure") return false; const conflict = pull.mergeable === false; await setPendingAccept(db, ref.task.id, { at: Date.now(), via, rebases: conflict ? 1 : 0, ...(gate.behind ? { updateSha: pull.head.sha } : {}) }); if (gate.behind) await giteaForBot().updatePullBranch(ref.project.giteaOwner, ref.project.giteaRepo, pull.number).catch(() => {}); if (!conflict) return true; try { await requestRebase(db, ref); } catch (e) { // No agent could start (budget, subscription): nothing is remembered, the story stays in review. await clearPendingAccept(db, ref.task.id); const fresh = await resolveTask(db, ref.key); if (fresh.task.status !== "review") await updateTask(db, fresh, { status: "review" }).catch(() => {}); throw new PeppaError(m("Изменения нужно обновить перед приёмкой, но агент не запустился: {message}", { message: (e as Error).message })); } return true; } /** * "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, answer = m("✅ Принято")): Promise { const q = await getQuestion(db, questionId); if (isRunnerClient()) { const r = await runnerCall<{ key: string; pending?: boolean }>(db, "accept", { questionId, via, answer }, { key: q.taskId ? `task:${q.taskId}` : null }); return { ...(await resolveTask(db, r.key)), pending: !!r.pending }; } 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 })); if (await deferAccept(db, ref, via)) { await answerQuestion(db, q.id, PENDING_ACCEPT_ANSWER, via).catch(() => {}); return { ...ref, pending: true }; } 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 = "web"): Promise { if (isRunnerClient()) { const r = await runnerCall<{ key: string; pending?: boolean }>(db, "acceptStory", { task: ref.key, via }, { key: `task:${ref.task.id}` }); return { ...(await resolveTask(db, r.key)), pending: !!r.pending }; } 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); if (await deferAccept(db, ref, via)) return { ...ref, pending: true }; await mergeTaskPr(ref); await moveTask(db, ref, "done"); await syncWorkspace(db, ref).catch(() => {}); return ref; } /** * «Поправить» on the story page (PEP-120): the owner's remark is kept in the story, the story * goes from review back to work and the remark reaches the agent — the live one right away, * otherwise a new agent starts with it. Built from calls that reach the runner service themselves. */ export async function fixStory(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string, via: NonNullable = "web"): Promise<{ delivered: boolean }> { const remark = text.trim(); if (!remark) throw new PeppaError(STORY_PRODUCT_TEXT.fixEmpty); if (ref.task.status !== "review") throw new PeppaError(m("{key} не в ревью (сейчас {status})", { key: ref.key, status: ref.task.status })); const c = await addStoryComment(db, ref, author, remark); const message = `Замечание PM (${author.login}) к ${ref.key} — стори возвращена в работу, поправь:\n${c.text}`; const live = await activeSessions(db, ref.task.id); const moved = await moveTask(db, ref, "in_progress", { prompt: message }); // The «готово к ревью» message is answered by the remark: nothing is left to accept. for (const q of (await pendingQuestions(db, ref.project.id)).filter((q) => q.taskId === ref.task.id && q.kind === "attention")) await answerQuestion(db, q.id, c.text, via).catch(() => {}); if (moved.started || moved.runner || moved.queued) return { delivered: true }; if (!live[0]) return { delivered: false }; // A session that died without the watchdog noticing yet: the agent reads the remark in get_task. return { delivered: await sendToSession(db, live[0].id, message).then(() => true, () => false) }; } /** True when an "attention" question is the ready-for-review message of its task. */ export async function isReviewQuestion(db: Db, q: Question): Promise { 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"; }