138 lines
6.6 KiB
TypeScript
138 lines
6.6 KiB
TypeScript
// PM-side moves on the task board and review acceptance (web and Telegram use these).
|
|
import { answerQuestion, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, 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 { startSession, stopSession, type StartOptions } from "./sessions.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";
|
|
|
|
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 ?? "проверки не пройдены" : 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; stopped: number }> {
|
|
const from = columnOf(ref.task.status);
|
|
let stopped = 0;
|
|
if (to === "in_progress") {
|
|
if (from !== "in_progress") await updateTask(db, ref, { status: "in_progress" });
|
|
if ((await activeSessions(db, ref.task.id)).length === 0) {
|
|
const s = await startSession(db, ref.key, start);
|
|
return { started: s.id, stopped };
|
|
}
|
|
return { stopped };
|
|
}
|
|
if (to === "review" && from !== "review") {
|
|
const reason = await reviewGate(ref);
|
|
if (reason) throw new PeppaError(`${ref.key} нельзя в ревью: ${reason}`);
|
|
}
|
|
if (to === "backlog" || to === "done") {
|
|
for (const s of await activeSessions(db, ref.task.id)) {
|
|
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);
|
|
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 }> {
|
|
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(`${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 = "✅ Принято"): Promise<TaskRef> {
|
|
const q = await getQuestion(db, questionId);
|
|
if (!q.taskId) throw new PeppaError("Вопрос не привязан к стори");
|
|
if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${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(`${ref.key} не в ревью (сейчас ${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-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 (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${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";
|
|
}
|