Merge pull request 'PEP-34/42/52: порядок и архив на доске, прогресс эпика; зависимости и планировщик эпика; палитра ⌘K' (#51) from task/pep-34-42-52 into main

This commit is contained in:
peppa-bot 2026-11-14 06:36:51 +05:00
commit 385e2607ff
57 changed files with 5441 additions and 113 deletions

View File

@ -39,6 +39,7 @@
- **Gitea → Пеппа (PEP-46)**: вебхук подписан на `GITEA_HOOK_EVENTS` (+ issues, issue_comment, pull_request_comment, pull_request_review; обновить у существующих — `peppa ci connect <KEY>`); `handleGiteaEvent` (runner/gitea-events.ts) определяет событие по форме payload (Gitea 1.22 зовёт и ревью, и комментарий `pull_request_comment`). Issue от владельца/участника (логин Gitea, `users.gitea_id > 0`) → стори в бэклоге (`tasks.gitea_issue`, идемпотентно) + комментарий-ссылка от peppa-bot; чужие игнор; `moveTask(done)` закрывает issue; разовый импорт `peppa project import-issues <KEY>` (без проверки автора). Комментарий/ревью «нужны изменения» в PR стори → агенту (живой раннер или новый, из «Ревью» — в работу); одобрения и `GITEA_BOT_LOGIN` (peppa-bot) — игнор. PR смержен руками → стори done, «готово к ревью» закрыт (`acceptTask` терпит гонку с вебхуком)
- **Превью на ревью (PEP-44)**: `reviewPreview` (core/preview.ts) — здоровый превью-стенд PR стори из `releases`, дифф `<PR>/files`, итог проверок, скриншоты, issue; в «готово к ревью» (Stop-хук, ревьюер), карточке (`components/ReviewPreview.tsx`) и `get_task`. Скриншоты снимает `peppa-deploy.sh preview` (headless Chromium в контейнере `PEPPA_SCREENSHOT_IMAGE`, сеть Traefik, base64 через stdout; страницы `deploy.screenshots`, по умолчанию `["/"]`) → `X-Peppa-Event: screenshots` → `recordScreenshots` (`$PEPPA_HOME/screenshots/<project>/`, ≤6×3 МБ, PNG) → `releases.screenshots`; веб `/api/releases/<id>/shots/<n>` (владелец/участник)
- Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены»)
- **Доска, зависимости, планировщик, палитра (PEP-34/42/52)**: порядок стори = приоритет — `tasks.position` (REAL, общий для проекта; `reorderTask` в core, `reorderBoardTask` в runner/flow.ts с колонкой; `listTasks` идёт по позиции и без архивных); архив `tasks.archived_at` (`archiveTask` останавливает агента; удаления нет); `epicProgress` — «готово/всего». Зависимости — таблица `task_deps` (core/deps.ts: блокирует, пока предшественник не в review/done и не в архиве; циклы и чужие проекты отклоняются); диспетчер PEP-24 и пуш простоя берут `readyBacklog` (runner/autonomy.ts). Планировщик — runner/planner.ts: `planEpic` (`$PEPPA_PLANNER_BIN -p`, `${PEPPA_PLANNER_MODEL:-sonnet}`, через `claudePrint`) → черновик в `settings` `planner.draft:<epicId>` → `applyPlan`; веб `/p/<KEY>/plan/<epicId>`, мок `mock-planner` (`MOCK_PLANNER_SCENARIO`). Веб-экшены — `app/(app)/board-actions.ts`. MCP PM: `reorder_task`, `archive_task`, `set_dependencies`, `plan_epic`, `apply_plan`, `blocked_by` в create/update_task. Палитра ⌘K — `components/CommandPalette.tsx` (данные `GET /api/palette` → `paletteItems` в core, ранжирование `@peppa/shared/palette` — чистый модуль для браузера), горячие клавиши через `data-hotkey-search|item|answer`, список — `lib/shortcuts.ts` и `/help/shortcuts`
- **Агент-ревьюер (PEP-26)**: настройка проекта `review_settings` (вкл/выкл, по умолчанию выкл; `max_iterations` = 2; `rules` PM) — веб «⋯ Настройки проекта → Ревьюер». Агент зовёт MCP `update_task(status: review)`, гейт PEP-57 пройден → `requestReview` (runner/reviewer.ts): ставит `code_reviews` (queued, головной SHA PR) и сразу запускает в процессе MCP, агенту — «закончи ход» (стори остаётся `in_progress`; Stop-хук не подгоняет, пока `pendingReview`). Ревью: дифф `GiteaClient.pullDiff` → `$PEPPA_REVIEW_BIN -p --output-format json --model ${PEPPA_REVIEW_MODEL:-sonnet}` (общий запуск `runner/claude-print.ts`, токен пула проекта, как триаж). `changes` → замечания агенту (`sendToSession` или новый раннер), `ok`/ошибка → стори в `review` и «готово к ревью» с резюме (если ход агента ещё идёт — его шлёт Stop-хук с той же заметкой `reviewNote`). Тот же одобренный SHA не ревьюится повторно; после `max_iterations` возвратов — к PM с последними замечаниями. Зависшие/непринятые — `reviewTick` в вачдоге (раз в минуту). Карточка и `get_task` — последнее ревью. PM, двигающий карточку сам, ревьюера не зовёт. Мок `mock-reviewer` (`MOCK_REVIEW_SCENARIO`)
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта

View File

@ -0,0 +1,122 @@
"use server";
// Board order and archive (PEP-34), story dependencies and the epic planner (PEP-42).
// Thin wrappers over core/runner with the owner/member check, like actions.ts.
import { getEpic, PeppaError, projectForUser, resolveTask, setDependencies, type TaskRef } from "@peppa/core";
import { applyPlan, archiveTask, discardPlanDraft, parseDepsInput, planEpic, reorderBoardTask, type PlanDep, type PlannedStory } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
let target = str(f, "back") || "/";
try {
target = (await fn()) || target;
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
const [path, query] = target.split("?");
const params = new URLSearchParams(query);
params.set("error", msg.slice(0, 300));
target = `${path}?${params}`;
}
revalidatePath("/", "layout");
redirect(target);
}
async function ownedTask(userId: number, key: string): Promise<TaskRef> {
const ref = await resolveTask(db, key);
await projectForUser(db, userId, ref.project.id);
return ref;
}
/** Drag within a column (before/after another card) or the card menu (top/bottom). */
export async function reorderTaskCard(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const ref = await ownedTask(user.id, str(f, "taskKey"));
const to = str(f, "to");
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
else throw new PeppaError("Неизвестное место");
});
}
/** Called from the board without a page reload (drag and drop); errors are returned. */
export async function reorderTaskInline(taskKey: string, to: "top" | "bottom" | "before" | "after", other?: string): Promise<string | null> {
const user = await requireUser();
try {
const ref = await ownedTask(user.id, taskKey);
if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, other ?? "") });
else await reorderBoardTask(db, ref, { to });
revalidatePath("/", "layout");
return null;
} catch (e) {
return e instanceof PeppaError ? e.message : (e as Error).message;
}
}
export async function archiveTaskAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const ref = await ownedTask(user.id, str(f, "taskKey"));
await archiveTask(db, ref, str(f, "archived") !== "0");
});
}
export async function setDependenciesAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const ref = await ownedTask(user.id, str(f, "taskKey"));
const keys = str(f, "blockedBy").split(/[\s,;]+/).filter(Boolean);
// "remove" drops one key from the current list; otherwise the field adds to it.
const current = (f.getAll("current") as string[]).map(String);
const remove = str(f, "remove");
await setDependencies(db, ref, remove ? current.filter((k) => k !== remove) : [...current, ...keys]);
});
}
export async function planEpicAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
if (!r.ok) throw new PeppaError(`Планировщик: ${r.error}`);
});
}
export async function applyPlanAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const epicId = Number(str(f, "epicId"));
const n = Number(str(f, "count"));
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
const kept: number[] = [];
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
if (!kept.length) throw new PeppaError("Не выбрано ни одной стори");
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
const stories: PlannedStory[] = kept.map((i) => {
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
if (typeof d !== "number") return d;
if (!renum.has(d)) throw new PeppaError(`Стори ${i} зависит от №${d}, которую вы сняли — уберите зависимость или оставьте стори`);
return renum.get(d)!;
});
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
});
await applyPlan(db, p, epicId, stories);
return `/p/${p.key}?epic=${epicId}`;
});
}
export async function discardPlanAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
await discardPlanDraft(db, epic.id);
});
}

View File

@ -6,10 +6,14 @@ import { PageHeader, Section } from "@/components/common";
const TOOLS: Array<[string, string]> = [
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке"],
["create_project", "новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
["list_epics / create_epic / update_epic", "эпики проекта (метки стори): завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"],
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, прогресс"],
["create_task / update_task", "завести стори (в Бэклог, с эпиком epic_id); поправить название, описание, эпик"],
["list_epics / create_epic / update_epic", "эпики проекта (метки стори) с прогрессом «готово/всего»: завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово, в каждой колонке — по порядку (сверху — важнее); «waits for» — стори ждёт предшественников"],
["reorder_task", "поменять место стори на доске (= приоритет): top / bottom в своей колонке, before / after другой стори; диспетчер берёт из бэклога сверху"],
["archive_task", "убрать стори в архив (пропадает с доски, диспетчера и прогресса эпика, агент останавливается, история остаётся) или вернуть (archived=false)"],
["set_dependencies", "от каких стори зависит стори (blocked_by, список заменяется; [] — убрать все); пока предшественники не в ревью/готово, диспетчер её не берёт; циклы и чужие проекты отклоняются"],
["plan_epic / apply_plan", "планировщик: разбить эпик на стори с критериями готовности и зависимостями (черновик, ничего не создаёт); после правок apply_plan создаёт стори в бэклоге под эпиком"],
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, зависимости, прогресс"],
["create_task / update_task", "завести стори (в конец Бэклога, с эпиком epic_id и зависимостями blocked_by); поправить название, описание, эпик, зависимости"],
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
["set_project_visibility", "сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий"],
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
@ -37,6 +41,10 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»" },
{ title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" },
{ title: "Выкатить в прод", say: "Что сейчас на staging в PAY? · Выкати PAY в прод", how: "list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет" },
{ title: "Разбить эпик на стори", say: "Спланируй эпик «Оплата картой» в PAY: сначала API, потом экран", how: "plan_epic → черновик со стори, критериями готовности и зависимостями; поправьте и подтвердите — apply_plan создаст стори. В вебе — «Спланировать стори эпика» над доской или в «⋯ Настройки проекта → Эпики»" },
{ title: "Приоритет", say: "Подними PAY-7 наверх бэклога · Поставь PAY-9 перед PAY-4", how: "reorder_task. Порядок в колонке = приоритет: диспетчер (автономность) берёт стори сверху. В вебе — перетащите карточку внутри колонки" },
{ title: "Зависимости", say: "PAY-8 делать только после PAY-6", how: "set_dependencies (или blocked_by в create_task / update_task). На карточке — «ждёт PAY-6», диспетчер её не возьмёт, пока PAY-6 не в ревью или готово" },
{ title: "Убрать стори", say: "PAY-5 больше не нужна", how: "archive_task — стори пропадает с доски, история остаётся; вернуть — archived=false или «Вернуть» на странице стори" },
{ title: "Закрыть эпик", say: "Эпик #5 закончен", how: "update_epic status=done — эпик пропадает из фильтра доски, стори не меняются" },
];
@ -53,7 +61,9 @@ export default async function Help() {
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="font-mono">&lt;ваш логин&gt;/&lt;slug&gt;</span>) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), <span className="font-mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий».</li>
<li><b>Стори</b> (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты <span className="font-mono">tasks.md</span> внутри change, не путать.</li>
<li><b>Эпик</b> — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP.</li>
<li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.</li>
<li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же).</li>
<li><b>Зависимости и планировщик</b> — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой.</li>
<li><b>Клавиатура</b> — <b>⌘K</b> (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — <Link href="/help/shortcuts">Горячие клавиши</Link> (или <b>?</b>).</li>
<li><b>Агент</b> — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.</li>
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.</li>
<li><b>Локальные пользователи</b> — аккаунты Пеппы без Gitea: входят по логину и паролю на странице входа, создаёт их суперадмин в разделе «Пользователи», пароль меняется в «Настройках». Их добавляют в участники по логину Пеппы; доступа к репозиторию в Gitea у них нет — код только через Пеппу, а их новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
@ -104,7 +114,7 @@ export default async function Help() {
CLI <span className="font-mono">peppa project autonomy KEY</span>). <b>Ручной</b> (по умолчанию): вы двигаете карточки и принимаете стори.{" "}
<b>С подсказками</b>: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками
«Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. <b>Автомат</b>: Пеппа сама берёт следующую стори из
бэклога (по номеру, одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент
бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент
сам делает rebase. Настройки можно комбинировать: одобрять каждый proposal, мержить сам, но закрывать вручную или «само через N
часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт
вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main.

View File

@ -0,0 +1,26 @@
import Link from "next/link";
import { ShortcutsList } from "@/components/CommandPalette";
import { PageHeader, Section } from "@/components/common";
import { Workspace } from "@/components/Workspace";
import { PALETTE_KEYS } from "@/lib/shortcuts";
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
export default function Shortcuts() {
return (
<Workspace>
<div className="max-w-3xl text-sm">
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">Помощь</Link>} title="Горячие клавиши">
Клавиши без ⌘/Ctrl работают, когда курсор не в поле ввода.
</PageHeader>
<Section title="Сочетания">
<div className="rounded-lg border bg-card px-4 py-2">
<ShortcutsList />
</div>
</Section>
<Section title="В палитре">
<p className="m-0 text-muted-foreground">{PALETTE_KEYS}. Поиск — по ключу, названию и проекту; все слова запроса должны совпасть.</p>
</Section>
</div>
</Workspace>
);
}

View File

@ -5,6 +5,7 @@ import { requireUser } from "@/lib/auth";
import { navCounts } from "@/lib/queries";
import { Sidebar } from "@/components/Sidebar";
import { AttentionBadge } from "@/components/AttentionBadge";
import { CommandPalette } from "@/components/CommandPalette";
export const dynamic = "force-dynamic";
@ -18,6 +19,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={await isSuperadmin(db, user)} />
<div className="flex min-w-0 flex-col pb-16 md:pb-0">{children}</div>
<CommandPalette />
</div>
);
}

View File

@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
import { taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@ -19,7 +19,7 @@ import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs";
import { CodeTab, EpicsPanel, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
@ -67,7 +67,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer] = await Promise.all([
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
board(p.id),
listEpics(db, p.id),
projectSessions(p.id),
@ -79,6 +79,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
listReleases(db, p.id, 15),
currentReleases(db, p.id),
getReviewSettings(db, p.id),
epicProgress(db, p.id),
blockersMap(db, p.id),
]);
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
@ -108,6 +110,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
// PEP-33: tasks.md progress of stories in work.
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
};
});
// Gitea and the working copy are read only for the open tab.
@ -159,7 +162,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</PanelSection>
<PanelSection title="Эпики" count={epics.length}>
<EpicsPanel projectId={p.id} epics={epics} back={back} />
<EpicsPanel projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
</PanelSection>
<PanelSection title="Ревьюер">
@ -347,12 +350,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
key={e.id}
href={boardHref(e.id || undefined)}
aria-current={active ? "page" : undefined}
className={cn("rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")}
className={cn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")}
>
{e.title}
{e.id > 0 && (
<span className="ml-1.5 inline-flex items-center gap-1 font-mono text-[10px] tabular-nums" title={`Готово ${progressLabel(progress.get(e.id))}`}>
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} className="w-8" />
{progressLabel(progress.get(e.id))}
</span>
)}
</a>
);
})}
{epicFilter && (
<a href={`/p/${p.key}/plan/${epicFilter.id}`} className="ml-auto text-xs text-primary">
Спланировать стори эпика →
</a>
)}
</nav>
)}
<Board cards={cards} back={back} />

View File

@ -0,0 +1,102 @@
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
import Link from "next/link";
import { notFound } from "next/navigation";
import { Sparkles } from "lucide-react";
import { getEpic, listTasks } from "@peppa/core";
import { getPlanDraft } from "@peppa/runner";
import { Hidden } from "@/components/cards";
import { Empty, Flash, PageHeader, Section } from "@/components/common";
import { PendingButton } from "@/components/PendingButton";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { projectForUserByKey } from "@/lib/queries";
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key, epic: epicParam } = await params;
const { error } = await searchParams;
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const epic = await getEpic(db, p.id, Number(epicParam)).catch(() => null);
if (!epic) notFound();
const [draft, existing] = await Promise.all([getPlanDraft(db, epic.id), listTasks(db, { projectId: p.id, goalId: epic.id })]);
const back = `/p/${p.key}/plan/${epic.id}`;
return (
<Workspace aside={null}>
<Flash error={error} />
<PageHeader
crumbs={
<>
<Link href={`/p/${p.key}`} className="text-muted-foreground hover:text-foreground">{p.name}</Link>
<span className="text-muted-foreground">/</span>
<Link href={`/p/${p.key}?epic=${epic.id}`} className="text-muted-foreground hover:text-foreground">эпик «{epic.title}»</Link>
</>
}
title={<>Спланировать эпик «{epic.title}»</>}
>
Планировщик (короткая сессия Claude на подписке пула проекта) предложит стори с критериями готовности и зависимостями. Ничего не создаётся, пока вы не утвердите план.
</PageHeader>
<Section title="Эпик">
<div className="rounded-lg border bg-card p-3 text-sm whitespace-pre-wrap">{epic.description || <span className="text-muted-foreground">Без описания — опишите эпик в «⋯ Настройки проекта → Эпики», так план будет точнее.</span>}</div>
{existing.length > 0 && (
<p className="m-0 text-sm text-muted-foreground">
Уже есть стори: {existing.map((t) => t.key).join(", ")} — планировщик их не повторит и может от них зависеть.
</p>
)}
<form action={planEpicAction} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
<Textarea name="wishes" rows={2} defaultValue={draft?.wishes ?? ""} placeholder="Пожелания планировщику (необязательно): например, «сначала API, потом экран», «без новых зависимостей»" aria-label="Пожелания планировщику" />
<PendingButton pendingText="Планировщик думает (до 3 минут)…" className="self-start">
<Sparkles />
{draft ? "Спланировать заново" : "Спланировать"}
</PendingButton>
</form>
</Section>
<Section title={draft ? `Черновик плана — ${draft.stories.length} стори` : "Черновик плана"}>
{!draft ? (
<Empty>Черновика нет. Нажмите «Спланировать».</Empty>
) : (
<>
<form action={applyPlanAction} className="flex flex-col gap-3">
<Hidden fields={{ projectId: p.id, epicId: epic.id, back, count: draft.stories.length }} />
{draft.stories.map((s, i) => {
const n = i + 1;
return (
<fieldset key={n} className="m-0 flex flex-col gap-2 rounded-lg border bg-card p-3">
<legend className="sr-only">Стори {n}</legend>
<div className="flex items-center gap-2">
<input type="checkbox" name={`keep_${n}`} defaultChecked aria-label={`Создать стори ${n}`} className="size-4 accent-primary" />
<span className="font-mono text-xs text-muted-foreground">№{n}</span>
<Input name={`title_${n}`} required minLength={3} defaultValue={s.title} aria-label={`Название стори ${n}`} className="h-8 flex-1" />
</div>
<Textarea name={`description_${n}`} rows={5} defaultValue={s.description} aria-label={`Описание стори ${n}`} />
<label className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground whitespace-nowrap">Ждёт</span>
<Input name={`deps_${n}`} defaultValue={s.dependsOn.join(", ")} placeholder={`номера плана или ключи: 1, ${p.key}-3`} aria-label={`Зависимости стори ${n}`} className="h-8" />
</label>
</fieldset>
);
})}
<p className="m-0 text-xs text-muted-foreground">Снимите галочку, чтобы не создавать стори. Стори встанут в конец бэклога в этом порядке; зависимые диспетчер не возьмёт, пока предшественники не в ревью или готово.</p>
<Button variant="default" className="self-start">Создать стори</Button>
</form>
<form action={discardPlanAction}>
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
<Button size="sm" variant="ghost">Удалить черновик</Button>
</form>
<p className="m-0 text-xs text-muted-foreground">
Черновик от {new Date(draft.createdAt).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}, {draft.createdBy}.
</p>
</>
)}
</Section>
</Workspace>
);
}

View File

@ -160,7 +160,17 @@ export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error:
}
/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
export function EpicsPanel({ projectId, epics, back }: { projectId: number; epics: Epic[]; back: string }) {
/** PEP-34: done/total of an epic as a thin bar. */
export function ProgressBar({ done, total, className }: { done: number; total: number; className?: string }) {
const pct = total ? Math.round((done / total) * 100) : 0;
return (
<span role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={done} aria-label={`Готово ${done} из ${total}`} className={`inline-block h-1 overflow-hidden rounded-full bg-muted ${className ?? "w-12"}`}>
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
</span>
);
}
export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
return (
<div className="flex flex-col gap-2 text-sm">
{epics.length === 0 && <p className="m-0 text-muted-foreground">Эпиков нет. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори.</p>}
@ -169,6 +179,8 @@ export function EpicsPanel({ projectId, epics, back }: { projectId: number; epic
<summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 select-none [&::-webkit-details-marker]:hidden">
<span className="text-muted-foreground transition-transform group-open:rotate-90">›</span>
<span className="min-w-0 flex-1 truncate">{e.title}</span>
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} />
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{progress.get(e.id)?.done ?? 0}/{progress.get(e.id)?.total ?? 0}</span>
<span className="font-mono text-[11px] text-muted-foreground">#{e.id}</span>
</summary>
<div className="flex flex-col gap-2 border-t px-3 py-2.5">
@ -178,12 +190,17 @@ export function EpicsPanel({ projectId, epics, back }: { projectId: number; epic
<Textarea name="description" rows={3} defaultValue={e.description ?? ""} placeholder="Описание для агента: зачем этот эпик" aria-label="Описание эпика" />
<Button size="xs" className="self-start">Сохранить</Button>
</form>
<form action={editEpic}>
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
<Button size="xs" variant="ghost">
<Archive />В архив
<div className="flex flex-wrap gap-2">
<Button asChild size="xs" variant="outline">
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать стори</a>
</Button>
</form>
<form action={editEpic}>
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
<Button size="xs" variant="ghost">
<Archive />В архив
</Button>
</form>
</div>
</div>
</details>
))}

View File

@ -84,7 +84,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
<form action="/runners" className="relative lg:ml-auto lg:w-64" role="search">
{filter && <input type="hidden" name="f" value={filter} />}
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input type="search" name="q" defaultValue={rawQ ?? ""} placeholder="Стори, проект, tmux…" aria-label="Поиск раннеров" className="h-8 pl-8" />
<Input type="search" name="q" data-hotkey-search defaultValue={rawQ ?? ""} placeholder="Стори, проект, tmux…" aria-label="Поиск раннеров" className="h-8 pl-8" />
</form>
</div>
{shown.length === 0 ? (

View File

@ -2,8 +2,10 @@
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
import Link from "next/link";
import { notFound } from "next/navigation";
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Pencil, Play } from "lucide-react";
import { Archive, ArchiveRestore, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
import {
blockersOf,
dependentsOf,
FINISHED_SESSION_STATUSES,
getEpic,
isSuperadmin,
@ -39,6 +41,8 @@ import { taskActivity, taskForUser } from "@/lib/queries";
import { cn } from "@/lib/utils";
import { editStoryAction, startTaskSession } from "../../actions";
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
import { Badge } from "@/components/ui/badge";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
@ -67,6 +71,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
const back = tabHref(tab);
const preview = await reviewPreview(db, ref);
const [blockers, dependents] = await Promise.all([blockersOf(db, ref), dependentsOf(db, ref)]);
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
const superadmin = await isSuperadmin(db, user);
const pool = await projectPool(db, project.id);
@ -90,6 +95,47 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const aside = (
<div className="flex flex-col gap-6">
<ReviewPreview preview={preview} />
<PanelSection title="Зависимости">
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">Стори ни от чего не зависит.</p>}
{blockers.length > 0 && (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{blockers.map((b) => (
<li key={b.id} className="flex items-center gap-2">
{b.open ? <Lock className="size-3.5 text-warn" /> : <CircleCheck className="size-3.5 text-ok" />}
<Link href={`/t/${b.key}`} className="min-w-0 flex-1 truncate">
<span className="font-mono text-xs text-primary">{b.key}</span> {b.title}
</Link>
<StatusBadge status={b.status} />
<form action={setDependenciesAction}>
<Hidden fields={{ taskKey: ref.key, back, remove: b.key }} />
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
<button type="submit" title={`Убрать зависимость от ${b.key}`} aria-label={`Убрать зависимость от ${b.key}`} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
<X className="size-3.5" />
</button>
</form>
</li>
))}
</ul>
)}
{blockers.some((b) => b.open) && <p className="m-0 text-xs text-muted-foreground">Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.</p>}
<form action={setDependenciesAction} className="flex gap-2">
<Hidden fields={{ taskKey: ref.key, back }} />
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
<Input name="blockedBy" required placeholder={`Ждёт стори: ${project.key}-3`} aria-label="Добавить зависимость" className="h-8" />
<Button size="sm" variant="outline">Добавить</Button>
</form>
{dependents.length > 0 && (
<p className="m-0 text-sm">
<span className="text-muted-foreground">Её ждут: </span>
{dependents.map((d, i) => (
<span key={d.id}>
{i > 0 && ", "}
<Link href={`/t/${d.key}`} className="font-mono text-xs">{d.key}</Link>
</span>
))}
</p>
)}
</PanelSection>
<PanelSection title="Проверки">
<Link href={tabHref("tests")} className="flex flex-wrap items-center gap-2 text-sm text-foreground hover:no-underline">
{CI_ICON[ci.state as keyof typeof CI_ICON]}
@ -142,6 +188,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} />
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">в архиве</Badge>}
</>
}
actions={
@ -160,6 +207,12 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
</a>
</Button>
)}
<form action={archiveTaskAction}>
<Hidden fields={{ taskKey: ref.key, back, archived: task.archivedAt ? "0" : "1" }} />
<Button size="sm" variant="ghost" title={task.archivedAt ? "Вернуть стори на доску (в конец)" : "Убрать с доски; агент остановится, история останется"}>
{task.archivedAt ? <><ArchiveRestore />Вернуть</> : <><Archive />В архив</>}
</Button>
</form>
</>
}
>

View File

@ -0,0 +1,12 @@
import { paletteItems } from "@peppa/core";
import { currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
export const dynamic = "force-dynamic";
/** Command palette data (PEP-52): projects, stories, runners and open questions of the user's projects. */
export async function GET() {
const user = await currentUser();
if (!user) return Response.json({ error: "unauthorized" }, { status: 401 });
return Response.json({ items: await paletteItems(db, user.id) }, { headers: { "Cache-Control": "private, no-store" } });
}

View File

@ -1,8 +1,11 @@
"use client";
import Link from "next/link";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
import { moveTaskCard } from "@/app/(app)/actions";
import { reorderTaskInline } from "@/app/(app)/board-actions";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
@ -17,6 +20,8 @@ export interface Card {
epic?: string | null;
/** tasks.md progress of a story in work (PEP-33). */
progress?: CardProgress | null;
/** PEP-42: "ждёт PEP-3" while a predecessor isn't in review/done. */
blocked?: string | null;
}
export interface CardProgress {
done: number;
@ -42,6 +47,8 @@ export function ProgressLine({ p, className }: { p: CardProgress; className?: st
);
}
const DONE_COLLAPSED = "peppa.board.doneCollapsed";
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
{ id: "backlog", title: "Бэклог", hint: "", dot: "bg-muted-foreground" },
{ id: "in_progress", title: "В работе", hint: "сюда — запустить агента", dot: "bg-info" },
@ -59,10 +66,30 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
review: { to: "done", label: "Принять ✓" },
};
/** Story board: drag a card (or use its button) to move it; the server starts/stops agents. */
/**
* Story board: drag a card to another column (or use its button) to move it — the server
* starts/stops agents; drag it onto a card of its own column to change the order (= priority
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
*/
export function Board({ cards, back }: { cards: Card[]; back: string }) {
const router = useRouter();
const [pending, start] = useTransition();
const [over, setOver] = useState<Column | null>(null);
const [error, setError] = useState<string | null>(null);
const [doneCollapsed, setDoneCollapsed] = useState(false);
useEffect(() => {
try {
setDoneCollapsed(localStorage.getItem(DONE_COLLAPSED) === "1");
} catch {}
}, []);
const toggleDone = () => {
setDoneCollapsed((v) => {
try {
localStorage.setItem(DONE_COLLAPSED, v ? "0" : "1");
} catch {}
return !v;
});
};
const move = (key: string, to: Column) => {
const f = new FormData();
f.set("taskKey", key);
@ -70,65 +97,121 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
f.set("back", back);
start(() => moveTaskCard(f));
};
const reorder = (key: string, to: "top" | "bottom" | "before" | "after", other?: string) =>
start(async () => {
setError(await reorderTaskInline(key, to, other));
router.refresh();
});
return (
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
{COLUMNS.map((c) => {
const list = cards.filter((x) => x.column === c.id);
return (
<section
key={c.id}
aria-label={c.title}
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5")}
onDragOver={(e) => {
e.preventDefault();
setOver(c.id);
}}
onDragLeave={() => setOver(null)}
onDrop={(e) => {
e.preventDefault();
setOver(null);
const key = e.dataTransfer.getData("text/plain");
const card = cards.find((x) => x.key === key);
if (card && card.column !== c.id) move(key, c.id);
}}
>
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
<span className={cn("size-1.5 rounded-full", c.dot)} />
{c.title}
<span className="ml-auto tabular-nums">{list.length}</span>
</h3>
{c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>}
{list.map((card) => (
<article
key={card.key}
draggable
onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}
className="flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
>
<Link href={`/t/${card.key}`} className="text-foreground hover:no-underline">
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
</Link>
{card.progress && <ProgressLine p={card.progress} />}
{(STATUS[card.status] || NEXT[c.id] || card.epic) && (
<div className="flex flex-wrap items-center gap-1.5">
{card.epic && (
<Badge variant="outline" className="max-w-full min-w-0" title={`Эпик: ${card.epic}`}>
<span className="truncate">{card.epic}</span>
</Badge>
)}
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>}
{NEXT[c.id] && (
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
{NEXT[c.id]!.label}
</Button>
)}
</div>
<div className="flex flex-col gap-2">
{error && (
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive">
{error}
</p>
)}
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
{COLUMNS.map((c) => {
const list = cards.filter((x) => x.column === c.id);
const collapsed = c.id === "done" && doneCollapsed;
return (
<section
key={c.id}
aria-label={c.title}
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5", collapsed && "min-h-0")}
onDragOver={(e) => {
e.preventDefault();
setOver(c.id);
}}
onDragLeave={() => setOver(null)}
onDrop={(e) => {
e.preventDefault();
setOver(null);
const key = e.dataTransfer.getData("text/plain");
const card = cards.find((x) => x.key === key);
if (!card) return;
if (card.column !== c.id) move(key, c.id);
else if (list.at(-1)?.key !== key) reorder(key, "bottom"); // empty space of its own column: to the end
}}
>
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
<span className={cn("size-1.5 rounded-full", c.dot)} />
{c.title}
<span className="ml-auto tabular-nums">{list.length}</span>
{c.id === "done" && (
<button type="button" onClick={toggleDone} aria-expanded={!collapsed} aria-label={collapsed ? "Развернуть «Готово»" : "Свернуть «Готово»"} className="-mr-1 rounded p-0.5 hover:bg-muted hover:text-foreground">
{collapsed ? <ChevronRight className="size-3.5" /> : <ChevronDown className="size-3.5" />}
</button>
)}
</article>
))}
</section>
);
})}
</h3>
{!collapsed && c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>}
{!collapsed &&
list.map((card, i) => (
<article
key={card.key}
draggable
data-task-key={card.key}
onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}
onDrop={(e) => {
const key = e.dataTransfer.getData("text/plain");
const dragged = cards.find((x) => x.key === key);
if (!dragged || dragged.column !== c.id) return; // another column: the section moves it
e.preventDefault();
e.stopPropagation();
setOver(null);
if (key === card.key) return;
const r = e.currentTarget.getBoundingClientRect();
reorder(key, e.clientY < r.top + r.height / 2 ? "before" : "after", card.key);
}}
className="group flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
>
<div className="flex items-start gap-1">
<Link href={`/t/${card.key}`} className="min-w-0 flex-1 text-foreground hover:no-underline">
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
</Link>
{list.length > 1 && (
<span className="flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 max-sm:opacity-100">
{i > 0 && (
<button type="button" title="Наверх" aria-label={`${card.key} наверх`} disabled={pending} onClick={() => reorder(card.key, "top")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
<ChevronsUp className="size-3.5" />
</button>
)}
{i < list.length - 1 && (
<button type="button" title="Вниз" aria-label={`${card.key} вниз`} disabled={pending} onClick={() => reorder(card.key, "bottom")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
<ChevronsDown className="size-3.5" />
</button>
)}
</span>
)}
</div>
{card.progress && <ProgressLine p={card.progress} />}
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
<div className="flex flex-wrap items-center gap-1.5">
{card.blocked && (
<Badge variant="warn" title="Диспетчер не возьмёт стори, пока предшественники не в ревью или готово">
<Lock className="size-3" />
{card.blocked}
</Badge>
)}
{card.epic && (
<Badge variant="outline" className="max-w-full min-w-0" title={`Эпик: ${card.epic}`}>
<span className="truncate">{card.epic}</span>
</Badge>
)}
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>}
{NEXT[c.id] && (
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
{NEXT[c.id]!.label}
</Button>
)}
</div>
)}
</article>
))}
</section>
);
})}
</div>
<p className="m-0 text-xs text-muted-foreground">Порядок в колонке — приоритет: перетащите карточку выше или ниже; диспетчер берёт стори из бэклога сверху.</p>
</div>
);
}

View File

@ -0,0 +1,290 @@
"use client";
// Command palette ⌘K and keyboard shortcuts (PEP-52). One document keydown listener: ⌘K/Ctrl+K
// toggles the palette anywhere; the rest (/, g x, j/k, a, ?) only outside text fields.
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useRef, useState, useTransition } from "react";
import { Bot, CircleHelp, FileText, FolderKanban, Keyboard, MessageCircleQuestion, Play, Search } from "lucide-react";
import { matchPalette, type PaletteItem } from "@peppa/shared/palette";
import { moveTaskCard } from "@/app/(app)/actions";
import { PALETTE_KEYS, SHORTCUTS } from "@/lib/shortcuts";
import { cn } from "@/lib/utils";
const ICON = { project: FolderKanban, story: FileText, runner: Bot, question: MessageCircleQuestion, page: CircleHelp } as const;
const GO: Record<string, string> = { h: "/", p: "/projects", r: "/runners", s: "/settings" };
const CACHE_MS = 30_000;
const typing = (t: EventTarget | null) => {
const el = t as HTMLElement | null;
return !!el && (el.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(el.tagName));
};
export function Kbd({ children }: { children: React.ReactNode }) {
return <kbd className="rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">{children}</kbd>;
}
export function ShortcutsList() {
return (
<table className="w-full border-collapse text-sm">
<tbody>
{SHORTCUTS.map((s) => (
<tr key={s.keys.join(" ") + s.what} className="border-b last:border-0">
<td className="py-1.5 pr-3 whitespace-nowrap">
{s.keys.map((k, i) => (
<span key={k}>
{i > 0 && <span className="px-0.5 text-muted-foreground">{s.keys[0]!.length > 1 ? "/" : " "}</span>}
<Kbd>{k}</Kbd>
</span>
))}
</td>
<td className="py-1.5">
{s.what}
{s.where && <span className="text-muted-foreground"> — {s.where}</span>}
</td>
</tr>
))}
</tbody>
</table>
);
}
export function CommandPalette() {
const router = useRouter();
const palette = useRef<HTMLDialogElement>(null);
const help = useRef<HTMLDialogElement>(null);
const input = useRef<HTMLInputElement>(null);
const [items, setItems] = useState<PaletteItem[]>([]);
const [loadedAt, setLoadedAt] = useState(0);
const [query, setQuery] = useState("");
const [sel, setSel] = useState(0);
const [note, setNote] = useState<string | null>(null);
const [pending, start] = useTransition();
const shown = matchPalette(items, query);
const load = useCallback(async () => {
if (Date.now() - loadedAt < CACHE_MS) return;
try {
const r = await fetch("/api/palette", { cache: "no-store" });
if (r.ok) {
setItems(((await r.json()) as { items: PaletteItem[] }).items);
setLoadedAt(Date.now());
}
} catch {}
}, [loadedAt]);
const open = useCallback(() => {
help.current?.close();
setQuery("");
setSel(0);
setNote(null);
if (!palette.current?.open) palette.current?.showModal();
input.current?.focus();
void load();
}, [load]);
const close = () => palette.current?.close();
const go = (item: PaletteItem) => {
close();
router.push(item.href);
};
const startStory = (item: PaletteItem) => {
if (!item.canStart) return;
const f = new FormData();
f.set("taskKey", item.key);
f.set("to", "in_progress");
f.set("back", item.href);
setNote(`${item.key} → В работу…`);
start(async () => {
close();
setLoadedAt(0);
await moveTaskCard(f); // redirects to the story page
});
};
// Global keys.
useEffect(() => {
let prefix: { key: string; at: number } | null = null;
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
if (palette.current?.open) close();
else open();
return;
}
if (e.metaKey || e.ctrlKey || e.altKey || typing(e.target) || palette.current?.open || help.current?.open) return;
if (prefix && prefix.key === "g" && Date.now() - prefix.at < 1000 && GO[e.key]) {
e.preventDefault();
prefix = null;
router.push(GO[e.key]!);
return;
}
prefix = null;
switch (e.key) {
case "g":
prefix = { key: "g", at: Date.now() };
return;
case "/": {
const el = document.querySelector<HTMLInputElement>("[data-hotkey-search]");
if (el) {
e.preventDefault();
el.focus();
el.select();
} else {
e.preventDefault();
open();
}
return;
}
case "?":
e.preventDefault();
help.current?.showModal();
return;
case "a": {
const el = document.querySelector<HTMLInputElement>("[data-hotkey-answer]");
if (el) {
e.preventDefault();
el.scrollIntoView({ block: "center" });
el.focus();
}
return;
}
case "j":
case "k": {
const list = [...document.querySelectorAll<HTMLAnchorElement>("[data-hotkey-item]")];
if (!list.length) return;
e.preventDefault();
const cur = list.findIndex((a) => a.getAttribute("aria-current") === "true");
const next = list[Math.min(list.length - 1, Math.max(0, cur < 0 ? 0 : cur + (e.key === "j" ? 1 : -1)))]!;
next.focus();
next.click();
return;
}
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, router]);
// Anyone can open the palette from a button: <button data-open-palette>.
useEffect(() => {
const onClick = (e: MouseEvent) => {
if ((e.target as HTMLElement | null)?.closest("[data-open-palette]")) {
e.preventDefault();
open();
}
};
document.addEventListener("click", onClick);
return () => document.removeEventListener("click", onClick);
}, [open]);
useEffect(() => {
document.getElementById(`palette-item-${sel}`)?.scrollIntoView({ block: "nearest" });
}, [sel]);
return (
<>
<dialog
ref={palette}
aria-label="Командная палитра"
className="m-auto mt-[12vh] w-[min(640px,calc(100vw-2rem))] rounded-xl border bg-popover p-0 text-popover-foreground shadow-2xl backdrop:bg-black/50"
onClick={(e) => e.target === palette.current && close()}
>
<div className="flex items-center gap-2 border-b px-3">
<Search className="size-4 text-muted-foreground" />
<input
ref={input}
value={query}
onChange={(e) => {
setQuery(e.target.value);
setSel(0);
}}
onKeyDown={(e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setSel((s) => Math.min(shown.length - 1, s + 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSel((s) => Math.max(0, s - 1));
} else if (e.key === "Enter" && shown[sel]) {
e.preventDefault();
if ((e.metaKey || e.ctrlKey) && shown[sel]!.canStart) startStory(shown[sel]!);
else go(shown[sel]!);
}
}}
placeholder="Проект, стори, раннер, вопрос или раздел…"
aria-label="Поиск"
role="combobox"
aria-expanded="true"
aria-controls="palette-list"
aria-activedescendant={shown[sel] ? `palette-item-${sel}` : undefined}
className="h-12 min-w-0 flex-1 bg-transparent text-sm outline-none"
/>
<Kbd>Esc</Kbd>
</div>
<ul id="palette-list" role="listbox" className="m-0 max-h-[52vh] list-none overflow-y-auto p-1.5">
{shown.length === 0 && <li className="px-3 py-6 text-center text-sm text-muted-foreground">{loadedAt ? "Ничего не найдено" : "Загрузка…"}</li>}
{shown.map((item, i) => {
const Icon = ICON[item.kind];
return (
<li
key={`${item.kind}:${item.key}:${item.href}`}
id={`palette-item-${i}`}
role="option"
aria-selected={i === sel}
onMouseMove={() => setSel(i)}
onClick={() => go(item)}
className={cn("flex cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-2 text-sm", i === sel && "bg-accent")}
>
<Icon className="size-4 shrink-0 text-muted-foreground" />
{item.key && <span className={cn("shrink-0 font-mono text-xs", item.kind === "page" ? "text-muted-foreground" : "text-primary")}>{item.key}</span>}
<span className="min-w-0 flex-1 truncate">{item.title}</span>
{item.hint && <span className="hidden shrink-0 text-xs text-muted-foreground sm:inline">{item.hint}</span>}
{item.canStart && (
<button
type="button"
title="В работу (⌘Enter)"
disabled={pending}
onClick={(e) => {
e.stopPropagation();
startStory(item);
}}
className="flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-xs text-muted-foreground hover:border-primary hover:text-foreground"
>
<Play className="size-3" />В работу
</button>
)}
</li>
);
})}
</ul>
<div className="flex items-center gap-2 border-t px-3 py-2 text-[11px] text-muted-foreground">
<span className="min-w-0 flex-1 truncate">{note ?? PALETTE_KEYS}</span>
<button
type="button"
onClick={() => {
close();
help.current?.showModal();
}}
className="flex items-center gap-1 hover:text-foreground"
>
<Keyboard className="size-3.5" />
Сочетания <Kbd>?</Kbd>
</button>
</div>
</dialog>
<dialog
ref={help}
aria-label="Горячие клавиши"
className="m-auto w-[min(560px,calc(100vw-2rem))] rounded-xl border bg-popover p-4 text-popover-foreground shadow-2xl backdrop:bg-black/50"
onClick={(e) => e.target === help.current && help.current?.close()}
>
<h2 className="m-0 mb-2 text-base font-semibold">Горячие клавиши</h2>
<ShortcutsList />
<p className="m-0 mt-3 text-xs text-muted-foreground">
Клавиши без ⌘ работают вне полей ввода. Список — на странице <a href="/help/shortcuts" className="text-primary">Помощь → Горячие клавиши</a>.
</p>
</dialog>
</>
);
}

View File

@ -0,0 +1,14 @@
"use client";
import { useFormStatus } from "react-dom";
import { Button } from "@/components/ui/button";
/** Submit button that shows a waiting text while its form's server action runs. */
export function PendingButton({ children, pendingText, className }: { children: React.ReactNode; pendingText: string; className?: string }) {
const { pending } = useFormStatus();
return (
<Button variant="default" disabled={pending} aria-busy={pending} className={className}>
{pending ? pendingText : children}
</Button>
);
}

View File

@ -56,6 +56,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
<Link
href={href}
scroll={false}
data-hotkey-item
aria-current={selected === true ? "true" : undefined}
className={cn(
"group grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 gap-y-0.5 rounded-md border border-transparent px-3 py-2.5 text-sm text-foreground transition-colors hover:bg-accent hover:no-underline",

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bot, FolderKanban, House, KeyRound, LifeBuoy, LogOut, Settings, Users, type LucideIcon } from "lucide-react";
import { Bot, FolderKanban, House, KeyRound, LifeBuoy, LogOut, Search, Settings, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@ -38,6 +38,17 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
<Brand />
<span className="hidden font-mono text-[11px] text-muted-foreground md:inline">фабрика</span>
</Link>
{/* PEP-52: the palette listens for clicks on [data-open-palette]. */}
<button
type="button"
data-open-palette
title="Поиск и команды (⌘K)"
className="ml-auto flex items-center gap-2 rounded-md border bg-background/60 px-2 py-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground md:mb-2 md:ml-0"
>
<Search className="size-4" />
<span className="hidden md:inline">Поиск</span>
<kbd className="ml-auto hidden rounded border bg-muted px-1 font-mono text-[10px] md:inline">⌘K</kbd>
</button>
<nav
aria-label="Разделы"
className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur md:static md:flex md:flex-col md:gap-0.5 md:border-0 md:bg-transparent md:pb-0 md:backdrop-blur-none"
@ -67,7 +78,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
);
})}
</nav>
<div className="ml-auto flex shrink-0 items-center gap-1 md:mt-auto md:ml-0 md:border-t md:pt-3">
<div className="flex shrink-0 items-center gap-1 md:mt-auto md:ml-0 md:border-t md:pt-3">
{avatarUrl && <img src={avatarUrl} alt="" width={24} height={24} className="hidden size-6 rounded-full md:block" />}
<span className="hidden min-w-0 flex-1 truncate text-sm md:block" title={login}>{login}</span>
<ThemeToggle />

View File

@ -67,7 +67,7 @@ export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }:
</div>
{q.kind !== "permission" && (
<div className="flex gap-2">
<Input name="answer" placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
<Input name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
<Button size="sm">Ответить</Button>
</div>
)}

View File

@ -34,7 +34,8 @@ export async function projectForUserByKey(userId: number, key: string): Promise<
}
export async function board(projectId: number) {
const ts = await db.select().from(tasks).where(eq(tasks.projectId, projectId)).orderBy(asc(tasks.number));
// PEP-34: board order (position), archived stories hidden.
const ts = await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number));
return { tasks: ts };
}

23
apps/web/lib/shortcuts.ts Normal file
View File

@ -0,0 +1,23 @@
// Keyboard shortcuts (PEP-52): one list for the «?» dialog and /help/shortcuts.
export interface Shortcut {
keys: string[];
what: string;
where?: string;
}
export const SHORTCUTS: Shortcut[] = [
{ keys: ["⌘K", "Ctrl+K"], what: "Командная палитра: поиск и переход к проекту, стори, раннеру, вопросу; «В работу», «Ответить»" },
{ keys: ["/"], what: "Фокус в поиск на странице", where: "списки с полем поиска (Раннеры)" },
{ keys: ["g", "h"], what: "Главная" },
{ keys: ["g", "p"], what: "Проекты" },
{ keys: ["g", "r"], what: "Раннеры" },
{ keys: ["g", "s"], what: "Настройки" },
{ keys: ["j"], what: "Следующий раннер", where: "Раннеры" },
{ keys: ["k"], what: "Предыдущий раннер", where: "Раннеры" },
{ keys: ["a"], what: "Фокус в поле ответа первого открытого вопроса", where: "Главная, стори, раннер" },
{ keys: ["?"], what: "Список сочетаний" },
{ keys: ["Esc"], what: "Закрыть палитру или окно" },
];
/** In the palette: ↑/↓ choose, Enter opens, ⌘Enter / Ctrl+Enter — «В работу» for a backlog story. */
export const PALETTE_KEYS = "↑↓ — выбор · Enter — открыть · ⌘Enter — в работу · Esc — закрыть";

View File

@ -0,0 +1,25 @@
# Design: PEP-34
## Порядок
- `position REAL`: вставка между соседями — среднее арифметическое, без перенумерации. Если
разрыв стал меньше 1e-6 — перенумеровать колонку проекта (1, 2, 3 …) в одной транзакции.
- Порядок общий для проекта, а не по колонке: карточка, ушедшая в работу и вернувшаяся,
сохраняет место. Перетаскивание считает соседей только внутри видимой колонки.
- Приоритет = порядок (как в описании стори): отдельного поля «приоритет» нет — две оси
сортировки путали бы и PM, и диспетчер.
- Новая стори: `max(position)+1` по проекту (в той же транзакции, где выдаётся номер).
## Архив, а не удаление
- Удаление каскадом стёрло бы события, вопросы и связь с инцидентами — история важнее.
`archived_at` скрывает стори везде, где идёт выбор работы (доска, диспетчер, пуш простоя,
прогресс, `list_tasks`), но `get_task`/страница стори работают.
- Архивирование останавливает активные сессии стори (`moveTask(..., "backlog")` если не
done/review) — агент не должен работать над невидимой карточкой.
## Прогресс эпика
- `epicProgress(db, projectId)` → `Map<epicId, {done, total}>` по неархивным стори.
## Веб
- Перетаскивание: drop на карточку = поставить перед ней (в нижнюю половину — после неё);
drop на пустое место своей колонки = в конец. Server action `reorderTaskCard`.
- Сворачивание «Готово»: `localStorage` `peppa.board.doneCollapsed`, по умолчанию развёрнуто.

View File

@ -0,0 +1,33 @@
# PEP-34: Доска — порядок (приоритет), прогресс эпика, архив, свёрнутое «Готово»
## Why
На доске нельзя задать, что важнее: карточки стоят по номеру, и диспетчер бэклога (PEP-24)
берёт самую старую стори. Не видно, насколько продвинулся эпик. Колонка «Готово» растёт
бесконечно, а ненужную стори нельзя убрать с доски.
## What Changes
- Порядок стори внутри колонки = приоритет: поле `tasks.position` (REAL, меньше = выше).
Перетаскивание карточки внутри колонки (над другой карточкой) ставит её между соседями;
кнопки «Наверх»/«Вниз» в меню карточки. Новая стори встаёт в конец бэклога.
- Диспетчер (PEP-24), пуш «Агенты простаивают» и `list_tasks` идут в этом порядке
(позиция, затем номер). Существующие стори получают позицию = номер (порядок не меняется).
- Прогресс эпика: «готово/всего» (готово = `done`) и полоса — в фильтре эпиков над доской и в
блоке «Эпики» настроек; MCP `list_epics` показывает то же.
- Архив стори: `tasks.archived_at`. Архивная стори пропадает с доски, из диспетчера и прогресса
эпика, её агент останавливается; вернуть можно на странице стори. Удаления нет — история
(события, вопросы, сессии) остаётся.
- Колонка «Готово» сворачивается (запоминается в браузере); в свёрнутом виде видна только
шапка со счётчиком.
- MCP PM (удалённый): `reorder_task` (top/bottom/before/after), `archive_task`
(archive/restore); агентский MCP порядок не меняет (приоритеты — решение PM), но `list_tasks`
идёт в порядке доски; `/help` описывает их.
## Capabilities
### Modified Capabilities
- `web-workspace`: порядок карточек, прогресс эпика, архив, сворачивание «Готово».
- `project-autonomy`: диспетчер берёт стори по порядку на доске.
## Impact
- Миграция: `tasks.position` (REAL NOT NULL DEFAULT 0, заполняется номером), `tasks.archived_at`.
- core/tasks.ts (`reorderTask`, `archiveTask`, `epicProgress`, сортировка `listTasks`),
runner/autonomy.ts, web Board/страница проекта/стори, MCP manager + agent, `/help`.

View File

@ -0,0 +1,10 @@
## ADDED Requirements
### Requirement: Диспетчер берёт стори по порядку доски
Диспетчер бэклога и пуш «Агенты простаивают» SHALL выбирать стори в порядке доски (позиция,
затем номер), пропуская архивные.
#### Scenario: Поднятая стори идёт первой
- **GIVEN** автономность «авто», WIP 1, бэклог PAY-1, PAY-2, PM поднял PAY-2 наверх
- **WHEN** вачдог запускает диспетчер
- **THEN** агент запускается на PAY-2

View File

@ -0,0 +1,35 @@
## ADDED Requirements
### Requirement: Порядок стори на доске
Стори проекта SHALL иметь порядок (приоритет), общий для проекта: карточки в колонке идут по
нему, PM меняет его перетаскиванием внутри колонки или командами «Наверх»/«Вниз», MCP
`reorder_task`. Новая стори встаёт в конец.
#### Scenario: Поднять стори
- **GIVEN** в бэклоге PAY-1, PAY-2, PAY-3
- **WHEN** PM перетаскивает PAY-3 на PAY-1
- **THEN** порядок бэклога — PAY-3, PAY-1, PAY-2, и он сохраняется после перезагрузки
### Requirement: Прогресс эпика
Веб и MCP SHALL показывать для каждого открытого эпика «готово/всего» по его неархивным стори
и полосу прогресса.
#### Scenario: Эпик наполовину готов
- **GIVEN** у эпика «Оплата» 4 стори, 2 из них в «Готово»
- **THEN** фильтр эпиков показывает «Оплата 2/4» с полосой на 50%
### Requirement: Архив стори
PM SHALL уметь убрать стори в архив и вернуть её. Архивная стори не видна на доске, не
считается в прогрессе, её не берёт диспетчер, её агент останавливается; история сохраняется.
#### Scenario: Убрать ненужную стори
- **GIVEN** стори PAY-5 в бэклоге
- **WHEN** PM нажимает «В архив» на странице стори
- **THEN** PAY-5 пропадает с доски, страница стори показывает «в архиве» и кнопку «Вернуть»
### Requirement: Свёрнутая колонка «Готово»
Колонку «Готово» SHALL можно свернуть до шапки со счётчиком; выбор запоминается в браузере.
#### Scenario: Свернуть
- **WHEN** PM сворачивает «Готово»
- **THEN** карточки колонки скрыты, видно «Готово 12», после перезагрузки колонка свёрнута

View File

@ -0,0 +1,19 @@
## 1. Данные
- [x] 1.1 Схема: `tasks.position`, `tasks.archived_at`; миграция с заполнением position = number
- [x] 1.2 core: `listTasks` по позиции, без архивных (флаг `includeArchived`); `createTask` в конец
- [x] 1.3 core: `reorderTask` (top/bottom/before/after, перенумерация), `archiveTask`/`restoreTask`, `epicProgress`
## 2. Диспетчер
- [x] 2.1 runner/autonomy: бэклог по позиции (уже через `listTasks`), архив стори останавливает агента
## 3. Веб
- [x] 3.1 Board: перетаскивание внутри колонки, «Наверх/Вниз», сворачивание «Готово»
- [x] 3.2 Прогресс эпика в фильтре и в блоке «Эпики»
- [x] 3.3 Архив/возврат на странице стори
## 4. MCP и справка
- [x] 4.1 `reorder_task`, `archive_task` (удалённый MCP), прогресс в `list_epics`
- [x] 4.2 `/help`
## 5. Тесты
- [x] 5.1 e2e: порядок, диспетчер берёт верхнюю, архив, прогресс

View File

@ -0,0 +1,29 @@
# Design: PEP-42
## Зависимости
- `task_deps(task_id, blocked_by_id)` — PK пары, оба FK на `tasks` с `ON DELETE CASCADE`.
- «Разблокирована» = все предшественники в `review`/`done` или в архиве. `review` — как в
постановке стори: предшественник готов к приёмке, его PR уже есть; ждать мержа значило бы
простаивать при ручном мерже.
- Проверка цикла — обход графа от нового предшественника назад к стори (графы маленькие).
- `setDependencies(ref, keys[])` заменяет весь список; `addDependency`/`removeDependency` —
точечно. События `task_updated` с `blockedBy` для журнала.
## Планировщик
- Тот же путь, что у триажа и ревьюера: `claudePrint` (пустой cwd, токен подписки пула
проекта, `--max-turns 1`). Таймаут `PEPPA_PLANNER_TIMEOUT_MS` (по умолчанию 180 с).
- Формат ответа — одна строка JSON:
`{"stories":[{"title":"…","description":"…","depends_on":[1,"PAY-3"]}]}`; номера — с 1 по
плану. Парсер берёт первый JSON-объект с `stories`, отбрасывает пустые названия, ссылки
вперёд допускает (цикл в плане — ошибка при утверждении), не больше 15 стори.
- Почему черновик, а не сразу стори: PM правит и утверждает (постановка); черновик в
`settings` — без новой таблицы, один на эпик, перезаписывается следующим запуском.
- `applyPlan` создаёт стори последовательно, затем зависимости; при ошибке зависимостей
созданные стори остаются (их видно на доске) — сообщение говорит, что не так.
- MCP `plan_epic` синхронный (до ~3 мин) — для удалённых клиентов это допустимо; веб
запускает его в server action с индикатором.
## Мок
`mock-planner` (testkit) — контракт `claude -p --output-format json`: читает промпт, отвечает
конвертом с `result` = JSON плана из `MOCK_PLANNER_SCENARIO` (`stories`, `fail`, `hang`,
`garbage`); лог вызовов в `<scenario>.log.jsonl`.

View File

@ -0,0 +1,36 @@
# PEP-42: Планировщик — разбить эпик на стори с зависимостями
## Why
PM пишет эпик (цель) и сам придумывает стори. Нужно, чтобы Пеппа предлагала разбивку со
стори, критериями готовности и зависимостями, а диспетчер не брал стори, чей предшественник
ещё не сделан.
## What Changes
- Зависимости стори: таблица `task_deps` («PAY-3 ждёт PAY-2»). Стори заблокирована, пока хоть
один предшественник не в `review`/`done` (архивный предшественник не блокирует). Циклы и
зависимость от стори другого проекта отклоняются.
- Диспетчер (PEP-24) и пуш «Агенты простаивают» пропускают заблокированные стори. PM руками
запустить может (доска не мешает), но карточка показывает «ждёт PAY-2».
- Планировщик: `planEpic` (runner/planner.ts) — один короткий `claude -p --output-format json`
(`$PEPPA_PLANNER_BIN`, модель `${PEPPA_PLANNER_MODEL:-sonnet}`) на подписке пула проекта, по
мини-промпту: эпик, его описание, уже существующие стори эпика, пожелания PM → JSON-список
стори (название, описание с «Критериями готовности», зависимости по номеру в плане или
ключу существующей стори). Ответ не по формату / ошибка — сообщение PM, ничего не создано.
- Черновик плана хранится в `settings` (`planner.draft:<epicId>`); PM правит его в вебе
(страница «Спланировать эпик»: снять галочку, поправить название/описание/зависимости) и
утверждает — стори создаются в бэклоге под эпиком в порядке плана, с зависимостями.
- Веб: на карточке — «ждёт PAY-2», на странице стори — блок «Зависимости» (добавить/убрать).
- MCP (удалённый): `plan_epic`, `apply_plan`, `set_dependencies`; `create_task`/`update_task`
принимают `blocked_by`; `get_task`/`list_tasks` показывают зависимости. Агентский MCP:
`create_task` с `blocked_by`, `get_task` с зависимостями. `/help`.
## Capabilities
### New Capabilities
- `story-planning`: зависимости стори и планировщик эпика.
### Modified Capabilities
- `project-autonomy`: диспетчер не берёт заблокированные стори.
## Impact
- Миграция: таблица `task_deps`.
- core/deps.ts, runner/planner.ts, mock-planner (testkit), web страница плана, карточка, стори,
MCP, `/help`.

View File

@ -0,0 +1,10 @@
## ADDED Requirements
### Requirement: Диспетчер ждёт предшественников
Диспетчер бэклога и пуш «Агенты простаивают» SHALL пропускать заблокированные стори и брать
следующую разблокированную по порядку доски.
#### Scenario: Сначала предшественник
- **GIVEN** автономность «авто», WIP 1, PAY-1 ждёт PAY-2, PAY-1 выше в бэклоге
- **WHEN** вачдог запускает диспетчер
- **THEN** агент запускается на PAY-2, PAY-1 остаётся в бэклоге до ревью PAY-2

View File

@ -0,0 +1,31 @@
## ADDED Requirements
### Requirement: Зависимости стори
Стори SHALL могут зависеть от других стори того же проекта. Стори заблокирована, пока хоть
один её предшественник не в «Ревью»/«Готово» и не в архиве. Циклы и межпроектные зависимости
отклоняются. Карточка и страница стори показывают, чего она ждёт.
#### Scenario: Цикл отклонён
- **GIVEN** PAY-3 ждёт PAY-2
- **WHEN** PM делает PAY-2 зависимой от PAY-3
- **THEN** ошибка «цикл зависимостей», зависимости не меняются
#### Scenario: Карточка показывает блокировку
- **GIVEN** PAY-3 ждёт PAY-2, PAY-2 в бэклоге
- **THEN** на карточке PAY-3 видно «ждёт PAY-2»
### Requirement: Планировщик эпика
По кнопке «Спланировать» (веб) или MCP `plan_epic` Пеппа SHALL одним коротким запуском
Claude на подписке пула проекта предлагать список стори эпика с описанием, критериями
готовности и зависимостями. План — черновик: PM правит и утверждает его, после чего стори
создаются в бэклоге под эпиком в порядке плана, с зависимостями. Ошибка или ответ не по
формату ничего не создают и показываются PM.
#### Scenario: Разбить эпик
- **GIVEN** эпик «Оплата картой» без стори
- **WHEN** PM нажимает «Спланировать», снимает одну стори из трёх и утверждает
- **THEN** в бэклоге две новые стори с эпиком «Оплата картой» и зависимостями из плана
#### Scenario: Планировщик ответил мусором
- **WHEN** ответ планировщика не JSON со списком стори
- **THEN** PM видит «планировщик ответил не по формату», стори не созданы

View File

@ -0,0 +1,19 @@
## 1. Зависимости
- [x] 1.1 Схема `task_deps` + миграция
- [x] 1.2 core/deps.ts: add/remove/set, цикл, `blockersOf`, `isBlocked`, `blockedMap`
- [x] 1.3 Диспетчер и пуш простоя пропускают заблокированные
## 2. Планировщик
- [x] 2.1 runner/planner.ts: промпт, парсер, `planEpic` (черновик в settings), `applyPlan`
- [x] 2.2 mock-planner (testkit)
## 3. Веб
- [x] 3.1 Страница «Спланировать эпик» (запуск, правка, утверждение)
- [x] 3.2 Карточка «ждёт …», блок «Зависимости» на странице стори
## 4. MCP и справка
- [x] 4.1 `plan_epic`, `apply_plan`, `set_dependencies`, `blocked_by` в create/update_task, вывод в get_task/list_tasks
- [x] 4.2 `/help`
## 5. Тесты
- [x] 5.1 e2e: циклы, диспетчер ждёт предшественника, планировщик на моке (успех, мусор, ошибка), applyPlan

View File

@ -0,0 +1,14 @@
# Design: PEP-52
- Палитра — клиентский компонент в раскладке `(app)`; при первом открытии грузит
`/api/palette` (проекты, неархивные стори до 500 последних, активные/последние раннеры до 50,
открытые вопросы) и кэширует на 30 с. Фильтр — на клиенте: все слова запроса должны входить
в строку (ключ, название, проект), ранжирование: совпадение с ключом, затем начало слова.
- Действие «В работу» — тот же server action `moveTaskCard`, что у доски (проверка доступа
там же); после — `router.refresh()`.
- Горячие клавиши — один `keydown` на document; игнорируются в `input/textarea/select/
[contenteditable]` и с модификаторами (кроме ⌘K). Последовательности `g x` — окно 1 с.
- `j`/`k` на «Раннерах»: ссылки раннеров помечены `data-hotkey-item`; переход — по ссылке.
- `a`: поле с `data-hotkey-answer` получает фокус.
- Список сочетаний — один массив `SHORTCUTS` в `lib/shortcuts.ts`: его рисуют и окно `?`, и
страница `/help/shortcuts` — не разъедутся.

View File

@ -0,0 +1,25 @@
# PEP-52: Командная палитра ⌘K и горячие клавиши
## Why
Чтобы перейти к стори, раннеру или ответить на вопрос, PM кликает через меню. Нужен быстрый
поиск-переход с клавиатуры и сочетания клавиш, как в привычных инструментах.
## What Changes
- Палитра ⌘K / Ctrl+K (и кнопка «Поиск ⌘K» в сайдбаре): поиск по проектам, стори, раннерам,
открытым вопросам и разделам; действия — «Открыть», «В работу» для стори из бэклога,
«Ответить» (переход к вопросу). Стрелки, Enter, Esc. Данные — `GET /api/palette`
(только проекты пользователя, `userProjectIds`).
- Горячие клавиши (вне полей ввода): `/` — фокус в поиск списка на странице (поле с
`data-hotkey-search`), `g h` / `g p` / `g r` / `g s` — Главная / Проекты / Раннеры /
Настройки, `j`/`k` — следующий/предыдущий раннер на странице раннеров, `a` — фокус в поле
ответа на странице вопроса/стори, `?` — список сочетаний.
- Страница `/help/shortcuts` со списком сочетаний (и окно по `?`).
- Без новых зависимостей: палитра — свой компонент поверх `<dialog>`.
## Capabilities
### Modified Capabilities
- `web-workspace`: палитра команд и горячие клавиши.
## Impact
- apps/web: `components/CommandPalette.tsx`, `components/Hotkeys.tsx`, `app/api/palette`,
`/help/shortcuts`, Sidebar; поле поиска с `data-hotkey-search` в списках.

View File

@ -0,0 +1,23 @@
## ADDED Requirements
### Requirement: Командная палитра
Веб SHALL открывать по ⌘K / Ctrl+K палитру поиска по проектам, стори, раннерам, открытым
вопросам и разделам пользователя с действиями «Открыть», «В работу» (стори из бэклога) и
«Ответить». Чужие проекты в палитру не попадают.
#### Scenario: Перейти к стори
- **WHEN** PM нажимает ⌘K, печатает «PAY-3» и Enter
- **THEN** открывается страница стори PAY-3
#### Scenario: Чужой проект
- **GIVEN** пользователь не участник проекта OPS
- **THEN** `/api/palette` не возвращает ни проект OPS, ни его стори
### Requirement: Горячие клавиши
Веб SHALL поддерживать сочетания: `/` — поиск в списке, `g h`/`g p`/`g r`/`g s` — разделы,
`j`/`k` — соседний раннер, `a` — поле ответа, `?` — список сочетаний; вне полей ввода. Список
сочетаний есть на странице `/help/shortcuts`.
#### Scenario: Список сочетаний
- **WHEN** PM нажимает `?` вне поля ввода
- **THEN** открывается окно со списком сочетаний, тот же список — на `/help/shortcuts`

View File

@ -0,0 +1,12 @@
## 1. Палитра
- [x] 1.1 `GET /api/palette` (доступ по проектам пользователя)
- [x] 1.2 `CommandPalette`: поиск, стрелки, Enter, действия «Открыть», «В работу», «Ответить»
- [x] 1.3 Кнопка в сайдбаре, подключение в раскладке
## 2. Горячие клавиши
- [x] 2.1 `lib/shortcuts.ts` + `Hotkeys` (/, g-последовательности, j/k, a, ?)
- [x] 2.2 Метки `data-hotkey-*` в списках, раннерах, полях ответа
- [x] 2.3 Страница `/help/shortcuts`, ссылка из `/help`
## 3. Тесты
- [x] 3.1 e2e: `/api/palette` отдаёт только свои проекты; ранжирование поиска (юнит)

View File

@ -92,3 +92,21 @@ PM SHALL получить один вопрос «Агенты простаив
#### Scenario: Закрытие по времени
- **WHEN** закрытие «через 2 часа», сообщение ревью без ответа 2 часа
- **THEN** стори принимается автоматически (PR мержится), ответ — «Принято автоматически»
### Requirement: Диспетчер берёт стори по порядку доски
Диспетчер бэклога и пуш «Агенты простаивают» SHALL выбирать стори в порядке доски (позиция,
затем номер), пропуская архивные.
#### Scenario: Поднятая стори идёт первой
- **GIVEN** автономность «авто», WIP 1, бэклог PAY-1, PAY-2, PM поднял PAY-2 наверх
- **WHEN** вачдог запускает диспетчер
- **THEN** агент запускается на PAY-2
### Requirement: Диспетчер ждёт предшественников
Диспетчер бэклога и пуш «Агенты простаивают» SHALL пропускать заблокированные стори и брать
следующую разблокированную по порядку доски.
#### Scenario: Сначала предшественник
- **GIVEN** автономность «авто», WIP 1, PAY-1 ждёт PAY-2, PAY-1 выше в бэклоге
- **WHEN** вачдог запускает диспетчер
- **THEN** агент запускается на PAY-2, PAY-1 остаётся в бэклоге до ревью PAY-2

View File

@ -0,0 +1,36 @@
# story-planning Specification
## Purpose
TBD - created by archiving change pep-42-epic-planner. Update Purpose after archive.
## Requirements
### Requirement: Зависимости стори
Стори SHALL могут зависеть от других стори того же проекта. Стори заблокирована, пока хоть
один её предшественник не в «Ревью»/«Готово» и не в архиве. Циклы и межпроектные зависимости
отклоняются. Карточка и страница стори показывают, чего она ждёт.
#### Scenario: Цикл отклонён
- **GIVEN** PAY-3 ждёт PAY-2
- **WHEN** PM делает PAY-2 зависимой от PAY-3
- **THEN** ошибка «цикл зависимостей», зависимости не меняются
#### Scenario: Карточка показывает блокировку
- **GIVEN** PAY-3 ждёт PAY-2, PAY-2 в бэклоге
- **THEN** на карточке PAY-3 видно «ждёт PAY-2»
### Requirement: Планировщик эпика
По кнопке «Спланировать» (веб) или MCP `plan_epic` Пеппа SHALL одним коротким запуском
Claude на подписке пула проекта предлагать список стори эпика с описанием, критериями
готовности и зависимостями. План — черновик: PM правит и утверждает его, после чего стори
создаются в бэклоге под эпиком в порядке плана, с зависимостями. Ошибка или ответ не по
формату ничего не создают и показываются PM.
#### Scenario: Разбить эпик
- **GIVEN** эпик «Оплата картой» без стори
- **WHEN** PM нажимает «Спланировать», снимает одну стори из трёх и утверждает
- **THEN** в бэклоге две новые стори с эпиком «Оплата картой» и зависимостями из плана
#### Scenario: Планировщик ответил мусором
- **WHEN** ответ планировщика не JSON со списком стори
- **THEN** PM видит «планировщик ответил не по формату», стори не созданы

View File

@ -310,3 +310,59 @@ SHALL показывать, на какой подписке работает с
- **GIVEN** раннер переключился с «Claude A» на «Claude B» из-за лимита
- **WHEN** PM открывает его в «Раннерах»
- **THEN** он видит подписку «Claude B» и запись «Claude A → Claude B · лимит»
### Requirement: Порядок стори на доске
Стори проекта SHALL иметь порядок (приоритет), общий для проекта: карточки в колонке идут по
нему, PM меняет его перетаскиванием внутри колонки или командами «Наверх»/«Вниз», MCP
`reorder_task`. Новая стори встаёт в конец.
#### Scenario: Поднять стори
- **GIVEN** в бэклоге PAY-1, PAY-2, PAY-3
- **WHEN** PM перетаскивает PAY-3 на PAY-1
- **THEN** порядок бэклога — PAY-3, PAY-1, PAY-2, и он сохраняется после перезагрузки
### Requirement: Прогресс эпика
Веб и MCP SHALL показывать для каждого открытого эпика «готово/всего» по его неархивным стори
и полосу прогресса.
#### Scenario: Эпик наполовину готов
- **GIVEN** у эпика «Оплата» 4 стори, 2 из них в «Готово»
- **THEN** фильтр эпиков показывает «Оплата 2/4» с полосой на 50%
### Requirement: Архив стори
PM SHALL уметь убрать стори в архив и вернуть её. Архивная стори не видна на доске, не
считается в прогрессе, её не берёт диспетчер, её агент останавливается; история сохраняется.
#### Scenario: Убрать ненужную стори
- **GIVEN** стори PAY-5 в бэклоге
- **WHEN** PM нажимает «В архив» на странице стори
- **THEN** PAY-5 пропадает с доски, страница стори показывает «в архиве» и кнопку «Вернуть»
### Requirement: Свёрнутая колонка «Готово»
Колонку «Готово» SHALL можно свернуть до шапки со счётчиком; выбор запоминается в браузере.
#### Scenario: Свернуть
- **WHEN** PM сворачивает «Готово»
- **THEN** карточки колонки скрыты, видно «Готово 12», после перезагрузки колонка свёрнута
### Requirement: Командная палитра
Веб SHALL открывать по ⌘K / Ctrl+K палитру поиска по проектам, стори, раннерам, открытым
вопросам и разделам пользователя с действиями «Открыть», «В работу» (стори из бэклога) и
«Ответить». Чужие проекты в палитру не попадают.
#### Scenario: Перейти к стори
- **WHEN** PM нажимает ⌘K, печатает «PAY-3» и Enter
- **THEN** открывается страница стори PAY-3
#### Scenario: Чужой проект
- **GIVEN** пользователь не участник проекта OPS
- **THEN** `/api/palette` не возвращает ни проект OPS, ни его стори
### Requirement: Горячие клавиши
Веб SHALL поддерживать сочетания: `/` — поиск в списке, `g h`/`g p`/`g r`/`g s` — разделы,
`j`/`k` — соседний раннер, `a` — поле ответа, `?` — список сочетаний; вне полей ввода. Список
сочетаний есть на странице `/help/shortcuts`.
#### Scenario: Список сочетаний
- **WHEN** PM нажимает `?` вне поля ввода
- **THEN** открывается окно со списком сочетаний, тот же список — на `/help/shortcuts`

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,5 @@ export * from "./autonomy.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
export * from "./preview.ts";
export * from "./deps.ts";
export * from "./palette.ts";

View File

@ -0,0 +1,67 @@
// Command palette ⌘K (PEP-52): what the signed-in user can jump to — only their own and shared
// projects (userProjectIds) — and the client-side ranking of a query against it.
import { projects, questions, sessions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, inArray, isNull } from "drizzle-orm";
import { userProjectIds } from "./users.ts";
import type { PaletteItem } from "@peppa/shared/palette";
export { matchPalette, type PaletteItem } from "@peppa/shared/palette";
const PAGES: PaletteItem[] = [
{ kind: "page", key: "g h", title: "Главная", href: "/" },
{ kind: "page", key: "g p", title: "Проекты", href: "/projects" },
{ kind: "page", key: "g r", title: "Раннеры", href: "/runners" },
{ kind: "page", key: "g s", title: "Настройки", href: "/settings" },
{ kind: "page", key: "", title: "Новый проект", href: "/projects/new" },
{ kind: "page", key: "?", title: "Горячие клавиши", href: "/help/shortcuts" },
{ kind: "page", key: "", title: "Помощь", href: "/help" },
];
const STATUS_RU: Record<string, string> = {
backlog: "бэклог",
proposing: "proposal",
awaiting_approval: "ждёт PM",
in_progress: "в работе",
review: "ревью",
done: "готово",
blocked: "блок",
};
export async function paletteItems(db: Db, userId: number): Promise<PaletteItem[]> {
const ids = await userProjectIds(db, userId);
if (!ids.length) return PAGES;
const ps = await db.select().from(projects).where(inArray(projects.id, ids));
const byId = new Map(ps.map((p) => [p.id, p]));
const ts = await db
.select({ id: tasks.id, projectId: tasks.projectId, number: tasks.number, title: tasks.title, status: tasks.status })
.from(tasks)
.where(and(inArray(tasks.projectId, ids), isNull(tasks.archivedAt)))
.orderBy(desc(tasks.updatedAt))
.limit(500);
const ss = await db
.select({ id: sessions.id, projectId: sessions.projectId, taskId: sessions.taskId, status: sessions.status })
.from(sessions)
.where(inArray(sessions.projectId, ids))
.orderBy(desc(sessions.id))
.limit(50);
const qs = await db
.select({ id: questions.id, projectId: questions.projectId, taskId: questions.taskId, text: questions.text, kind: questions.kind })
.from(questions)
.where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)))
.orderBy(desc(questions.id))
.limit(50);
const taskKey = new Map(ts.map((t) => [t.id, formatTaskKey(byId.get(t.projectId)!.key, t.number)]));
const taskTitle = new Map(ts.map((t) => [t.id, t.title]));
return [
...qs.map((q): PaletteItem => {
const k = q.taskId ? taskKey.get(q.taskId) : undefined;
return { kind: "question", key: `#${q.id}`, title: q.text.split("\n")[0]!.slice(0, 140), hint: `ответить · ${k ?? byId.get(q.projectId)!.key}`, href: k ? `/t/${k}#q-${q.id}` : `/#q-${q.id}` };
}),
...ps.map((p): PaletteItem => ({ kind: "project", key: p.key, title: p.name, hint: "проект", href: `/p/${p.key}` })),
...ts.map((t): PaletteItem => ({ kind: "story", key: taskKey.get(t.id)!, title: t.title, hint: `${byId.get(t.projectId)!.name} · ${STATUS_RU[t.status] ?? t.status}`, href: `/t/${taskKey.get(t.id)}`, canStart: t.status === "backlog" })),
...ss.map((s): PaletteItem => ({ kind: "runner", key: `#${s.id}`, title: s.taskId ? `${taskKey.get(s.taskId) ?? ""} ${taskTitle.get(s.taskId) ?? ""}`.trim() : byId.get(s.projectId)!.name, hint: `раннер · ${s.status}`, href: `/runners?id=${s.id}` })),
...PAGES,
];
}

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 = Task & { key: string }>(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

@ -3,7 +3,14 @@
"version": "0.0.0",
"private": true,
"type": "module",
"exports": { ".": "./src/index.ts" },
"scripts": { "typecheck": "tsc -p ." },
"dependencies": { "zod": "4.6.7" }
"exports": {
".": "./src/index.ts",
"./palette": "./src/palette.ts"
},
"scripts": {
"typecheck": "tsc -p ."
},
"dependencies": {
"zod": "4.6.7"
}
}

View File

@ -0,0 +1,41 @@
// Command palette (PEP-52): item shape and ranking — pure, imported by the browser bundle too.
export interface PaletteItem {
kind: "project" | "story" | "runner" | "question" | "page";
/** Shown first, monospace: PEP, PEP-3, #12. */
key: string;
title: string;
/** Context line: project name, status. */
hint?: string;
href: string;
/** A backlog story can be moved to «В работе» from the palette. */
canStart?: boolean;
}
/**
* Filters and ranks items for a query: every word must occur in "key title hint"; an exact key
* wins, then a key prefix, then a word start in the title. Empty query: questions, then the rest as is.
*/
export function matchPalette(items: PaletteItem[], query: string, limit = 30): PaletteItem[] {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
if (!words.length) return items.slice(0, limit);
const scored: Array<{ item: PaletteItem; score: number; i: number }> = [];
items.forEach((item, i) => {
const key = item.key.toLowerCase();
const title = item.title.toLowerCase();
const hay = `${key} ${title} ${(item.hint ?? "").toLowerCase()}`;
if (!words.every((w) => hay.includes(w))) return;
const q = words.join(" ");
let score = 0;
if (key === q) score += 100;
else if (key.startsWith(q)) score += 50;
if (title.startsWith(q)) score += 30;
for (const w of words) if (new RegExp(`(^|[\\s«"(])${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(title)) score += 10;
if (item.kind === "page") score -= 5;
scored.push({ item, score, i });
});
return scored
.sort((a, b) => b.score - a.score || a.i - b.i)
.slice(0, limit)
.map((x) => x.item);
}

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

@ -0,0 +1,259 @@
// PEP-34 (board order = priority, archive, epic progress) and PEP-42 (story dependencies,
// dispatcher waits for predecessors, epic planner on mock-planner).
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, describe, test } from "node:test";
import { core, db, project, runner, teardown } from "./helpers.ts";
after(teardown);
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const keysOf = async (projectId: number, status?: "backlog") => (await core.listTasks(db, { projectId, statuses: status ? [status] : undefined })).map((t) => t.key);
const refOf = (key: string) => core.resolveTask(db, key);
const projectOf = async () => {
const tp = await project({ turns: [] });
return { tp, p: await core.getProject(db, tp.key) };
};
describe("board order (PEP-34)", () => {
test("new stories go to the bottom; reorder top/bottom/before/after; order survives work and back", async () => {
const { tp, p } = await projectOf();
const b = await core.createTask(db, { projectId: p.id, title: "вторая" });
const c = await core.createTask(db, { projectId: p.id, title: "третья" });
const a = tp.taskKey;
assert.deepEqual(await keysOf(p.id), [a, b.key, c.key]);
await runner.reorderBoardTask(db, await refOf(c.key), { to: "before", other: await refOf(a) });
assert.deepEqual(await keysOf(p.id), [c.key, a, b.key]);
await runner.reorderBoardTask(db, await refOf(c.key), { to: "after", other: await refOf(a) });
assert.deepEqual(await keysOf(p.id), [a, c.key, b.key]);
await runner.reorderBoardTask(db, await refOf(b.key), { to: "top" });
assert.deepEqual(await keysOf(p.id), [b.key, a, c.key]);
await runner.reorderBoardTask(db, await refOf(b.key), { to: "bottom" });
assert.deepEqual(await keysOf(p.id), [a, c.key, b.key]);
// "top" is within the column: a story in review doesn't count for the backlog.
await core.updateTask(db, await refOf(a), { status: "review" });
await runner.reorderBoardTask(db, await refOf(b.key), { to: "top" });
assert.deepEqual(await keysOf(p.id, "backlog"), [b.key, c.key]);
await core.updateTask(db, await refOf(a), { status: "backlog" });
assert.deepEqual(await keysOf(p.id), [b.key, a, c.key], "a keeps its project-wide place; b, raised in the backlog, is above it");
});
test("tiny gaps renumber the project without losing the order", async () => {
const { tp, p } = await projectOf();
const b = await core.createTask(db, { projectId: p.id, title: "b" });
const c = await core.createTask(db, { projectId: p.id, title: "c" });
// Squeeze c between a and b many times: the midpoint halves the gap every time.
for (let i = 0; i < 30; i++) {
await runner.reorderBoardTask(db, await refOf(c.key), { to: "after", other: await refOf(tp.taskKey) });
await runner.reorderBoardTask(db, await refOf(b.key), { to: "after", other: await refOf(tp.taskKey) });
}
assert.deepEqual(await keysOf(p.id), [tp.taskKey, b.key, c.key]);
const positions = (await core.listTasks(db, { projectId: p.id })).map((t) => t.position);
assert.ok(positions[1]! - positions[0]! > 1e-7, `positions stay apart: ${positions}`);
});
test("other projects are refused", async () => {
const one = await projectOf();
const two = await projectOf();
await assert.rejects(runner.reorderBoardTask(db, await refOf(one.tp.taskKey), { to: "before", other: await refOf(two.tp.taskKey) }), /разных проектов/);
});
test("archive hides a story from the board, the dispatcher and epic progress; restore puts it at the bottom", async () => {
const { tp, p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Оплата");
const s1 = await core.createTask(db, { projectId: p.id, title: "s1", goalId: epic.id });
const s2 = await core.createTask(db, { projectId: p.id, title: "s2", goalId: epic.id });
const s3 = await core.createTask(db, { projectId: p.id, title: "s3", goalId: epic.id });
await core.updateTask(db, s1, { status: "done" });
assert.deepEqual((await core.epicProgress(db, p.id)).get(epic.id), { done: 1, total: 3 });
await runner.archiveTask(db, await refOf(s3.key), true);
assert.deepEqual(await keysOf(p.id), [tp.taskKey, s1.key, s2.key]);
assert.deepEqual((await core.epicProgress(db, p.id)).get(epic.id), { done: 1, total: 2 });
assert.equal(core.progressLabel((await core.epicProgress(db, p.id)).get(epic.id)), "1/2");
assert.ok((await refOf(s3.key)).task.archivedAt, "the story page still resolves");
assert.deepEqual((await core.listTasks(db, { projectId: p.id, includeArchived: true })).length, 4);
await assert.rejects(runner.reorderBoardTask(db, await refOf(s3.key), { to: "top" }), /в архиве/);
await runner.reorderBoardTask(db, await refOf(s2.key), { to: "top" });
await runner.archiveTask(db, await refOf(s3.key), false);
assert.equal((await keysOf(p.id)).at(-1), s3.key);
});
test("archiving a story at work stops its agent and returns it to the backlog", async () => {
const tp = await project({ turns: [[{ say: "работаю" }]] });
const sid = await tp.start();
await core.updateTask(db, await refOf(tp.taskKey), { status: "in_progress" });
const r = await runner.archiveTask(db, await refOf(tp.taskKey), true);
assert.equal(r.stopped, 1);
assert.equal((await tp.task()).status, "backlog");
assert.equal((await core.getSession(db, sid)).status, "done");
});
});
describe("dependencies (PEP-42)", () => {
test("blocked until predecessors are in review/done; no self, cycles or other projects; set replaces atomically", async () => {
const { tp, p } = await projectOf();
const a = await refOf(tp.taskKey);
const b = await core.createTask(db, { projectId: p.id, title: "b" });
const c = await core.createTask(db, { projectId: p.id, title: "c" });
await core.addDependency(db, c, b);
await core.addDependency(db, b, a);
assert.deepEqual([...(await core.blockedTaskIds(db, p.id))].sort(), [b.task.id, c.task.id].sort());
assert.equal(core.blockedLabel(await core.blockersOf(db, c)), `ждёт ${b.key}`);
assert.deepEqual((await core.dependentsOf(db, a)).map((d) => d.key), [b.key]);
await assert.rejects(core.addDependency(db, a, c), /Цикл/);
await assert.rejects(core.addDependency(db, a, a), /самой себя/);
const other = await projectOf();
await assert.rejects(core.addDependency(db, a, await refOf(other.tp.taskKey)), /другого проекта/);
// setDependencies: one bad key → nothing changes.
await assert.rejects(core.setDependencies(db, a, [c.key]), /Цикл/);
assert.deepEqual(await core.blockersOf(db, a), []);
await assert.rejects(core.setDependencies(db, c, [a.key, c.key]), /самой себя/);
assert.deepEqual((await core.blockersOf(db, c)).map((x) => x.key), [b.key], "previous list restored");
assert.deepEqual((await core.setDependencies(db, c, [String(a.task.number)])).map((x) => x.key), [a.key], "bare numbers are this project's stories");
await core.updateTask(db, a, { status: "review" });
assert.deepEqual([...(await core.blockedTaskIds(db, p.id))], [], "review unblocks b and c");
const details = await core.getTaskDetails(db, await refOf(c.key));
assert.deepEqual(details.blockers.map((x) => [x.key, x.open]), [[a.key, false]]);
});
test("an archived predecessor doesn't block", async () => {
const { tp, p } = await projectOf();
const b = await core.createTask(db, { projectId: p.id, title: "b" });
await core.addDependency(db, b, await refOf(tp.taskKey));
assert.equal((await core.blockedTaskIds(db, p.id)).has(b.task.id), true);
await runner.archiveTask(db, await refOf(tp.taskKey), true);
assert.equal((await core.blockedTaskIds(db, p.id)).has(b.task.id), false);
});
test("auto dispatcher takes the top unblocked story; a raised story goes first", async () => {
const { tp, p } = await projectOf();
const second = await core.createTask(db, { projectId: p.id, title: "предшественник" });
const third = await core.createTask(db, { projectId: p.id, title: "поднятая" });
// The first story waits for the second.
await core.addDependency(db, await refOf(tp.taskKey), second);
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.key), [second.key, third.key]);
await runner.reorderBoardTask(db, third, { to: "top" });
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.key), [third.key, second.key]);
await core.setAutonomy(db, p.id, { level: "auto", quietFrom: null, quietTo: null, wipLimit: 2 });
await runner.autonomyTick(db, { now: new Date() });
const active = (await core.listSessions(db, { active: true })).filter((s) => s.projectId === p.id);
assert.deepEqual(active.map((s) => s.taskKey).sort(), [second.key, third.key].sort(), "WIP 2: the blocked first story waits");
assert.equal((await tp.task()).status, "backlog");
for (const s of active) await runner.stopSession(db, s.id);
});
});
describe("epic planner (PEP-42)", () => {
const dir = mkdtempSync(join(tmpdir(), "peppa-planner-"));
const scenario = join(dir, "scenario.json");
process.env.PEPPA_PLANNER_BIN = join(ROOT, "packages/testkit/bin/mock-planner");
process.env.MOCK_PLANNER_SCENARIO = scenario;
const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { args: string[]; epic: string; wishes: string | null; existing: string });
test("plan → draft → edit → apply: stories in the epic, plan order, dependencies", async () => {
writeFileSync(scenario, "{}");
const { tp, p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Оплата картой", "Платёжная форма и вебхуки");
await core.updateTask(db, await refOf(tp.taskKey), { goalId: epic.id });
const r = await runner.planEpic(db, p, epic.id, { wishes: "без Stripe", by: "pm" });
assert.ok(r.ok, !r.ok ? r.error : "");
assert.equal(r.draft.stories.length, 3);
assert.deepEqual(r.draft.stories.map((s) => s.dependsOn), [[], [1], [2]]);
const call = calls().at(-1)!;
assert.equal(call.epic, "Оплата картой");
assert.equal(call.wishes, "без Stripe");
assert.match(call.existing, new RegExp(tp.taskKey), "existing stories of the epic go into the prompt");
assert.ok(call.args.includes("--model") && call.args.includes("sonnet"));
assert.deepEqual((await runner.getPlanDraft(db, epic.id))?.stories.length, 3);
// The PM drops the middle story and makes the last one wait for the first and an existing story.
const edited = [r.draft.stories[0]!, { ...r.draft.stories[2]!, dependsOn: [1, tp.taskKey] }];
const created = await runner.applyPlan(db, p, epic.id, edited);
assert.equal(created.length, 2);
assert.deepEqual((await keysOf(p.id)).slice(-2), created.map((c) => c.key), "bottom of the board, plan order");
assert.ok(created.every((c) => c.task.goalId === epic.id));
assert.deepEqual((await core.blockersOf(db, created[1]!)).map((b) => b.key), [tp.taskKey, created[0]!.key]);
assert.equal(await runner.getPlanDraft(db, epic.id), null, "the draft is gone after approval");
});
test("bad plans are refused before anything is created", async () => {
const { p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Эпик");
const before = (await keysOf(p.id)).length;
const s = (title: string, dependsOn: Array<number | string> = []) => ({ title, description: "", dependsOn });
await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", [2]), s("вторая", [1])]), /цикл/);
await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", [5])]), /нет стори №5/);
await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", ["ZZ-1"])]), /ZZ-1/);
await assert.rejects(runner.applyPlan(db, p, epic.id, []), /нет стори/);
assert.equal((await keysOf(p.id)).length, before);
});
test("prose around the JSON is fine; garbage and a failing CLI create nothing", async () => {
const { p } = await projectOf();
const epic = await core.createEpic(db, p.id, "Отчёты");
writeFileSync(scenario, JSON.stringify({ prose: true, stories: [{ title: "Отчёт по продажам", description: "{фигурные} скобки", depends_on: [] }] }));
const ok = await runner.planEpic(db, p, epic.id, { by: "pm" });
assert.ok(ok.ok);
assert.equal(ok.draft.stories[0]!.description, "{фигурные} скобки");
writeFileSync(scenario, JSON.stringify({ garbage: true }));
const bad = await runner.planEpic(db, p, epic.id, { by: "pm" });
assert.ok(!bad.ok);
assert.match(bad.error, /не по формату/);
writeFileSync(scenario, JSON.stringify({ fail: true }));
const failed = await runner.planEpic(db, p, epic.id, { by: "pm" });
assert.ok(!failed.ok);
assert.match(failed.error, /кодом 1/);
});
test("parser: depends_on as strings, caps, empty titles", () => {
const text = JSON.stringify({ stories: [{ title: "ok story", depends_on: ["2", "pep-7"] }, { title: "" }, ...Array.from({ length: 20 }, (_, i) => ({ title: `s${i} story` }))] });
const plan = runner.parsePlannerOutput(text)!;
assert.equal(plan.length, runner.PLAN_MAX_STORIES - 1, "cut to the cap, the empty title dropped");
assert.deepEqual(plan[0]!.dependsOn, [2, "PEP-7"]);
assert.equal(runner.parsePlannerOutput("нет плана"), null);
assert.deepEqual(runner.parseDepsInput("1, pep-3 ;2"), [1, "PEP-3", 2]);
});
});
describe("command palette (PEP-52)", () => {
test("only the user's projects; archived stories left out; backlog stories can start", async () => {
const pm = await core.createLocalUser(db, { login: "mock-palette-pm", password: "mock-Passw0rd-123" });
const stranger = await core.createLocalUser(db, { login: "mock-palette-x", password: "mock-Passw0rd-123" });
const mine = await core.createProject(db, { slug: "pal", key: "PAL", name: "Платежи", giteaOwner: "test", workspacePath: mkdtempSync(join(tmpdir(), "pal-")), ownerId: pm.id });
const other = await core.createProject(db, { slug: "ops", key: "OPS", name: "Опс", giteaOwner: "test", workspacePath: mkdtempSync(join(tmpdir(), "ops-")), ownerId: stranger.id });
const form = await core.createTask(db, { projectId: mine.id, title: "Форма оплаты" });
const gone = await core.createTask(db, { projectId: mine.id, title: "Ненужная" });
await core.createTask(db, { projectId: other.id, title: "Секретная" });
await runner.archiveTask(db, gone, true);
await core.askPm(db, form, { kind: "question", text: "Какой провайдер?" });
const items = await core.paletteItems(db, pm.id);
assert.ok(items.some((i) => i.kind === "project" && i.key === "PAL"));
assert.ok(!items.some((i) => i.key.startsWith("OPS") || i.title.includes("Секретная") || i.title === "Опс"), "no foreign project");
assert.ok(!items.some((i) => i.key === gone.key), "archived story hidden");
const story = items.find((i) => i.key === form.key)!;
assert.equal(story.canStart, true);
assert.equal(story.href, `/t/${form.key}`);
const q = items.find((i) => i.kind === "question")!;
assert.match(q.href, new RegExp(`^/t/${form.key}#q-\\d+$`));
assert.ok((await core.paletteItems(db, stranger.id)).every((i) => !i.key.startsWith("PAL")));
// Ranking: exact key first, then title word starts; every word must match.
assert.equal(core.matchPalette(items, form.key.toLowerCase())[0]!.key, form.key);
assert.equal(core.matchPalette(items, "форма")[0]!.key, form.key);
assert.equal(core.matchPalette(items, "форма ненужная").length, 0);
assert.equal(core.matchPalette(items, "раннеры")[0]!.href, "/runners");
});
});

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);
@ -223,7 +223,7 @@ describe("goals, task goal and project creation over MCP", () => {
const key = /Created (\S+):/.exec(t.text)![1]!;
assert.equal((await core.resolveTask(db, key)).task.goalId, a);
const listed = (await call("list_epics", { project: p.key })).text;
assert.match(listed, /Оплата картой — Приём оплат/);
assert.match(listed, /Оплата картой \(done 0\/1\) — Приём оплат/);
assert.equal((await call("list_goals", { project: p.key })).text, listed, "list_goals is an alias");
assert.match((await call("list_tasks", { project: p.key })).text, new RegExp(`${key} \\[backlog\\] \\(epic #${a}\\)`));