PEP-34/42: board order, archive, epic progress, story dependencies, epic planner (core, runner, MCP)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 05:50:35 +05:00
parent 0b448a8b8a
commit f6e3725e5f
19 changed files with 3771 additions and 30 deletions

View File

@ -18,8 +18,9 @@
(события, вопросы, сессии) остаётся.
- Колонка «Готово» сворачивается (запоминается в браузере); в свёрнутом виде видна только
шапка со счётчиком.
- MCP (удалённый и агента): `reorder_task` (top/bottom/before/after), `archive_task`
(archive/restore); `/help` описывает их.
- MCP PM (удалённый): `reorder_task` (top/bottom/before/after), `archive_task`
(archive/restore); агентский MCP порядок не меняет (приоритеты — решение PM), но `list_tasks`
идёт в порядке доски; `/help` описывает их.
## Capabilities
### Modified Capabilities

View File

@ -12,7 +12,7 @@
- [ ] 3.3 Архив/возврат на странице стори
## 4. MCP и справка
- [ ] 4.1 `reorder_task`, `archive_task` (удалённый и агента), прогресс в `list_epics`
- [ ] 4.1 `reorder_task`, `archive_task` (удалённый MCP), прогресс в `list_epics`
- [ ] 4.2 `/help`
## 5. Тесты

126
packages/core/src/deps.ts Normal file
View File

@ -0,0 +1,126 @@
// PEP-42: story dependencies. "PAY-3 waits for PAY-2": PAY-3 is blocked until every
// predecessor reaches review/done (an archived predecessor doesn't block). Same project only,
// no cycles. The backlog dispatcher (PEP-24) skips blocked stories.
import { events, projects, taskDeps, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, eq, inArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import { resolveTask, type Task, type TaskRef, type TaskStatus } from "./tasks.ts";
/** A predecessor in these statuses no longer blocks its successors. */
export const UNBLOCKING: TaskStatus[] = ["review", "done"];
export interface Blocker {
id: number;
key: string;
title: string;
status: TaskStatus;
/** Still holds the story back (not in review/done, not archived). */
open: boolean;
}
const isOpen = (t: Pick<Task, "status" | "archivedAt">) => !t.archivedAt && !UNBLOCKING.includes(t.status);
/** Predecessors of each of the given stories (all of a project when `projectId` is given). */
export async function blockersMap(db: Db, projectId: number): Promise<Map<number, Blocker[]>> {
const projectTasks = await db.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.projectId, projectId));
const byId = new Map(projectTasks.map((t) => [t.id, t]));
if (!projectTasks.length) return new Map();
const deps = await db.select().from(taskDeps).where(inArray(taskDeps.taskId, projectTasks.map((t) => t.id)));
const [project] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
if (!project) return new Map();
const out = new Map<number, Blocker[]>();
for (const d of deps) {
const b = byId.get(d.blockedById);
if (!b) continue;
const list = out.get(d.taskId) ?? [];
list.push({ id: b.id, key: formatTaskKey(project.key, b.number), title: b.title, status: b.status, open: isOpen(b) });
out.set(d.taskId, list);
}
for (const list of out.values()) list.sort((a, b) => a.id - b.id);
return out;
}
export async function blockersOf(db: Db, ref: TaskRef): Promise<Blocker[]> {
return (await blockersMap(db, ref.project.id)).get(ref.task.id) ?? [];
}
/** Stories that wait for this one. */
export async function dependentsOf(db: Db, ref: TaskRef): Promise<Array<{ id: number; key: string; title: string; status: TaskStatus }>> {
const rows = await db
.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status })
.from(taskDeps)
.innerJoin(tasks, eq(taskDeps.taskId, tasks.id))
.where(eq(taskDeps.blockedById, ref.task.id));
return rows.map((r) => ({ id: r.id, key: formatTaskKey(ref.project.key, r.number), title: r.title, status: r.status }));
}
/** Ids of the project's stories that are blocked right now. */
export async function blockedTaskIds(db: Db, projectId: number): Promise<Set<number>> {
const out = new Set<number>();
for (const [id, list] of await blockersMap(db, projectId)) if (list.some((b) => b.open)) out.add(id);
return out;
}
/** True when `from` can reach `to` following "waits for" edges. */
async function reaches(db: Db, from: number, to: number): Promise<boolean> {
const seen = new Set<number>();
let frontier = [from];
while (frontier.length) {
if (frontier.includes(to)) return true;
frontier.forEach((x) => seen.add(x));
const rows = await db.select({ next: taskDeps.blockedById }).from(taskDeps).where(inArray(taskDeps.taskId, frontier));
frontier = [...new Set(rows.map((r) => r.next))].filter((x) => !seen.has(x));
}
return false;
}
/** Makes `ref` wait for `blocker`. Idempotent; rejects other projects, itself and cycles. */
export async function addDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise<void> {
if (blocker.project.id !== ref.project.id) throw new PeppaError(`${blocker.key} из другого проекта — зависимости только внутри проекта`);
if (blocker.task.id === ref.task.id) throw new PeppaError(`${ref.key} не может зависеть от самой себя`);
if (await reaches(db, blocker.task.id, ref.task.id)) throw new PeppaError(`Цикл зависимостей: ${blocker.key} уже ждёт ${ref.key}`);
const r = await db.insert(taskDeps).values({ taskId: ref.task.id, blockedById: blocker.task.id }).onConflictDoNothing().returning();
if (r.length) await logDeps(db, ref, { added: blocker.key });
}
export async function removeDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise<void> {
const r = await db.delete(taskDeps).where(and(eq(taskDeps.taskId, ref.task.id), eq(taskDeps.blockedById, blocker.task.id))).returning();
if (r.length) await logDeps(db, ref, { removed: blocker.key });
}
/** Replaces the whole list of predecessors ("PAY-2", "2"). Validates everything before changing anything. */
export async function setDependencies(db: Db, ref: TaskRef, keys: string[]): Promise<Blocker[]> {
const wanted: TaskRef[] = [];
for (const k of [...new Set(keys.map((x) => x.trim()).filter(Boolean))]) wanted.push(await resolveTask(db, k, ref.project.key));
const current = await blockersOf(db, ref);
const keep = new Set(wanted.map((w) => w.task.id));
for (const c of current) if (!keep.has(c.id)) await db.delete(taskDeps).where(and(eq(taskDeps.taskId, ref.task.id), eq(taskDeps.blockedById, c.id)));
const have = new Set(current.map((c) => c.id));
const added: string[] = [];
try {
for (const w of wanted) {
if (have.has(w.task.id)) continue;
await addDependency(db, ref, w);
added.push(w.key);
}
} catch (e) {
// Roll back to the previous list: either all of it applies or none.
await db.delete(taskDeps).where(eq(taskDeps.taskId, ref.task.id));
if (current.length) await db.insert(taskDeps).values(current.map((c) => ({ taskId: ref.task.id, blockedById: c.id })));
throw e;
}
return blockersOf(db, ref);
}
async function logDeps(db: Db, ref: TaskRef, payload: Record<string, string>) {
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_deps", payload });
await notify(db, { type: "task_updated", taskId: ref.task.id });
}
/** "ждёт PAY-2, PAY-5" for the open blockers, or null. */
export function blockedLabel(list: Blocker[] | undefined): string | null {
const open = (list ?? []).filter((b) => b.open);
return open.length ? `ждёт ${open.map((b) => b.key).join(", ")}` : null;
}

View File

@ -29,3 +29,4 @@ export * from "./autonomy.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
export * from "./preview.ts";
export * from "./deps.ts";

View File

@ -9,6 +9,7 @@ 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";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@ -61,9 +62,15 @@ export async function createTask(db: Db, t: NewTask): Promise<TaskRef> {
.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 })
.values({ ...t, number: project.nextTaskNumber - 1, position: Math.floor(last?.max ?? 0) + 1 })
.returning()
.get();
return { project, task, key: formatTaskKey(project.key, task.number) };
@ -76,6 +83,8 @@ 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 }>> {
@ -83,15 +92,103 @@ export async function listTasks(db: Db, f: TaskFilter = {}): Promise<Array<Task
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.number));
.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("Стори из разных проектов");
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(`${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 } });
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: {} });
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;
@ -140,6 +237,9 @@ export interface TaskDetails {
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 }>;
}
export const COMMENT_EVENT = "pm_comment";
@ -181,7 +281,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
.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) };
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) };
}
export interface NewQuestion {

View File

@ -0,0 +1,13 @@
CREATE TABLE `task_deps` (
`task_id` integer NOT NULL,
`blocked_by_id` integer NOT NULL,
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
PRIMARY KEY(`task_id`, `blocked_by_id`),
FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`blocked_by_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `task_deps_blocked_by` ON `task_deps` (`blocked_by_id`);--> statement-breakpoint
ALTER TABLE `tasks` ADD `position` real DEFAULT 0 NOT NULL;--> statement-breakpoint
ALTER TABLE `tasks` ADD `archived_at` integer;--> statement-breakpoint
UPDATE `tasks` SET `position` = `number`;

File diff suppressed because it is too large Load Diff

View File

@ -57,6 +57,13 @@
"when": 1794617253656,
"tag": "0007_calm_anthem",
"breakpoints": true
},
{
"idx": 8,
"version": "6",
"when": 1794619727659,
"tag": "0008_board_order_deps",
"breakpoints": true
}
]
}

View File

@ -1,6 +1,6 @@
import { relations } from "drizzle-orm";
import { sql } from "drizzle-orm";
import { integer, primaryKey, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
// SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is
// text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only.
@ -129,12 +129,27 @@ export const tasks = sqliteTable(
ciFailedSha: text("ci_failed_sha"),
// PEP-46: the Gitea issue of the project's repo this story came from (or is linked to).
giteaIssue: integer("gitea_issue"),
// PEP-34: order on the board = priority for the dispatcher (lower first; shared by the project).
position: real("position").notNull().default(0),
// PEP-34: archived stories are hidden from the board, the dispatcher and epic progress.
archivedAt: integer("archived_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue)],
);
/** PEP-42: "task waits for blocked_by" — a story is blocked until its predecessors reach review/done. */
export const taskDeps = sqliteTable(
"task_deps",
{
taskId: integer("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }),
blockedById: integer("blocked_by_id").notNull().references(() => tasks.id, { onDelete: "cascade" }),
createdAt: createdAt(),
},
(t) => [primaryKey({ columns: [t.taskId, t.blockedById] }), index("task_deps_blocked_by").on(t.blockedById)],
);
/** PEP-57: one deployment of a project to an environment (and its outcome). */
export const releases = sqliteTable("releases", {
id: integer("id").primaryKey({ autoIncrement: true }),

View File

@ -23,6 +23,12 @@ export function formatTask(d: TaskDetails): string {
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
if (d.preview?.issueUrl) lines.push(`- Issue Gitea: ${d.preview.issueUrl}`);
if (d.preview?.previewUrl) lines.push(`- Превью: ${d.preview.previewUrl}${d.preview.screenshots.length ? ` (скриншотов: ${d.preview.screenshots.length})` : ""}`);
if (task.archivedAt) lines.push(`- В архиве с ${task.archivedAt.toISOString().slice(0, 10)} (не видна на доске, диспетчер её не берёт)`);
if (d.blockers?.length) {
const open = d.blockers.filter((b) => b.open);
lines.push(`- Ждёт: ${d.blockers.map((b) => `${b.key} [${b.status}]${b.open ? "" : " ✓"}`).join(", ")}${open.length ? " — заблокирована, пока они не в review/done" : " — разблокирована"}`);
}
if (d.dependents?.length) lines.push(`- Её ждут: ${d.dependents.map((t) => `${t.key} [${t.status}]`).join(", ")}`);
lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`);
for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`);
if (d.review) {

View File

@ -14,6 +14,11 @@ import {
listIncidents,
listEpics,
listTasks,
blockedLabel,
blockersMap,
epicProgress,
progressLabel,
setDependencies,
loadSharedRules,
PeppaError,
reportProgress,
@ -79,13 +84,17 @@ tool("get_task", "Get a Peppa story (one business story = one OpenSpec change):
tool(
"list_tasks",
"List stories in a project, optionally filtered by status or epic.",
"List stories in a project in board order (top = highest priority), optionally filtered by status or epic; \"waits for\" marks stories blocked by unfinished predecessors.",
{ project: projectArg, status: z.enum(TASK_STATUSES).optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id") },
async ({ project, status, epic_id, goal_id }) => {
const p = await projectOrDefault(project);
const rows = await listTasks(db, { projectId: p.id, goalId: epic_id ?? goal_id, statuses: status ? [status] : undefined });
if (!rows.length) return "No stories.";
return rows.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`).join("\n");
const deps = await blockersMap(db, p.id);
return rows.map((t) => {
const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for");
return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`;
}).join("\n");
},
);
@ -93,7 +102,8 @@ const listEpicsText = async ({ project }: { project?: string }) => {
const p = await projectOrDefault(project);
const rows = await listEpics(db, p.id);
if (!rows.length) return "No open epics.";
return rows.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
const progress = await epicProgress(db, p.id);
return rows.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
};
tool("list_epics", "List the open epics of a project (labels that group stories).", { project: projectArg }, listEpicsText);
tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, listEpicsText);
@ -106,12 +116,14 @@ tool(
description: z.string().optional(),
epic_id: z.number().int().optional(),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Stories this one waits for (keys); it won't be started automatically until they are in review/done"),
project: projectArg,
},
async ({ title, description, epic_id, goal_id, project }) => {
async ({ title, description, epic_id, goal_id, blocked_by, project }) => {
const p = await projectOrDefault(project);
const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description });
return `Created ${ref.key}: ${title}`;
const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : [];
return `Created ${ref.key}: ${title}${deps.length ? ` (waits for ${deps.map((d) => d.key).join(", ")})` : ""}`;
},
);

View File

@ -30,11 +30,16 @@ import {
listIncidents,
POLICY_RU,
updateIncidentSettings,
blockedLabel,
blockersMap,
epicProgress,
progressLabel,
setDependencies,
type User,
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
import { applyPlan, archiveTask, planEpic, reorderBoardTask, type PlannedStory, currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
@ -54,6 +59,9 @@ Good habits:
- Before creating, look: list_projects, list_epics, list_tasks. Don't duplicate — fix with update_task / update_epic.
- Label stories with an epic (epic_id) when one fits. Write story descriptions with context and a "Definition of done" list; the agent works from them.
- Only move a story to in_progress when the user asks to start the work.
- Board order = priority: list_tasks shows each column top-down; reorder_task moves a story (the backlog dispatcher takes from the top). archive_task hides a story without deleting it.
- Dependencies: a story can wait for others (blocked_by in create_task/update_task, set_dependencies); blocked stories are not started by the dispatcher until predecessors are in review/done.
- Planning: plan_epic breaks an epic into stories with dependencies and returns a draft; after the user agrees (edit freely), apply_plan creates them.
- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user.
- Projects can be shared: add_member / remove_member (owner only); members can do everything else. Repos are public by default; set_project_visibility (owner only) makes one private or public again.
- CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks.
@ -132,7 +140,8 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
const listEpicsText = async ({ project }: { project: string }) => {
const p = await ownedProject(project);
const gs = await listEpics(db, p.id);
return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open epics.";
const progress = await epicProgress(db, p.id);
return gs.length ? gs.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open epics.";
};
const createEpicShape = { project: projectArg, title: z.string().trim().min(3), description: z.string().optional().describe("What the epic is about; agents get it with every story of the epic") };
const createEpicText = async ({ project, title, description }: { project: string; title: string; description?: string }) => {
@ -238,16 +247,23 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"list_tasks",
"List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column.",
"List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column. Each column is in board order (top = highest priority; the backlog dispatcher takes from the top); \"waits for\" marks stories blocked by unfinished predecessors.",
{ project: projectArg, column: z.enum(COLUMNS).optional() },
true,
async ({ project, column }) => {
const p = await ownedProject(project);
const ts = await listTasks(db, { projectId: p.id });
const deps = await blockersMap(db, p.id);
const out: string[] = [];
for (const c of column ? [column] : COLUMNS) {
const inCol = ts.filter((t) => columnOf(t.status) === c);
out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`));
out.push(
`## ${COLUMN_NAME[c]} (${inCol.length})`,
...inCol.map((t) => {
const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for");
return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`;
}),
);
}
return out.join("\n");
},
@ -267,31 +283,35 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
description: z.string().optional(),
epic_id: z.number().int().optional().describe("Epic of the same project (list_epics)"),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Stories of the same project this one waits for (keys like PEP-3); the dispatcher won't start it until they are in review/done"),
},
false,
async ({ project, title, description, epic_id, goal_id }) => {
async ({ project, title, description, epic_id, goal_id, blocked_by }) => {
const p = await ownedProject(project);
const ref = await createTask(db, { projectId: p.id, title, description, goalId: epic_id ?? goal_id });
return `Created ${ref.key}: ${title} (Backlog). ${webUrl}/t/${ref.key}`;
const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : [];
return `Created ${ref.key}: ${title} (Backlog, bottom of the board)${deps.length ? ` · waits for ${deps.map((d) => d.key).join(", ")}` : ""}. ${webUrl}/t/${ref.key}`;
},
);
tool(
"update_task",
"Edit a story: title, description and/or epic (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
"Edit a story: title, description, epic and/or dependencies (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
{
task: taskArg,
title: z.string().trim().min(3).optional().describe("New title"),
description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"),
epic_id: z.number().int().nullable().optional().describe("Label with this epic of the same project; null removes the epic"),
goal_id: z.number().int().nullable().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Replaces the stories this one waits for (keys like PEP-3); [] removes all dependencies"),
},
false,
async ({ task, title, description, epic_id, goal_id }) => {
async ({ task, title, description, epic_id, goal_id, blocked_by }) => {
const epic = epic_id !== undefined ? epic_id : goal_id;
if (title === undefined && description === undefined && epic === undefined) throw new PeppaError("Nothing to update: pass title, description and/or epic_id");
if (title === undefined && description === undefined && epic === undefined && blocked_by === undefined) throw new PeppaError("Nothing to update: pass title, description, epic_id and/or blocked_by");
const ref = await ownedTask(task);
await updateTask(db, ref, { title, description, goalId: epic });
if (blocked_by !== undefined) await setDependencies(db, ref, blocked_by);
if (title !== undefined || description !== undefined || epic !== undefined) await updateTask(db, ref, { title, description, goalId: epic });
const updated = await resolveTask(db, ref.key);
return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`;
},
@ -309,6 +329,80 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
tool(
"reorder_task",
"Change a story's place on the board (= priority: the backlog dispatcher and idle pushes take from the top). top/bottom are within the story's column; before/after put it next to another story of the same project.",
{ task: taskArg, position: z.enum(["top", "bottom", "before", "after"]), other: z.string().optional().describe("For before/after: the story key to put it next to") },
false,
async ({ task, position, other }) => {
const ref = await ownedTask(task);
if ((position === "before" || position === "after") && !other) throw new PeppaError("Pass `other` for before/after");
const r = position === "top" || position === "bottom" ? { to: position } : { to: position, other: await ownedTask(other!) };
await reorderBoardTask(db, ref, r as never);
const col = columnOf(ref.task.status);
const inCol = (await listTasks(db, { projectId: ref.project.id })).filter((t) => columnOf(t.status) === col);
return `${COLUMN_NAME[col]}: ${inCol.map((t) => t.key).join(", ")}`;
},
);
tool(
"archive_task",
"Archive a story (hide it from the board, the dispatcher and epic progress; its agent stops; history stays) or restore it to the bottom of the board. There is no hard delete.",
{ task: taskArg, archived: z.boolean().default(true).describe("false restores the story") },
false,
async ({ task, archived }) => {
const ref = await ownedTask(task);
const r = await archiveTask(db, ref, archived);
return archived ? `${ref.key} archived${r.stopped ? ` · ${r.stopped} session(s) stopped` : ""}` : `${ref.key} restored to the board`;
},
);
tool(
"set_dependencies",
"Set the stories a story waits for (replaces the list; [] clears it). A story is blocked until every predecessor is in review/done; the dispatcher skips blocked stories. Same project only, no cycles.",
{ task: taskArg, blocked_by: z.array(z.string()).describe("Story keys like PEP-3") },
false,
async ({ task, blocked_by }) => {
const ref = await ownedTask(task);
const list = await setDependencies(db, ref, blocked_by);
return list.length ? `${ref.key} waits for ${list.map((b) => `${b.key} [${b.status}]`).join(", ")}` : `${ref.key} has no dependencies`;
},
);
const planStory = z.object({
title: z.string().trim().min(3),
description: z.string().default(""),
depends_on: z.array(z.union([z.number().int().positive(), z.string()])).default([]).describe("1-based numbers of other stories in this plan, or keys of existing stories"),
});
const planText = (stories: PlannedStory[]) =>
stories.map((s, i) => `${i + 1}. ${s.title}${s.dependsOn.length ? ` (after ${s.dependsOn.join(", ")})` : ""}\n${s.description.replace(/^/gm, " ")}`).join("\n\n");
tool(
"plan_epic",
"Ask Peppa's planner (a short Claude run on the project's subscription, up to ~3 min) to break an epic into stories with acceptance criteria and dependencies. Returns a DRAFT — nothing is created. Show it to the user, edit as they wish, then apply_plan.",
{ project: projectArg, epic_id: z.number().int(), wishes: z.string().optional().describe("Extra guidance for the planner from the user") },
false,
async ({ project, epic_id, wishes }) => {
const p = await ownedProject(project);
const r = await planEpic(db, p, epic_id, { wishes, by: user.login });
if (!r.ok) throw new PeppaError(`Planner failed: ${r.error}`);
const json = JSON.stringify(r.draft.stories.map((s) => ({ title: s.title, description: s.description, depends_on: s.dependsOn })));
return `Draft plan for epic #${epic_id} (${r.draft.stories.length} stories; also editable at ${webUrl}/p/${p.key}/plan/${epic_id}):\n\n${planText(r.draft.stories)}\n\nTo create: apply_plan with these stories (edited if needed):\n${json}`;
},
);
tool(
"apply_plan",
"Create stories from an approved plan: in the backlog under the epic, in plan order (bottom of the board), with dependencies (depends_on: plan numbers from 1 or existing story keys).",
{ project: projectArg, epic_id: z.number().int(), stories: z.array(planStory).min(1).max(15) },
false,
async ({ project, epic_id, stories }) => {
const p = await ownedProject(project);
const created = await applyPlan(db, p, epic_id, stories.map((s) => ({ title: s.title, description: s.description, dependsOn: s.depends_on.map((d) => (typeof d === "string" ? d.toUpperCase() : d)) })));
return `Created ${created.length} stories: ${created.map((r) => r.key).join(", ")}. ${webUrl}/p/${p.key}?epic=${epic_id}`;
},
);
tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, stories, who deployed).", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const [cur, rows] = await Promise.all([currentReleases(db, p.id), listReleases(db, p.id, 15)]);

View File

@ -7,6 +7,7 @@ import {
answerQuestion,
askPm,
askPmProject,
blockedTaskIds,
enqueueTelegram,
getAutonomy,
getSetting,
@ -223,6 +224,8 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
const sessions = (await listSessions(db, { active: true })).filter((s) => s.projectId === project.id);
const working = await workingSessions(db, sessions);
const backlog = await listTasks(db, { projectId: project.id, statuses: ["backlog"] });
// PEP-42: only stories whose predecessors are in review/done; PEP-34: in board order.
const ready = await readyBacklog(db, project.id, backlog);
const state = await getIdle(db, project.id);
// Someone works or nothing is left: an open "agents are idle" question is moot.
@ -241,7 +244,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
if (a.pick === "auto") {
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
let slots = a.wipLimit - working.length;
for (const task of backlog) {
for (const task of ready) {
if (slots <= 0) break;
const ref = refOf(project, task);
try {
@ -268,12 +271,19 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
return;
}
if (!a.idlePush || working.length > 0 || !backlog.length || limited || state.questionId) return;
if (!a.idlePush || working.length > 0 || !ready.length || limited || state.questionId) return;
if (inAutonomyQuietHours(a, now)) return;
if ((state.snoozeUntil ?? 0) > now.getTime()) return;
if (state.at && now.getTime() - state.at < a.idlePushHours * 3_600_000) return;
await offerStory(db, project, backlog[0]!, now);
log(`${project.key}: idle push (${formatTaskKey(project.key, backlog[0]!.number)})`);
await offerStory(db, project, ready[0]!, now);
log(`${project.key}: idle push (${formatTaskKey(project.key, ready[0]!.number)})`);
}
/** Backlog stories that can start now: not blocked by a predecessor (PEP-42), in board order (PEP-34). */
export async function readyBacklog<T extends Task>(db: Db, projectId: number, backlog?: T[]): Promise<T[]> {
const list = backlog ?? ((await listTasks(db, { projectId, statuses: ["backlog"] })) as unknown as T[]);
const blocked = await blockedTaskIds(db, projectId);
return list.filter((t) => !blocked.has(t.id));
}
/** Sessions that hold a WIP slot: their story is being worked on (not in review). */
@ -309,8 +319,9 @@ export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise
const now = Date.now();
const text = answer.trim();
if (text.startsWith(IDLE_NEXT)) {
const backlog = await listTasks(db, { projectId: q.projectId, statuses: ["backlog"] });
const next = backlog.find((t) => t.number > ref.task.number) ?? backlog[0];
const backlog = await readyBacklog(db, q.projectId);
const at = backlog.findIndex((t) => t.id === ref.task.id);
const next = (at >= 0 ? backlog[at + 1] : backlog.find((t) => t.position > ref.task.position)) ?? backlog.find((t) => t.id !== ref.task.id);
await setIdle(db, q.projectId, { ...state, questionId: null });
if (next) await offerStory(db, ref.project, next, new Date(now));
return true;

View File

@ -1,5 +1,5 @@
// PM-side moves on the task board and review acceptance (web and Telegram use these).
import { answerQuestion, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core";
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";
@ -66,6 +66,30 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
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),

View File

@ -26,3 +26,4 @@ export * from "./workspace-sync.ts";
export * from "./rotation.ts";
export * from "./live.ts";
export * from "./gitea-events.ts";
export * from "./planner.ts";

View File

@ -0,0 +1,196 @@
// Epic planner (PEP-42): one short non-interactive Claude call that breaks an epic into
// stories with acceptance criteria and dependencies. The result is a draft (settings
// `planner.draft:<epicId>`) the PM edits and approves; approval creates the stories in the
// backlog under the epic, in plan order, with their dependencies. Tests use mock-planner.
import {
addDependency,
createTask,
deleteSetting,
getGoal,
getSetting,
listTasks,
PeppaError,
resolveTask,
setSetting,
type Goal,
type Project,
type TaskRef,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { claudePrint } from "./claude-print.ts";
/** A dependency: 1-based number of another story in the plan, or the key of an existing story. */
export type PlanDep = number | string;
export interface PlannedStory {
title: string;
description: string;
dependsOn: PlanDep[];
}
export interface PlanDraft {
epicId: number;
stories: PlannedStory[];
/** The PM's wishes passed to the planner, if any. */
wishes: string | null;
createdAt: string;
createdBy: string;
}
export const PLAN_MAX_STORIES = 15;
const draftKey = (epicId: number) => `planner.draft:${epicId}`;
export function plannerPrompt(project: Pick<Project, "key" | "name">, epic: Pick<Goal, "title" | "description">, existing: Array<{ key: string; title: string; status: string }>, wishes?: string | null): string {
return [
"Ты — планировщик софтвейр-фабрики Пеппа. Разбей эпик проекта на стори для AI-агентов.",
"Стори — одна законченная бизнес-история, которую агент делает за один PR (одна OpenSpec change):",
"не слишком мелкая (не «добавить поле»), не слишком крупная (не «сделать всё»). Обычно 3–8 стори, не больше " + PLAN_MAX_STORIES + ".",
"Для каждой стори: короткое название (до 80 символов), описание — кому и зачем, что сделать,",
"и раздел «Критерии готовности» списком; зависимости — какие стори должны быть готовы раньше.",
"Не повторяй уже существующие стори эпика; можешь зависеть от них по ключу.",
"",
`Проект: ${project.key} — ${project.name}`,
`Эпик: ${epic.title}`,
"Описание эпика:",
epic.description?.trim() || "(нет описания)",
"",
"Уже есть стори эпика:",
existing.length ? existing.map((t) => `- ${t.key} [${t.status}] ${t.title}`).join("\n") : "(нет)",
...(wishes?.trim() ? ["", "Пожелания PM:", wishes.trim()] : []),
"",
'Ответь ОДНОЙ строкой JSON без пояснений: {"stories":[{"title":"…","description":"…","depends_on":[1,"' + project.key + '-3"]}]}',
"depends_on — номера стори этого плана (с 1) или ключи существующих стори; пустой список, если зависимостей нет.",
].join("\n");
}
/** Extracts the plan from the CLI's text answer (bare JSON or JSON inside prose/code fences). */
export function parsePlannerOutput(text: string): PlannedStory[] | null {
const start = text.indexOf("{");
if (start < 0) return null;
// The first balanced JSON object that has "stories".
for (let i = start; i >= 0 && i < text.length; i = text.indexOf("{", i + 1)) {
let depth = 0;
let inStr = false;
for (let j = i; j < text.length; j++) {
const c = text[j];
if (inStr) {
if (c === "\\") j++;
else if (c === '"') inStr = false;
continue;
}
if (c === '"') inStr = true;
else if (c === "{") depth++;
else if (c === "}" && --depth === 0) {
try {
const o = JSON.parse(text.slice(i, j + 1)) as { stories?: unknown };
if (Array.isArray(o.stories)) return normalizePlan(o.stories);
} catch {}
break;
}
}
}
return null;
}
function normalizePlan(raw: unknown[]): PlannedStory[] | null {
const out: PlannedStory[] = [];
for (const r of raw.slice(0, PLAN_MAX_STORIES)) {
if (!r || typeof r !== "object") continue;
const o = r as { title?: unknown; description?: unknown; depends_on?: unknown; dependsOn?: unknown };
const title = String(o.title ?? "").trim().slice(0, 200);
if (title.length < 3) continue;
const deps = (Array.isArray(o.depends_on) ? o.depends_on : Array.isArray(o.dependsOn) ? o.dependsOn : [])
.map((d) => (typeof d === "number" ? d : /^\d+$/.test(String(d).trim()) ? Number(d) : String(d).trim().toUpperCase()))
.filter((d) => (typeof d === "number" ? Number.isInteger(d) && d > 0 : d.length > 0));
out.push({ title, description: String(o.description ?? "").trim().slice(0, 8000), dependsOn: [...new Set(deps)] });
}
return out.length ? out : null;
}
export type PlanResult = { ok: true; draft: PlanDraft } | { ok: false; error: string };
/** Runs `$PEPPA_PLANNER_BIN -p` (default `claude`) on a Claude subscription of the project's pool; saves the draft. */
export async function planEpic(db: Db, project: Project, epicId: number, o: { wishes?: string | null; by: string }): Promise<PlanResult> {
const epic = await getGoal(db, project.id, epicId);
const existing = await listTasks(db, { projectId: project.id, goalId: epic.id });
const out = await claudePrint(db, project, {
bin: process.env.PEPPA_PLANNER_BIN ?? "claude",
model: process.env.PEPPA_PLANNER_MODEL ?? "sonnet",
timeoutMs: Number(process.env.PEPPA_PLANNER_TIMEOUT_MS ?? 180_000),
prompt: plannerPrompt(project, epic, existing.map((t) => ({ key: t.key, title: t.title, status: t.status })), o.wishes),
who: "планировщик",
});
if (!out.ok) return out;
const stories = parsePlannerOutput(out.text);
if (!stories) return { ok: false, error: "планировщик ответил не по формату — попробуйте ещё раз или уточните описание эпика" };
const draft: PlanDraft = { epicId: epic.id, stories, wishes: o.wishes?.trim() || null, createdAt: new Date().toISOString(), createdBy: o.by };
await setSetting(db, draftKey(epic.id), draft);
return { ok: true, draft };
}
export async function getPlanDraft(db: Db, epicId: number): Promise<PlanDraft | null> {
return getSetting<PlanDraft>(db, draftKey(epicId));
}
export async function discardPlanDraft(db: Db, epicId: number): Promise<void> {
await deleteSetting(db, draftKey(epicId));
}
/** Plan numbers must point inside the plan and the plan must have no cycles. */
export function validatePlan(stories: PlannedStory[]): string | null {
if (!stories.length) return "в плане нет стори";
if (stories.length > PLAN_MAX_STORIES) return `не больше ${PLAN_MAX_STORIES} стори за раз`;
for (const [i, s] of stories.entries()) {
if (s.title.trim().length < 3) return `стори ${i + 1}: нужно название`;
for (const d of s.dependsOn) {
if (typeof d === "number" && (d < 1 || d > stories.length)) return `стори ${i + 1}: нет стори №${d} в плане`;
if (d === i + 1) return `стори ${i + 1} зависит от самой себя`;
}
}
const state = new Array<number>(stories.length).fill(0);
const visit = (i: number): boolean => {
if (state[i] === 1) return false;
if (state[i] === 2) return true;
state[i] = 1;
for (const d of stories[i]!.dependsOn) if (typeof d === "number" && !visit(d - 1)) return false;
state[i] = 2;
return true;
};
for (let i = 0; i < stories.length; i++) if (!visit(i)) return "цикл зависимостей в плане";
return null;
}
/**
* Creates the approved plan: stories in the backlog under the epic, in plan order, then the
* dependencies. References to existing stories are checked before anything is created.
*/
export async function applyPlan(db: Db, project: Project, epicId: number, stories: PlannedStory[]): Promise<TaskRef[]> {
const epic = await getGoal(db, project.id, epicId);
const bad = validatePlan(stories);
if (bad) throw new PeppaError(`План не принят: ${bad}`);
const existing = new Map<string, TaskRef>();
for (const s of stories) {
for (const d of s.dependsOn) {
if (typeof d !== "string" || existing.has(d)) continue;
const ref = await resolveTask(db, d, project.key).catch(() => null);
if (!ref || ref.project.id !== project.id) throw new PeppaError(`План не принят: стори ${d} нет в проекте ${project.key}`);
existing.set(d, ref);
}
}
const created: TaskRef[] = [];
for (const s of stories) created.push(await createTask(db, { projectId: project.id, goalId: epic.id, title: s.title.trim(), description: s.description.trim() || undefined }));
for (const [i, s] of stories.entries()) {
for (const d of s.dependsOn) await addDependency(db, created[i]!, typeof d === "number" ? created[d - 1]! : existing.get(d)!);
}
await discardPlanDraft(db, epic.id);
return created;
}
/** "PAY-3, 2" → deps for a planned story (numbers stay plan numbers). */
export function parseDepsInput(s: string): PlanDep[] {
return s
.split(/[\s,;]+/)
.map((x) => x.trim())
.filter(Boolean)
.map((x) => (/^\d+$/.test(x) ? Number(x) : x.toUpperCase()));
}

View File

@ -0,0 +1,3 @@
#!/usr/bin/env bash
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-planner.ts" "$@"

View File

@ -0,0 +1,44 @@
// mock-planner (PEP-42): stands in for `claude -p --output-format json` as the epic planner.
// Reads the prompt on stdin, answers with the CLI's JSON envelope whose `result` is the plan
// line. Behaviour comes from MOCK_PLANNER_SCENARIO (a JSON file):
// { "stories": [{ "title": "…", "description": "…", "depends_on": [1] }],
// "garbage": false, "fail": false, "hang": false, "prose": false }
// Without a scenario: three stories derived from the epic title, each depending on the previous.
// Every call is appended to <scenario>.log.jsonl (epic, wishes, existing stories, token, args).
import { appendFileSync, existsSync, readFileSync } from "node:fs";
interface Scenario {
stories?: Array<{ title: string; description?: string; depends_on?: Array<number | string> }>;
garbage?: boolean;
fail?: boolean;
hang?: boolean;
/** Wrap the JSON in prose and a code fence, like a chatty model. */
prose?: boolean;
}
const file = process.env.MOCK_PLANNER_SCENARIO;
const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
const prompt = readFileSync(0, "utf8");
const epic = /^Эпик: (.*)$/m.exec(prompt)?.[1] ?? "";
const wishes = /Пожелания PM:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null;
const existing = /Уже есть стори эпика:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? "";
if (file) {
appendFileSync(`${file}.log.jsonl`, JSON.stringify({ args: process.argv.slice(2), epic, wishes, existing, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
}
if (!process.argv.includes("-p")) {
console.error("mock-planner: expected -p (non-interactive print mode)");
process.exit(2);
}
if (sc.hang) await new Promise(() => setInterval(() => {}, 1000));
if (sc.fail) {
console.error("mock-planner: API Error: 529 overloaded");
process.exit(1);
}
const stories = sc.stories ?? [
{ title: `${epic}: модель данных`, description: "Схема и миграция.\n\nКритерии готовности:\n- миграция применяется", depends_on: [] },
{ title: `${epic}: API`, description: "Эндпоинты.\n\nКритерии готовности:\n- тесты зелёные", depends_on: [1] },
{ title: `${epic}: экран`, description: "UI.\n\nКритерии готовности:\n- экран открывается", depends_on: [2] },
];
const json = JSON.stringify({ stories });
const result = sc.garbage ? "Извините, я не могу составить план." : sc.prose ? `Вот план:\n\`\`\`json\n${json}\n\`\`\`\nУдачи!` : json;
process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-planner" }) + "\n");

View File

@ -99,7 +99,7 @@ describe("PM tools over MCP", () => {
await core.setProjectOwner(db, proj.id, owner.id);
const { client, call } = await mcpAs(owner);
const tools = (await client.listTools()).tools;
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]);
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "apply_plan", "archive_task", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]);
assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true);
assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false);