peppa/packages/core/src/tasks.ts
peppa-bot 5019e1ad80
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/test test: success за 1546с
peppa-ci / ci (pull_request) Successful in 28m56s
Merge branch 'main' into task/pep-259
Миграция сроков разрешений переименована в 0034 (0033 заняла PEP-252).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:54:14 +00:00

457 lines
22 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.

import { asIs, hasAsIs, 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";
import { taskAttachments, type TaskAttachment } from "./attachments.ts";
import { raiseOnce, type MessageTopic } from "./message-state.ts";
import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts";
import { defaultMessageType, type MessageType } from "./questions.ts";
import { renderMain, type AgentMessage } from "./agent-message.ts";
import { insertQuestion, setMessageDetails } from "./message-details.ts";
import { touchVersion } from "./task-origin.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<TaskRef> {
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;
/** PEP-197: who made it (default: a person); agents' stories are «Предложено» unless a breakage. */
origin?: "human" | "acceptance" | "incident" | "analyst" | "agent";
proposed?: boolean;
severity?: "breakage" | "important" | "minor" | null;
}
export async function createTask(db: Db, t: NewTask): Promise<TaskRef> {
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).
const made = 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<number | null>`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" },
);
// PEP-197: a story of a person belongs to the project's current version.
if ((t.origin ?? "human") === "human") await touchVersion(db, t.projectId, made.task.id);
return made;
}
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<Array<Task & { key: string }>> {
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<Task> {
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<Task> {
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<number> {
const [r] = await db.select({ max: sql<number | null>`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<Map<number, EpicProgress>> {
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<number, EpicProgress>();
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<Task> {
if (patch.goalId != null) await getGoal(db, ref.project.id, patch.goalId);
// PEP-209: a patch of undefined fields only (MCP update_task with nothing but `status: review` while
// the checks run) — drizzle refuses an empty SET («No values to set»): nothing to write, the story as it is.
const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined)) as TaskPatch;
if (!Object.keys(defined).length) {
const [cur] = await db.select().from(tasks).where(eq(tasks.id, ref.task.id));
return cur!;
}
const [task] = await db.update(tasks).set(defined).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<typeof events.$inferSelect>;
/** 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-159: files attached to the story and its discussion. */
attachments?: TaskAttachment[];
/** 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" | "acceptance";
}
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
/** PEP-180: the longest message a person can send in a chat or a task's discussion. */
export const MESSAGE_MAX = 60_000;
export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string, extra: { chatMessageId?: number } = {}): Promise<StoryComment> {
const body = text.trim();
if (!body) throw new PeppaError(tr("Пустой комментарий"));
// PEP-180: a pasted document fits; longer — as a file (PEP-159).
if (body.length > MESSAGE_MAX) throw new PeppaError(tr("Текст слишком длинный (больше {n} символов) — приложите его файлом", { n: MESSAGE_MAX }));
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<StoryComment[]> {
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" | "acceptance" };
// PEP-198: the old «product» role is the analyst's work now; the acceptance agent keeps its name.
if (e.type === "intake_note") return { id: e.id, login: p.role === "acceptance" ? 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<TaskDetails> {
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), attachments: await taskAttachments(db, ref.task.id) };
}
export interface NewQuestion {
kind: QuestionKind;
text: string;
options?: string[];
sessionId?: number;
/** PEP-151: the type of the message when its text cannot tell (see MessageTopic). */
topic?: MessageTopic;
/** Head commit of the result, when the caller knows it. */
head?: string | null;
/** PEP-149: what the message is for the person; default — by kind (core/questions.ts). */
msgType?: MessageType | null;
/** PEP-149: the option the agent goes on with meanwhile (one of `options`). */
defaultOption?: string;
/** PEP-152: technical details — never in the text, shown under «Подробнее». */
details?: string | null;
}
/** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */
export async function askPm(db: Db, ref: TaskRef, { topic, head, details, ...q }: NewQuestion): Promise<Question> {
// PEP-154: no service text (tags, command output, paths) in what the person reads.
const original = q.text;
q = { ...q, text: messageText(q.kind, q.text) };
// PEP-151: the same state of the story again refreshes the earlier message instead of adding one.
const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => {
return insertQuestion(db, { projectId: ref.project.id, taskId: ref.task.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }, details);
});
// The status goes right after the question: an answer that comes at once (it moves the story
// on) must not be overwritten by a late «awaiting approval».
if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId);
// PEP-152: the details follow the message (a refreshed one gets the fresh details).
if (details !== undefined) await setMessageDetails(db, row.id, details);
await keepQuestionDetails(db, row.id, original, q.text).catch(() => {});
await notify(db, { type: "question", questionId: row.id });
return row;
}
/**
* PEP-139: the question's text and options are the agent's own words (asked through MCP), not
* a factory template — they reach the reader as written, in any interface language.
*/
export const questionIsFreeText = (q: Pick<Question, "kind" | "sessionId">): boolean => q.sessionId != null && (q.kind === "question" || q.kind === "approval");
/** PEP-152: a text built in the message format already carries the marks around the agent's words. */
/** The question's text for a translating reader (`t.text`, `localizeText`): an agent's own words are marked free text. */
export const questionText = (q: Pick<Question, "kind" | "sessionId" | "text">): string => (questionIsFreeText(q) && !hasAsIs(q.text) ? asIs(q.text) : q.text);
/** 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[]; msgType?: MessageType | null; defaultOption?: string | null }): Promise<Question> {
const text = messageText(q.kind, q.text);
const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text, msgType: q.msgType ?? defaultMessageType(q) }).returning();
await keepQuestionDetails(db, row!.id, q.text, text).catch(() => {});
await notify(db, { type: "question", questionId: row!.id });
return row!;
}
export async function pendingQuestions(db: Db, projectId?: number): Promise<Question[]> {
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<Question["answeredVia"]>,
): Promise<Question> {
// PEP-154: an answer is a person's words — service blocks never land in it.
if (via !== "system") {
const said = stripServiceBlocks(answer);
if (!said && answer.trim()) throw new PeppaError(`Question #${questionId}: the answer is service text only`);
answer = said;
}
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;
}
/**
* A progress note of a story. PEP-152: an agent's note comes as a message in the format — the
* payload keeps the main text (`text`) and, apart from it, the details for «Подробнее».
*/
export async function reportProgress(db: Db, ref: TaskRef, note: string | AgentMessage, sessionId?: number) {
const payload = typeof note === "string" ? { text: note } : { text: renderMain(note), details: note.details?.trim() || undefined };
const [row] = await db
.insert(events)
.values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "progress", payload, ...actorColumns(sessionId) })
.returning();
await notify(db, { type: "progress", eventId: row!.id });
return row!;
}
/**
* PEP-149: the agent cannot go on and it is not a product decision — a `blocker` event in the
* story thread («События агентов»). The owner is not asked; what happens next is Peppa's job.
*/
export async function reportBlocker(db: Db, ref: TaskRef, b: { what: string; tried: string; details?: string | null; /** PEP-152: `what` is the platform's neutral line, not the agent's words. */ neutral?: boolean }, sessionId?: number) {
const [row] = await db
.insert(events)
.values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "blocker", payload: { what: b.what, tried: b.tried, details: b.details?.trim() || undefined, neutral: b.neutral || undefined }, ...actorColumns(sessionId) })
.returning();
await notify(db, { type: "progress", eventId: row!.id });
return row!;
}
function pick<T extends object>(o: T, keys: string[]): Record<string, unknown> {
return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]]));
}