import { m as tr } from "@peppa/shared/i18n"; import { actorColumns, currentActor, runAsActor } from "./actor.ts"; import { events, goals, projects, questions, taskStatus, tasks, type Db } from "@peppa/db"; import { formatTaskKey, parseTaskKey } from "@peppa/shared"; import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { getGoal, getProject, type Goal, type Project } from "./projects.ts"; import { incidentForTask, type Incident } from "./incidents.ts"; import { taskCiSummary, type CiSummary } from "./ci.ts"; import { latestReview, type CodeReview } from "./reviews.ts"; import { getAutonomy, type AutonomySettings } from "./autonomy.ts"; import { reviewPreview, type ReviewPreview } from "./preview.ts"; import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; import { taskBudgetView, type TaskBudgetView } from "./budgets.ts"; import { productNeeds, type ProductNeedView } from "./product-needs.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; export type Question = typeof questions.$inferSelect; export type QuestionKind = Question["kind"]; export const TASK_STATUSES = taskStatus.enumValues; export interface TaskRef { project: Project; task: Task; key: string; } /** Resolves "PEP-42" / "42" (with a default project key) to the task row. */ export async function resolveTask(db: Db, input: string, defaultProjectKey?: string): Promise { const parsed = parseTaskKey(input, defaultProjectKey); if (!parsed) { throw new PeppaError( defaultProjectKey ? `Can't parse task "${input}": expected ${defaultProjectKey}-42 or 42` : `Can't parse task "${input}": expected KEY-42 (no default project here — is .peppa/project.json present?)`, ); } const project = await getProject(db, parsed.projectKey); const [task] = await db .select() .from(tasks) .where(and(eq(tasks.projectId, project.id), eq(tasks.number, parsed.number))); if (!task) throw new PeppaError(`Task ${formatTaskKey(project.key, parsed.number)} not found`); return { project, task, key: formatTaskKey(project.key, task.number) }; } export interface NewTask { projectId: number; goalId?: number; title: string; description?: string; } export async function createTask(db: Db, t: NewTask): Promise { if (t.goalId != null) await getGoal(db, t.projectId, t.goalId); // Hand out the per-project number atomically. SQLite transactions are synchronous: no // await inside (the driver refuses an async callback). return db.transaction( (tx) => { const [project] = tx .update(projects) .set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` }) .where(eq(projects.id, t.projectId)) .returning() .all(); if (!project) throw new PeppaError(`Project #${t.projectId} not found`); // PEP-34: a new story goes to the end of the board order. const last = tx .select({ max: sql`max(${tasks.position})` }) .from(tasks) .where(eq(tasks.projectId, t.projectId)) .get(); const task = tx .insert(tasks) .values({ ...t, number: project.nextTaskNumber - 1, position: Math.floor(last?.max ?? 0) + 1 }) .returning() .get(); return { project, task, key: formatTaskKey(project.key, task.number) }; }, { behavior: "immediate" }, ); } export interface TaskFilter { projectId?: number; goalId?: number; statuses?: TaskStatus[]; /** PEP-34: archived stories are left out unless asked for. */ includeArchived?: boolean; } export async function listTasks(db: Db, f: TaskFilter = {}): Promise> { const where = []; if (f.projectId != null) where.push(eq(tasks.projectId, f.projectId)); if (f.goalId != null) where.push(eq(tasks.goalId, f.goalId)); if (f.statuses?.length) where.push(inArray(tasks.status, f.statuses)); if (!f.includeArchived) where.push(isNull(tasks.archivedAt)); const rows = await db .select({ task: tasks, projectKey: projects.key }) .from(tasks) .innerJoin(projects, eq(tasks.projectId, projects.id)) .where(and(...where)) .orderBy(asc(projects.key), asc(tasks.position), asc(tasks.number)); return rows.map((r) => ({ ...r.task, key: formatTaskKey(r.projectKey, r.task.number) })); } // ── PEP-34: board order (= priority), archive, epic progress ─────────────────── export type ReorderTo = { to: "top" | "bottom" } | { to: "before" | "after"; other: TaskRef }; /** * Moves a story in the project's board order. The order is shared by the whole project * (a card that went to work and came back keeps its place); "top"/"bottom" are relative to the * story's own column. Positions are reals: the new one is the midpoint between neighbours, * the project is renumbered when the gap gets too small. */ export async function reorderTask(db: Db, ref: TaskRef, r: ReorderTo, columnOf: (s: TaskStatus) => string = (s) => s): Promise { if ("other" in r && r.other.project.id !== ref.project.id) throw new PeppaError(tr("Задачи из разных проектов. Выберите задачи одного проекта.")); if ("other" in r && r.other.task.id === ref.task.id) return ref.task; const all = (await listTasks(db, { projectId: ref.project.id })).filter((t) => t.id !== ref.task.id); const col = all.filter((t) => columnOf(t.status) === columnOf(ref.task.status)); let prev: Task | undefined; let next: Task | undefined; if (r.to === "top") next = col[0]; else if (r.to === "bottom") prev = col.at(-1); else if ("other" in r) { const i = all.findIndex((t) => t.id === r.other.task.id); if (i < 0) throw new PeppaError(tr("{key} в архиве или не найдена", { key: r.other.key })); if (r.to === "before") [prev, next] = [all[i - 1], all[i]]; else [prev, next] = [all[i], all[i + 1]]; } let position: number; if (prev && next) position = (prev.position + next.position) / 2; else if (next) position = next.position - 1; else if (prev) position = prev.position + 1; else position = ref.task.position; if (prev && next && next.position - prev.position < 1e-6) { // Renumber the project 1, 2, 3 … with the story in its new place. const order = [...all]; const at = next ? order.findIndex((t) => t.id === next!.id) : order.length; order.splice(at, 0, ref.task as Task & { key: string }); db.transaction((tx) => { order.forEach((t, i) => tx.update(tasks).set({ position: i + 1 }).where(eq(tasks.id, t.id)).run()); }, { behavior: "immediate" }); position = at + 1; } const [task] = await db.update(tasks).set({ position }).where(eq(tasks.id, ref.task.id)).returning(); await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_reordered", payload: { to: r.to, other: "other" in r ? r.other.key : null }, ...actorColumns() }); await notify(db, { type: "task_updated", taskId: ref.task.id }); return task!; } /** PEP-34: archive (hide everywhere work is picked) or restore a story. History stays. */ export async function setTaskArchived(db: Db, ref: TaskRef, archived: boolean): Promise { const [task] = await db .update(tasks) .set({ archivedAt: archived ? new Date() : null, ...(archived ? {} : { position: await nextPosition(db, ref.project.id) }) }) .where(eq(tasks.id, ref.task.id)) .returning(); await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: archived ? "task_archived" : "task_restored", payload: {}, ...actorColumns() }); await notify(db, { type: "task_updated", taskId: ref.task.id }); return task!; } async function nextPosition(db: Db, projectId: number): Promise { const [r] = await db.select({ max: sql`max(${tasks.position})` }).from(tasks).where(eq(tasks.projectId, projectId)); return Math.floor(r?.max ?? 0) + 1; } export interface EpicProgress { done: number; total: number; } /** PEP-34: done/total of each epic over its non-archived stories. */ export async function epicProgress(db: Db, projectId: number): Promise> { const rows = await db .select({ goalId: tasks.goalId, status: tasks.status }) .from(tasks) .where(and(eq(tasks.projectId, projectId), isNull(tasks.archivedAt))); const out = new Map(); for (const r of rows) { if (r.goalId == null) continue; const p = out.get(r.goalId) ?? { done: 0, total: 0 }; p.total++; if (r.status === "done") p.done++; out.set(r.goalId, p); } return out; } export const progressLabel = (p: EpicProgress | undefined) => (p ? `${p.done}/${p.total}` : "0/0"); export interface TaskPatch { status?: TaskStatus; title?: string; description?: string; goalId?: number | null; openspecChange?: string | null; prUrl?: string | null; } /** `login`: the person who changed it from the web (PEP-32: authors in Activity). */ export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, sessionId?: number, login?: string): Promise { if (patch.goalId != null) await getGoal(db, ref.project.id, patch.goalId); const [task] = await db.update(tasks).set(patch).where(eq(tasks.id, ref.task.id)).returning(); const changed = Object.fromEntries( Object.entries(patch).filter(([k, v]) => v !== undefined && ref.task[k as keyof Task] !== v), ); if (Object.keys(changed).length) { await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "task_updated", payload: { from: pick(ref.task, Object.keys(changed)), to: changed, ...(login ? { login } : {}) }, ...actorColumns(sessionId), }); await notify(db, { type: "task_updated", taskId: ref.task.id }); } return task!; } export interface TaskDetails { key: string; task: Task; project: Project; goal: Goal | null; questions: Question[]; recentEvents: Array; /** The production error this task fixes (PEP-58), if any. */ incident: Incident | null; /** CI checks of the task's latest commit (PEP-57). */ ci: CiSummary; /** Latest review by the project's reviewer agent (PEP-26), if any. */ review: CodeReview | null; /** The project's autonomy settings (PEP-23): agents follow them. */ autonomy: AutonomySettings; /** PM comments on the story (PEP-32), oldest first: the agent reads them in get_task. */ comments: StoryComment[]; /** Preview stand, diff, checks, screenshots, Gitea issue (PEP-44/46). */ preview: ReviewPreview; /** PEP-42: stories this one waits for, and stories that wait for it. */ blockers: Blocker[]; dependents: Array<{ id: number; key: string; title: string; status: TaskStatus }>; /** PEP-112: what the owner has to give before the product works for real. */ needs?: ProductNeedView[]; /** PEP-43/5: what the story spent and its budget. */ budget: TaskBudgetView; } export const COMMENT_EVENT = "pm_comment"; export interface StoryComment { id: number; login: string; text: string; createdAt: Date; /** PEP-84: a note of «продакт» / «аналитик» rather than a person's comment. */ role?: "product" | "analyst"; } /** A PM comment on a story (PEP-32): an event the agent sees in get_task. */ export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string, extra: { chatMessageId?: number } = {}): Promise { const body = text.trim(); if (!body) throw new PeppaError(tr("Пустой комментарий")); if (body.length > 8000) throw new PeppaError(tr("Комментарий длиннее 8000 символов")); const [row] = await db .insert(events) .values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body, ...extra }, ...actorColumns() }) .returning(); await notify(db, { type: "task_updated", taskId: ref.task.id }); return { id: row!.id, login: author.login, text: body, createdAt: row!.createdAt }; } export async function storyComments(db: Db, taskId: number): Promise { const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), inArray(events.type, [COMMENT_EVENT, "intake_note"]))).orderBy(asc(events.id)); return rows.map((e) => { const p = (e.payload ?? {}) as { login?: string; text?: string; role?: "product" | "analyst" }; if (e.type === "intake_note") return { id: e.id, login: p.role === "product" ? tr("Продакт") : tr("Аналитик"), text: p.text ?? "", createdAt: e.createdAt, role: p.role ?? "analyst" }; return { id: e.id, login: p.login ?? "?", text: p.text ?? "", createdAt: e.createdAt }; }); } export async function getTaskDetails(db: Db, ref: TaskRef): Promise { const [goal] = ref.task.goalId ? await db.select().from(goals).where(eq(goals.id, ref.task.goalId)) : []; const qs = await db.select().from(questions).where(eq(questions.taskId, ref.task.id)).orderBy(asc(questions.id)); const evs = await db .select() .from(events) .where(and(eq(events.taskId, ref.task.id), ne(events.type, "step"))) .orderBy(desc(events.id)) .limit(20); const incident = await incidentForTask(db, ref.task.id); return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref), budget: await taskBudgetView(db, ref.task), needs: await productNeeds(db, ref.project.id) }; } export interface NewQuestion { kind: QuestionKind; text: string; options?: string[]; sessionId?: number; } /** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */ export async function askPm(db: Db, ref: TaskRef, q: NewQuestion): Promise { const [row] = await db .insert(questions) .values({ projectId: ref.project.id, taskId: ref.task.id, ...q }) .returning(); if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId); await notify(db, { type: "question", questionId: row!.id }); return row!; } /** A message for the PM about the project as a whole (releases), not about a task. */ export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise { const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); await notify(db, { type: "question", questionId: row!.id }); return row!; } export async function pendingQuestions(db: Db, projectId?: number): Promise { return db .select() .from(questions) .where(and(isNull(questions.answeredAt), projectId != null ? eq(questions.projectId, projectId) : undefined)) .orderBy(asc(questions.id)); } export async function answerQuestion( db: Db, questionId: number, answer: string, via: NonNullable, ): Promise { const [row] = await db .update(questions) .set({ answer, answeredVia: via, answeredAt: new Date() }) .where(and(eq(questions.id, questionId), isNull(questions.answeredAt))) .returning(); if (!row) throw new PeppaError(`Question #${questionId} not found or already answered`); // PEP-48: who answered the agent (Peppa closing its own messages is not an action). if (via !== "system") { const a = currentActor(); const actor = a?.kind === "user" ? a : { kind: "user" as const, channel: via }; await runAsActor(actor, () => db.insert(events).values({ projectId: row.projectId, taskId: row.taskId, sessionId: row.sessionId, type: "question_answered", payload: { questionId, kind: row.kind, via, answer: answer.length > 500 ? `${answer.slice(0, 500)}…` : answer }, ...actorColumns(), }), ); } await notify(db, { type: "question_answered", questionId }); return row; } export async function reportProgress(db: Db, ref: TaskRef, text: string, sessionId?: number) { const [row] = await db .insert(events) .values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "progress", payload: { text }, ...actorColumns(sessionId) }) .returning(); await notify(db, { type: "progress", eventId: row!.id }); return row!; } function pick(o: T, keys: string[]): Record { return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]])); }