Merge pull request 'PEP-66: проект как в GitHub — вкладки Код, Спеки, PR; цели → эпики; задачи → стори' (#41) from task/PEP-66 into main

This commit is contained in:
peppa-bot 2026-11-14 03:34:19 +05:00
commit 6a81bb5687
47 changed files with 1427 additions and 306 deletions

View File

@ -6,7 +6,7 @@
Текущее состояние и порядок работ: `docs/HANDOFF.md`.
## Структура
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36)
- `packages/shared` — env, ключи задач (`PEP-42`)

View File

@ -162,7 +162,7 @@ export function createBot(o: BotOptions) {
if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`;
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
scheduleReconcile();
return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории задачи.";
return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори.";
}
const canAccess = (user: User, projectId: number) =>

View File

@ -2,7 +2,9 @@
import {
linkEgovIin,
createEpic,
createTask,
updateEpic,
getQuestion,
getSession,
PeppaError,
@ -78,12 +80,37 @@ export async function addTask(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (!str(f, "title")) throw new PeppaError("Нужно название задачи");
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined });
if (!str(f, "title")) throw new PeppaError("Нужно название стори");
const epic = Number(str(f, "epicId")) || undefined;
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
return `/t/${ref.key}`;
});
}
/** Epics (PEP-66): labels that group stories; stored in the goals table. */
export async function addEpic(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
});
}
export async function editEpic(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const id = Number(str(f, "epicId"));
if (str(f, "archive")) {
await updateEpic(db, p.id, id, { status: "archived" });
return;
}
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
});
}
export async function startTaskSession(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {

View File

@ -4,12 +4,12 @@ import { Workspace } from "@/components/Workspace";
import { PageHeader, Section } from "@/components/common";
const TOOLS: Array<[string, string]> = [
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько задач в каждой колонке"],
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке"],
["create_project", "новый проект: репозиторий в Gitea (приватный по умолчанию или публичный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
["list_goals / create_goal / update_goal", "цели проекта: завести, переименовать, отметить достигнутой или убрать в архив"],
["list_epics / create_epic / update_epic", "эпики проекта (метки стори): завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"],
["get_task", "карточка задачи: описание, цель, статус, OpenSpec, вопросы, прогресс"],
["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"],
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, прогресс"],
["create_task / update_task", "завести стори (в Бэклог, с эпиком epic_id); поправить название, описание, эпик"],
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"],
@ -21,19 +21,19 @@ const TOOLS: Array<[string, string]> = [
const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Создать проект", say: "Создай проект «Платежи», репо payments, ключ PAY", how: "create_project → проект с доской; агенты будут работать в этом репозитории" },
{ title: "Завести цель", say: "В PAY заведи цель «Приём оплат картой» — зачем и какой результат", how: "create_goal. Цель — верхнеуровневый результат, под ней собираются задачи" },
{ title: "Создать задачу под целью", say: "Под этой целью создай задачу «Форма оплаты» с условиями готовности: …", how: "create_task с goal_id. Пишите контекст и список «Условия готовности» — по ним работает агент" },
{ title: "Поправить задачу", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в цель #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
{ title: "Завести эпик", say: "В PAY заведи эпик «Оплата картой» — зачем и какой результат", how: "create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори" },
{ title: "Создать стори в эпике", say: "В этом эпике создай стори «Форма оплаты» с условиями готовности: …", how: "create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент" },
{ title: "Поправить стори", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
{ title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" },
{ title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит задачу в Ревью" },
{ title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит стори в Ревью" },
{ title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" },
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «Подключить отслеживание ошибок»" },
{ 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: "Отметь цель #5 достигнутой", how: "update_goal status=done" },
{ title: "Закрыть эпик", say: "Эпик #5 закончен", how: "update_epic status=done — эпик пропадает из фильтра доски, стори не меняются" },
];
export default async function Help() {
@ -45,15 +45,15 @@ export default async function Help() {
<Section title="Как устроена Пеппа">
<ul>
<li><b>Проект</b> — репозиторий в Gitea с ключом задач (например, PEP). Создаётся из веба или через MCP.</li>
<li><b>Проект</b> — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки <b>Доска · Код</b> (README, ветки, коммиты) <b>· Спеки</b> (что система умеет сейчас — <span className="font-mono">openspec/specs</span>) <b>· PR</b> (открытые PR и их проверки) <b>· Релизы · Баги · Сессии</b>; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке.</li>
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="font-mono">&lt;ваш логин&gt;/&lt;slug&gt;</span>) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), <span className="font-mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.</li>
<li><b>Цель</b> — верхнеуровневый результат («Мультипользовательская платформа»). Группирует задачи и даёт агенту контекст «зачем».</li>
<li><b>Задача</b> (PEP-12) — один результат с описанием и условиями готовности.</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> — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.</li>
<li><b>Агент</b> — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.</li>
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.</li>
<li><b>Локальные пользователи</b> — аккаунты Пеппы без Gitea: входят по логину и паролю на странице входа, создаёт их суперадмин в разделе «Пользователи», пароль меняется в «Настройках». Их добавляют в участники по логину Пеппы; доступа к репозиторию в Gitea у них нет — код только через Пеппу, а их новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
<li><b>Раннер</b> — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, задача, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).</li>
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).</li>
<li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li>
</ul>
</Section>
@ -98,10 +98,10 @@ export default async function Help() {
<p className="m-0 text-muted-foreground">
Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "}
<span className="font-mono">typecheck</span>, <span className="font-mono">test</span>, <span className="font-mono">build</span>. Команды —
в <span className="font-mono">.peppa/project.json → checks</span> (заполняет агент на первой задаче), workflow приходит из
в <span className="font-mono">.peppa/project.json → checks</span> (заполняет агент на первой стори), workflow приходит из
шаблона; в старый проект — командой <span className="font-mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в
карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без
карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
прогонов подряд Пеппа спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без
конфликтов. PR, меняющий конвейер (<span className="font-mono">.gitea/</span>, <span className="font-mono">checks</span>,{" "}
<span className="font-mono">deploy</span>), сам не мержится никогда.
</p>
@ -125,7 +125,7 @@ export default async function Help() {
<p className="m-0 text-muted-foreground">
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
проекта: сообщением, задачей или с кнопками «В бэклог / В работу / Игнорировать».
проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать».
</p>
</Section>
</div>

View File

@ -1,16 +1,16 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, platformReleaseOffers, type Release } from "@peppa/runner";
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
import { getIncidentSettings, listEpics, listErrorSources, listIncidents, listMembers, listSpecs, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
import { Hidden, SessionCard } from "@/components/cards";
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentsSection } from "@/components/Incidents";
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
import { SettingsDialog } from "@/components/SettingsDialog";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
@ -18,6 +18,7 @@ import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
deploying: { label: "выкатывается", tone: "info" },
@ -29,6 +30,9 @@ const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" |
const TABS = [
{ id: "board", label: "Доска" },
{ id: "code", label: "Код" },
{ id: "specs", label: "Спеки" },
{ id: "pulls", label: "PR" },
{ id: "releases", label: "Релизы" },
{ id: "bugs", label: "Баги" },
{ id: "sessions", label: "Сессии" },
@ -54,15 +58,16 @@ function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
);
}
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string }> }) {
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string }> }) {
const user = await requireUser();
const { key } = await params;
const { error, created, tab: tabParam } = await searchParams;
const { error, created, tab: tabParam, epic: epicParam } = await searchParams;
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const [{ tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([
board(p.id),
listEpics(db, p.id),
projectSessions(p.id),
listMembers(db, p),
describeRepo(db, p),
@ -80,13 +85,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
const missingAccess = team.members.some((m) => noRepoAccess(m.login));
const isOwner = p.ownerId === user.id;
const back = tab === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${tab}`;
const cards: Card[] = tasks.map((t) => ({
key: `${p.key}-${t.number}`,
title: t.title,
status: t.status,
column: columnOf(t.status),
}));
// Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
const cards: Card[] = tasks
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
.map((t) => ({
key: `${p.key}-${t.number}`,
title: t.title,
status: t.status,
column: columnOf(t.status),
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
}));
// Gitea and the working copy are read only for the open tab.
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
const specs = tab === "specs" ? listSpecs(p) : [];
const aside = (
<div className="flex flex-col gap-6">
@ -115,6 +130,21 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</Button>
</PanelSection>
<PanelSection title="Эпики" count={epics.length}>
<EpicsPanel projectId={p.id} epics={epics} back={back} />
</PanelSection>
<PanelSection title="Баги">
<IncidentSettingsPanel
projectId={p.id}
back={back}
isOwner={isOwner}
settings={incidentSettings}
sources={sources}
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
/>
</PanelSection>
<PanelSection title="Участники" count={team.members.length + 1}>
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
<li className="flex flex-col rounded-md px-2 py-1.5">
@ -173,6 +203,14 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<Hidden fields={{ projectId: p.id, back }} />
<Input name="title" required placeholder="Что сделать" aria-label="Название стори" />
<Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label="Описание стори" />
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label="Эпик">
<option value="">Без эпика</option>
{epics.map((e) => (
<option key={e.id} value={e.id}>
{e.title}
</option>
))}
</NativeSelect>
<Button variant="default" size="sm" className="self-start">Создать стори</Button>
</form>
);
@ -226,7 +264,35 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
))}
</nav>
{tab === "board" && <Board cards={cards} back={back} />}
{tab === "board" && (
<>
{epics.length > 0 && (
<nav aria-label="Фильтр по эпику" className="mb-3 flex flex-wrap items-center gap-1.5 text-sm">
<span className="text-xs text-muted-foreground">Эпик:</span>
{[{ id: 0, title: "все" }, ...epics].map((e) => {
const active = (epicFilter?.id ?? 0) === e.id;
return (
<a
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")}
>
{e.title}
</a>
);
})}
</nav>
)}
<Board cards={cards} back={back} />
</>
)}
{tab === "code" && code && <CodeTab code={code} />}
{tab === "specs" && <SpecsTab specs={specs} />}
{tab === "pulls" && pulls && <PullsTab pulls={pulls.pulls} error={pulls.error} repoUrl={repo.url} />}
{tab === "releases" && (
<Section title="Релизы">
@ -280,17 +346,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
)}
{tab === "bugs" && (
<IncidentsSection
projectId={p.id}
projectKey={p.key}
back={back}
isOwner={isOwner}
settings={incidentSettings}
sources={sources}
incidents={incidents}
taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))}
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
/>
<IncidentsSection projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
)}
{tab === "sessions" && (

View File

@ -0,0 +1,199 @@
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
import { Archive, ExternalLink, GitBranch, GitPullRequest } from "lucide-react";
import type { Epic, SpecSummary } from "@peppa/core";
import type { OpenPull, RepoOverview } from "@peppa/runner";
import { addEpic, editEpic } from "../../actions";
import { Hidden } from "@/components/cards";
import { Disclosure, Empty, Key, Section, StatusBadge } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" }) : "—");
function plural(n: number, one: string, few: string, many: string) {
const m10 = n % 10;
const m100 = n % 100;
return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many;
}
export function CodeTab({ code }: { code: RepoOverview }) {
const gitea = (
<Button asChild size="sm">
<a href={code.url}>
Открыть в Gitea <ExternalLink />
</a>
</Button>
);
if (code.error) {
return (
<Section title="Код" actions={gitea}>
<Empty>{code.error}. Репозиторий: <a href={code.url} className="text-primary">{code.url}</a></Empty>
</Section>
);
}
return (
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
<Section title={<>README {code.readme && <span className="ml-1 font-mono text-xs font-normal text-muted-foreground">{code.readme.path}</span>}</>} actions={gitea}>
{code.readme ? (
<pre className="m-0 max-h-[40em] overflow-auto rounded-lg border bg-card p-4 font-mono text-xs leading-relaxed whitespace-pre-wrap">{code.readme.text}</pre>
) : (
<Empty>{code.defaultBranch ? `В ветке ${code.defaultBranch} нет README.` : "Репозиторий пуст."}</Empty>
)}
</Section>
<div className="flex flex-col gap-6">
<Section title="Ветки" count={code.branches.length}>
{code.branches.length === 0 ? (
<Empty>Веток нет.</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{code.branches.map((b) => (
<li key={b.name} className="flex min-w-0 items-center gap-2 rounded-md px-2 py-1">
<GitBranch className="size-3.5 shrink-0 text-muted-foreground" />
<a href={`${code.url}/src/branch/${b.name.split("/").map(encodeURIComponent).join("/")}`} className="truncate font-mono text-xs text-primary">
{b.name}
</a>
{b.name === code.defaultBranch && <Badge variant="muted">по умолчанию</Badge>}
<span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{b.sha.slice(0, 7)}</span>
</li>
))}
</ul>
)}
</Section>
<Section title={`Коммиты ${code.defaultBranch ?? ""}`}>
{code.commits.length === 0 ? (
<Empty>Коммитов нет.</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-2 p-0 text-sm">
{code.commits.map((c) => (
<li key={c.sha} className="flex flex-col gap-0.5 rounded-md border bg-card px-3 py-2">
<span className="[overflow-wrap:anywhere]">{c.message}</span>
<span className="flex flex-wrap gap-x-2 text-xs text-muted-foreground">
<a href={c.url} className="font-mono text-primary">{c.sha.slice(0, 7)}</a>
{c.author} · {when(c.date)}
</span>
</li>
))}
</ul>
)}
</Section>
</div>
</div>
);
}
export function SpecsTab({ specs }: { specs: SpecSummary[] }) {
return (
<Section title="Спеки" count={specs.length}>
<p className="m-0 text-sm text-muted-foreground">Что система умеет сейчас: требования OpenSpec из рабочей копии (openspec/specs). Обновляются, когда стори архивирует свой change.</p>
{specs.length === 0 ? (
<Empty>Спек ещё нет — они появляются после archive первого change.</Empty>
) : (
specs.map((s) => (
<Disclosure
key={s.name}
summary={
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="flex items-center gap-2">
<span className="font-mono">{s.name}</span>
<Badge variant="muted">
{s.requirements} {plural(s.requirements, "требование", "требования", "требований")}
</Badge>
</span>
{s.purpose && <span className="text-xs font-normal text-muted-foreground">{s.purpose.split("\n")[0]}</span>}
</span>
}
>
<pre className="m-0 max-h-[40em] overflow-auto font-mono text-xs leading-relaxed whitespace-pre-wrap">{s.text}</pre>
</Disclosure>
))
)}
</Section>
);
}
const CI_TONE = { success: "ok", failure: "danger", pending: "info", none: "muted", not_configured: "muted" } as const;
export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error: string | null; repoUrl: string }) {
return (
<Section
title="Открытые PR"
count={pulls.length}
actions={
<Button asChild size="sm">
<a href={`${repoUrl}/pulls`}>
Все PR в Gitea <ExternalLink />
</a>
</Button>
}
>
{error ? (
<Empty>{error}.</Empty>
) : pulls.length === 0 ? (
<Empty>Открытых PR нет.</Empty>
) : (
pulls.map((p) => (
<article key={p.number} className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
<div className="flex items-start gap-2">
<GitPullRequest className="mt-0.5 size-4 shrink-0 text-ok" />
<a href={p.url} className="min-w-0 flex-1 text-foreground [overflow-wrap:anywhere]">
<span className="font-mono text-xs text-muted-foreground">#{p.number}</span> {p.title}
</a>
</div>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<span className="font-mono">{p.branch}</span>
{p.task ? (
<>
· <Key href={`/t/${p.task.key}`}>{p.task.key}</Key>
<StatusBadge status={p.task.status} />
<Badge variant={CI_TONE[p.task.ci.state]}>{p.task.ci.label}</Badge>
</>
) : (
<span>· не стори Пеппы</span>
)}
</div>
</article>
))
)}
</Section>
);
}
/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
export function EpicsPanel({ projectId, epics, back }: { projectId: number; epics: Epic[]; back: string }) {
return (
<div className="flex flex-col gap-2 text-sm">
{epics.length === 0 && <p className="m-0 text-muted-foreground">Эпиков нет. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори.</p>}
{epics.map((e) => (
<details key={e.id} className="group rounded-md border bg-card">
<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>
<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">
<form action={editEpic} className="flex flex-col gap-2">
<Hidden fields={{ projectId, epicId: e.id, back }} />
<Input name="title" required minLength={2} defaultValue={e.title} aria-label="Название эпика" className="h-8" />
<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 />В архив
</Button>
</form>
</div>
</details>
))}
<form action={addEpic} className="flex flex-col gap-2">
<Hidden fields={{ projectId, back }} />
<div className="flex gap-2">
<Input name="title" required minLength={2} placeholder="Новый эпик" aria-label="Название нового эпика" className="h-8" />
<Button size="sm">Добавить</Button>
</div>
</form>
</div>
);
}

View File

@ -51,7 +51,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
<Input name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" className="font-mono" />
</Label>
<Label className="w-32">
Ключ задач
Ключ стори
<Input name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="font-mono uppercase" />
</Label>
</div>

View File

@ -26,7 +26,7 @@ export default async function Projects({ searchParams }: { searchParams: Promise
</Button>
}
>
Свои и общие проекты: доска задач, релизы, ошибки из прода, участники.
Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.
</PageHeader>
<ProjectList projects={projects} userId={user.id} />
</Workspace>

View File

@ -59,7 +59,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
<Workspace aside={aside} asideWideOnly={!id}>
<AutoRefresh />
<Flash error={error} />
<PageHeader title="Раннеры">Агенты в tmux по задачам твоих и общих проектов: кто ждёт тебя, кто работает, что готово.</PageHeader>
<PageHeader title="Раннеры">Агенты в tmux по стори твоих и общих проектов: кто ждёт тебя, кто работает, что готово.</PageHeader>
<div className="mb-3 flex flex-col gap-3 lg:flex-row lg:items-center">
<nav className="flex flex-wrap gap-1.5" aria-label="Фильтр раннеров">
{FILTERS.map((x) => {
@ -84,11 +84,11 @@ 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" defaultValue={rawQ ?? ""} placeholder="Стори, проект, tmux…" aria-label="Поиск раннеров" className="h-8 pl-8" />
</form>
</div>
{shown.length === 0 ? (
<Empty>{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</Empty>
<Empty>{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси стори в «В работе» на доске проекта."}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5">
{shown.map((s) => (

View File

@ -1,7 +1,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react";
import { taskCiSummary } from "@peppa/core";
import { getEpic, taskCiSummary } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Hidden, QuestionCard, SessionCard } from "@/components/cards";
@ -16,7 +16,7 @@ import { startTaskSession } from "../../actions";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key } = await params;
const { error } = await searchParams;
@ -26,6 +26,7 @@ export default async function TaskPage({ params, searchParams }: { params: Promi
const { questions, sessions, events } = await taskActivity(task.id);
const artifacts = openspecArtifacts(project, task.openspecChange);
const ci = await taskCiSummary(db, ref);
const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null;
const back = `/t/${ref.key}`;
const aside = (
@ -77,6 +78,14 @@ export default async function TaskPage({ params, searchParams }: { params: Promi
crumbs={
<>
<Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link>
{epic && (
<>
<span className="text-muted-foreground">/</span>
<Link href={`/p/${project.key}?epic=${epic.id}`} title="Эпик" className="text-muted-foreground hover:text-foreground">
эпик «{epic.title}»
</Link>
</>
)}
</>
}
title={

View File

@ -6,7 +6,7 @@ import { cn } from "@/lib/utils";
import { THEME_COOKIE } from "@/lib/theme";
import "./app.css";
export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, задачи и агенты" };
export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты" };
export default async function RootLayout({ children }: { children: ReactNode }) {
// Dark by default; the cookie is read on the server so a light choice renders without a dark flash.

View File

@ -16,7 +16,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
<main className="grid min-h-dvh place-items-center px-4">
<div className="flex w-full max-w-sm flex-col items-center gap-5 text-center">
<Brand large />
<p className="m-0 text-sm text-muted-foreground">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p>
<p className="m-0 text-sm text-muted-foreground">Софтвейр-фабрика: проекты в Gitea, стори по OpenSpec, агенты Claude Code и Codex.</p>
<Flash error={error} />
<Button asChild variant="default" size="lg" className="w-full">
<a href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a>

View File

@ -43,8 +43,8 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>.
</p>
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-sm">
<li>видеть ваши проекты, цели, задачи и вопросы агентов;</li>
<li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li>
<li>видеть ваши проекты, эпики, стори и вопросы агентов;</li>
<li>создавать стори и двигать карточки — перенос в «В работе» запускает агента;</li>
<li>отвечать на вопросы агентов и принимать ревью.</li>
</ul>
<p className="m-0 text-xs text-muted-foreground">Отозвать доступ можно в «Настройки → Подключённые приложения».</p>

View File

@ -13,6 +13,8 @@ export interface Card {
title: string;
status: string;
column: Column;
/** Epic label (PEP-66), if the story has an open epic. */
epic?: string | null;
}
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
@ -32,7 +34,7 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
review: { to: "done", label: "Принять ✓" },
};
/** Task board: drag a card (or use its button) to move it; the server starts/stops agents. */
/** Story board: drag a card (or use its button) to move it; the server starts/stops agents. */
export function Board({ cards, back }: { cards: Card[]; back: string }) {
const [pending, start] = useTransition();
const [over, setOver] = useState<Column | null>(null);
@ -81,8 +83,13 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
<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>
{(STATUS[card.status] || NEXT[c.id]) && (
{(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)}>

View File

@ -1,4 +1,4 @@
// Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list.
// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
@ -14,22 +14,55 @@ function Code({ children }: { children: React.ReactNode }) {
return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs">{children}</code>;
}
/** Tab «Баги»: the incidents list. Settings live in «⋯ Настройки проекта» (PEP-66). */
export function IncidentsSection(props: {
projectId: number;
projectKey: string;
back: string;
settings: IncidentSettings | null;
incidents: Incident[];
taskKeys: Map<number, string>;
}) {
const { settings: s } = props;
if (!s) {
return (
<Section title="Баги">
<p className="m-0 text-sm text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта.</p>
<Empty>Отслеживание ошибок не подключено — подключает владелец в «⋯ Настройки проекта».</Empty>
</Section>
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
<Section title="Баги" count={active.length} actions={<span className="text-xs text-muted-foreground">политика: {POLICY_RU[s.policy]}</span>}>
{active.length === 0 ? <Empty>Открытых ошибок нет.</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
{rest.length > 0 && (
<Disclosure summary={`Исправленные и игнорируемые (${rest.length})`}>
<div className="flex flex-col gap-2">
{rest.map((i) => (
<IncidentCard key={i.id} i={i} {...props} />
))}
</div>
</Disclosure>
)}
</Section>
);
}
/** «⋯ Настройки проекта» → Баги: connect Bugsink, DSN, webhook, incident policy (PEP-66). */
export function IncidentSettingsPanel(props: {
projectId: number;
back: string;
isOwner: boolean;
settings: IncidentSettings | null;
sources: ErrorSource[];
incidents: Incident[];
taskKeys: Map<number, string>;
webhookUrl: string | null;
}) {
const { projectId, back, settings: s } = props;
if (!s) {
return (
<Section title="Ошибки">
<p className="m-0 text-sm text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.</p>
<div className="flex flex-col gap-2 text-sm">
<p className="m-0 text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят во вкладку «Баги» и становятся стори по политике проекта.</p>
{props.isOwner ? (
<form action={connectErrorTrackingAction}>
<Hidden fields={{ projectId, back }} />
@ -41,72 +74,55 @@ export function IncidentsSection(props: {
) : (
<Empty>Не подключено — подключает владелец проекта.</Empty>
)}
</Section>
</div>
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
<Section title="Ошибки" count={active.length} actions={<span className="text-xs text-muted-foreground">политика: {POLICY_RU[s.policy]}</span>}>
{active.length === 0 ? <Empty>Открытых ошибок нет.</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
{rest.length > 0 && (
<Disclosure summary={`Исправленные и игнорируемые (${rest.length})`}>
<div className="flex flex-col gap-2">
{rest.map((i) => (
<IncidentCard key={i.id} i={i} {...props} />
))}
</div>
</Disclosure>
)}
<Disclosure summary="Настройки ошибок">
<div className="flex flex-col gap-3 text-sm">
{props.sources.map((src) => (
<div key={src.id} className="flex flex-col gap-1">
<span className="font-medium">DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</span>
<Code>{src.dsn}</Code>
</div>
))}
<p className="m-0 text-muted-foreground">
В коде: <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> из окружения, <code className="font-mono">release</code> = SHA деплоя,{" "}
<code className="font-mono">environment</code> = prod, <code className="font-mono">sendDefaultPii: false</code>.
</p>
{!s.webhookAuto && props.webhookUrl && (
<div className="flex flex-col gap-1">
<span><b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:</span>
<Code>{props.webhookUrl}</Code>
<span className="text-muted-foreground">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
</div>
)}
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
<Hidden fields={{ projectId, back }} />
<Label>
Политика инцидентов
<NativeSelect name="policy" defaultValue={s.policy} aria-label="Политика инцидентов">
{incidentPolicies.map((p) => (
<option key={p} value={p}>
{p} — {POLICY_RU[p]}
</option>
))}
</NativeSelect>
</Label>
<Textarea
name="triagePrompt"
rows={3}
defaultValue={s.triagePrompt ?? ""}
aria-label="Как принимать решение (для триажёра)"
placeholder="Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»"
/>
<div className="flex gap-2">
<Input name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" />
<Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Задач в сутки" className="w-24" />
</div>
<Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" />
<Button size="sm" className="self-start">Сохранить</Button>
</form>
<div className="flex flex-col gap-3 text-sm">
{props.sources.map((src) => (
<div key={src.id} className="flex flex-col gap-1">
<span className="font-medium">DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</span>
<Code>{src.dsn}</Code>
</div>
</Disclosure>
</Section>
))}
<p className="m-0 text-muted-foreground">
В коде: <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> из окружения, <code className="font-mono">release</code> = SHA деплоя,{" "}
<code className="font-mono">environment</code> = prod, <code className="font-mono">sendDefaultPii: false</code>.
</p>
{!s.webhookAuto && props.webhookUrl && (
<div className="flex flex-col gap-1">
<span><b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:</span>
<Code>{props.webhookUrl}</Code>
<span className="text-muted-foreground">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
</div>
)}
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
<Hidden fields={{ projectId, back }} />
<Label>
Политика инцидентов
<NativeSelect name="policy" defaultValue={s.policy} aria-label="Политика инцидентов">
{incidentPolicies.map((p) => (
<option key={p} value={p}>
{p} — {POLICY_RU[p]}
</option>
))}
</NativeSelect>
</Label>
<Textarea
name="triagePrompt"
rows={3}
defaultValue={s.triagePrompt ?? ""}
aria-label="Как принимать решение (для триажёра)"
placeholder="Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»"
/>
<div className="flex gap-2">
<Input name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" />
<Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Стори в сутки" title="Стори из ошибок в сутки" className="w-24" />
</div>
<Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" />
<Button size="sm" className="self-start">Сохранить</Button>
</form>
</div>
);
}

View File

@ -43,7 +43,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
<span className={cn("row-span-2 size-2 self-start mt-1.5 rounded-full", TONE_BG[st.tone], (s.status === "running" || s.status === "starting") && "animate-pulse")} />
<span className="flex min-w-0 items-baseline gap-2">
<span className="shrink-0 font-mono text-xs text-primary">{s.taskKey ?? s.projectKey}</span>
<span className="truncate">{s.taskTitle ?? "без задачи"}</span>
<span className="truncate">{s.taskTitle ?? "без стори"}</span>
</span>
<span className={cn("text-right font-mono text-xs whitespace-nowrap", TONE_TEXT[st.tone])}>{limited ? (
<>
@ -85,7 +85,7 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }:
</div>
<h2 className="m-0 text-base leading-snug font-semibold">
{s.taskKey && <Key href={`/t/${s.taskKey}`} className="mr-1.5">{s.taskKey}</Key>}
{s.taskTitle ?? "без задачи"}
{s.taskTitle ?? "без стори"}
</h2>
{s.status === "rate_limited" && (
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">

View File

@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
/**
* Button that opens a side dialog (native <dialog>) with content rendered on the server.
* Default trigger is "⋯" (page settings); pass `trigger` for a labelled button such as "+ Задача".
* Default trigger is "⋯" (page settings); pass `trigger` for a labelled button such as "+ Стори".
*/
export function SettingsDialog({ title, trigger, children }: { title: string; trigger?: ReactNode; children: ReactNode }) {
const ref = useRef<HTMLDialogElement>(null);

View File

@ -0,0 +1,43 @@
# Design: PEP-66
## Эпики = таблица `goals`
Таблица `goals` (`title`, `description`, `status` open/done/archived) и `tasks.goal_id`
(необязательная ссылка, `on delete set null`) уже делают всё, что нужно эпику-метке. Миграция
не нужна: в коде core появляются синонимы `createEpic`/`listEpics`/`updateEpic` поверх
функций целей, в интерфейсе слово «цель» заменено на «эпик». Колонку не переименовываем —
переименование таблицы ради слова стоило бы миграции боевой базы без пользы.
«В архив» в «⋯» = `status: archived`: эпик пропадает из фильтра и выбора, стори остаются с
ним (на карточке тега нет, так как архивные эпики не показываются).
## MCP: алиасы, а не переименование
Удалённые клиенты (claude.ai) кэшируют список инструментов; молча убрать `list_goals` значит
сломать сохранённые сценарии. Поэтому основные — `*_epic(s)` и `epic_id`, старые — алиасы с
описанием «Alias of …». Если переданы и `epic_id`, и `goal_id` — берётся `epic_id`.
## Вкладки Код и PR — Gitea по требованию
Страница проекта обновляется каждые несколько секунд (`AutoRefresh`), поэтому Gitea
спрашивается только для открытой вкладки и не чаще раза в минуту на проект (кэш как у
`describeRepo`), с таймаутом 5 с; при ошибке — пустое состояние со ссылкой на Gitea, страница
не падает. Клиент — тот же порядок, что у `describeRepo`: клиент владельца, затем peppa-bot.
README рисуется как текст (`<pre>`, как артефакты OpenSpec на странице стори) — без
markdown-зависимости.
PR → стори: по ветке `task/<key>-<n>` (`taskForCheck`) или по номеру PR из `tasks.pr_url`.
Проверки — `taskCiSummary` (уже есть для карточки стори). PR без стори показывается без
проверок.
## Спеки из рабочей копии
`openspec/specs/<capability>/spec.md` из `project.workspacePath` (как артефакты change на
странице стори). Показываем имя capability, `Purpose` и число требований; текст — в
раскрывашке.
## Настройки багов в «⋯»
`IncidentsSection` делится на две части: настройки (подключение, политика, окружения,
вебхук) — в «⋯ Настройки проекта», список инцидентов — во вкладке «Баги». Формы — те же
server actions, `back` указывает на текущую вкладку.
## Тексты «стори»
Меняем только то, что видит человек: веб, сообщения бота и уведомления (outbox),
описания MCP-инструментов и `instructions`, «Помощь». Внутренние имена (`tasks`, `taskKey`,
`create_task`) не трогаем. Промпты агенту («Работай над задачей …») переводим на «стори»,
чтобы агент не путал с пунктами `tasks.md`.

View File

@ -0,0 +1,36 @@
# PEP-66: Проект как в GitHub — вкладки Код, Спеки, PR; цели → эпики; задачи → стори
## Why
PM привык к GitHub: страница репозитория с вкладками Code / Issues / Pull requests / Actions /
Settings. Этап 1 (вкладки Доска · Релизы · Баги · Сессии, «+ Стори», «⋯ Настройки проекта»)
сделан быстрой полировкой. Не хватает того, что PM видит в GitHub первым делом: код (README,
ветки, коммиты), открытые PR с проверками и «что система умеет» (спеки OpenSpec). Цели как
отдельный экран не прижились — PM нужна лёгкая группировка, как label/milestone. Слово
«задача» путается с пунктами `tasks.md` внутри OpenSpec change.
## What Changes
- Вкладки страницы проекта: **Доска · Код · Спеки · PR · Релизы · Баги · Сессии** (`?tab=`).
- «Код»: README ветки по умолчанию, ссылка на Gitea, ветки, последние коммиты — через клиент
Gitea в core (`listBranches`, `listCommits`, `readme`), сборка — `repoOverview` в runner.
- «Спеки»: `openspec/specs/*/spec.md` из рабочей копии проекта (`listSpecs`).
- «PR»: открытые PR репозитория, у PR стори — ключ стори и `taskCiSummary`.
- **Эпики** вместо целей: необязательный эпик у стори (хранилище — таблица `goals`, без
миграции), тег на карточке доски, фильтр доски по эпику (`?epic=`), выбор эпика в «+ Стори»,
управление эпиками (создать, переименовать, описание, в архив) в «⋯ Настройки проекта».
Описание эпика по-прежнему уходит агенту в `get_task`. Bugsink-цель «Стабильность» — эпик.
- MCP PM: `list_epics` / `create_epic` / `update_epic` и `epic_id` в `create_task` /
`update_task`; старые `list_goals` / `create_goal` / `update_goal` и `goal_id` остаются
алиасами. Агентский MCP: `list_epics` (+ алиас `list_goals`).
- **Стори**: в интерфейсе (доска, страница стори, Главная, раннеры, бот, описания
MCP-инструментов и `instructions`, «Помощь») задачи Пеппы называются «стори». Имена
MCP-инструментов (`create_task` и т.п.) не меняются. Пункты `tasks.md` остаются «задачами».
- Настройки багов (политика, окружения, `IncidentsSection` с формой подключения) — в
«⋯ Настройки проекта»; вкладка «Баги» показывает список инцидентов.
## Impact
- `apps/web` (страница проекта, доска, «Помощь», тексты), `packages/core` (gitea, epics,
specs), `packages/runner` (repoOverview, openPulls), `packages/mcp` (тексты, алиасы),
`apps/bot` и уведомления в core/runner (тексты), `packages/testkit` (mock-gitea: ветки,
коммиты; тесты).
- Без миграций и новых зависимостей. Чтение Gitea на странице — только на открытой вкладке,
с кэшем в минуту.

View File

@ -0,0 +1,56 @@
## REMOVED Requirements
### Requirement: Цели через MCP
**Reason**: цели переименованы в эпики.
**Migration**: «Эпики через MCP»; старые инструменты остались алиасами.
### Requirement: Цель задачи
**Reason**: цели переименованы в эпики.
**Migration**: «Эпик стори»; `goal_id` остался алиасом `epic_id`.
## MODIFIED Requirements
### Requirement: Инструкции сервера
MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться
инструментами, в терминах проект → эпики → стори → доска.
#### Scenario: Подключение
- **WHEN** клиент инициализирует соединение
- **THEN** получает инструкции сервера с моделью проект → эпики → стори → доска
## ADDED Requirements
### Requirement: Эпики через MCP
MCP SHALL позволять создавать эпики в проекте пользователя (`create_epic`), видеть открытые
(`list_epics`) и менять их название, описание и статус (`update_epic`: открыт, завершён, в
архиве). `list_goals` / `create_goal` / `update_goal` SHALL работать как алиасы.
#### Scenario: Новый эпик и стори в нём
- **GIVEN** проект PAY пользователя
- **WHEN** клиент вызывает `create_epic` «Оплата картой» и затем `create_task` с его `epic_id`
- **THEN** эпик виден в `list_epics`, стори относится к этому эпику
#### Scenario: Эпик завершён
- **GIVEN** открытый эпик «Оплата картой»
- **WHEN** клиент вызывает `update_epic` со статусом `done`
- **THEN** эпик пропадает из `list_epics`, его стори не меняются
#### Scenario: Алиас цели
- **GIVEN** открытый эпик «Оплата картой»
- **WHEN** клиент вызывает `list_goals`
- **THEN** получает тот же список, что `list_epics`
### Requirement: Эпик стори
`update_task` SHALL позволять перенести стори в другой эпик своего проекта (`epic_id`, алиас
`goal_id`) или отвязать от эпика (`null`), не меняя остальное.
#### Scenario: Перенос в другой эпик
- **GIVEN** стори PAY-3 в эпике «А» и эпик «Б» того же проекта
- **WHEN** клиент вызывает `update_task` с `epic_id` эпика «Б»
- **THEN** стори относится к «Б», статус и название прежние, `get_task` показывает «Эпик: #… Б»
#### Scenario: Эпик чужого проекта
- **GIVEN** эпик принадлежит другому проекту
- **WHEN** клиент вызывает `update_task` с его `epic_id`
- **THEN** ошибка, стори не меняется

View File

@ -0,0 +1,138 @@
## REMOVED Requirements
### Requirement: Цели и задачи
**Reason**: целей как отдельного экрана нет; их место заняли эпики-метки стори.
**Migration**: см. «Стори и эпики»; таблица `goals` хранит эпики, данные не меняются.
## MODIFIED Requirements
### Requirement: Доска задач
Вкладка «Доска» страницы проекта SHALL показывать стори доской с колонками Бэклог, В
работе, Ревью, Готово; карточку можно перенести перетаскиванием или кнопкой. Перенос в «В
работе» запускает агента по стори, если активной сессии нет; перенос в «Бэклог» или «Готово»
останавливает активную сессию. Доску можно отфильтровать по эпику.
#### Scenario: Карточку в работу
- **GIVEN** стори PAY-3 в «Бэклог» без активной сессии
- **WHEN** PM переносит карточку в «В работе»
- **THEN** стори получает статус `in_progress` и по ней запускается сессия агента
#### Scenario: Карточку в готово
- **GIVEN** стори PAY-3 в «Ревью» с активной сессией
- **WHEN** PM переносит карточку в «Готово»
- **THEN** стори `done`, активная сессия по ней остановлена
#### Scenario: Фильтр по эпику
- **GIVEN** стори PAY-1 в эпике «Оплата картой» и PAY-2 без эпика
- **WHEN** PM выбирает над доской эпик «Оплата картой»
- **THEN** на доске только PAY-1, адрес страницы содержит `?epic=<id>`
#### Scenario: Чужой эпик в фильтре
- **GIVEN** эпик с id 999 принадлежит другому проекту
- **WHEN** PM открывает доску PAY с `?epic=999`
- **THEN** доска показывает все стори проекта без фильтра
## ADDED Requirements
### Requirement: Стори и эпики
Пользователь SHALL создавать стори (задачи Пеппы) в своём проекте и относить их к
необязательному эпику проекта. Номер стори выдаётся так же, как через MCP и CLI. Отдельного
экрана целей нет: эпики — метки стори.
#### Scenario: Новая стори в эпике
- **GIVEN** в проекте PAY есть эпик «Оплата картой»
- **WHEN** пользователь в «+ Стори» вводит название «Форма оплаты» и выбирает эпик «Оплата картой»
- **THEN** стори получает следующий номер проекта (`PAY-N`), статус `backlog`
- **AND** на её карточке на доске виден тег «Оплата картой»
#### Scenario: Стори без эпика
- **GIVEN** проект PAY
- **WHEN** пользователь создаёт стори, оставив эпик «без эпика»
- **THEN** стори создана без эпика, на карточке тега нет
### Requirement: Вкладки проекта
Страница проекта SHALL иметь вкладки Доска · Код · Спеки · PR · Релизы · Баги · Сессии
(параметр `?tab=`), кнопку «+ Стори» и «⋯ Настройки проекта» в заголовке. Неизвестная вкладка
открывает Доску.
#### Scenario: Переход на вкладку
- **GIVEN** проект PAY
- **WHEN** пользователь открывает `/p/PAY?tab=code`
- **THEN** активна вкладка «Код»
#### Scenario: Неизвестная вкладка
- **WHEN** пользователь открывает `/p/PAY?tab=nope`
- **THEN** активна вкладка «Доска»
### Requirement: Вкладка «Код»
Вкладка «Код» SHALL показывать README ветки по умолчанию, ссылку на репозиторий в Gitea,
ветки и последние коммиты (сообщение, автор, время, короткий SHA). Gitea спрашивается не чаще
раза в минуту на проект; если Gitea недоступна, вкладка показывает ссылку на репозиторий и
сообщение, страница не падает.
#### Scenario: Репозиторий с кодом
- **GIVEN** в репозитории PAY ветки `main` и `task/PAY-3`, в `main` есть README.md «# Pay»
- **WHEN** пользователь открывает вкладку «Код»
- **THEN** видны текст README «# Pay», ветки `main` и `task/PAY-3` и последний коммит `main`
#### Scenario: Gitea недоступна
- **GIVEN** Gitea не отвечает
- **WHEN** пользователь открывает вкладку «Код»
- **THEN** видна ссылка на репозиторий и «Gitea сейчас не отвечает»
### Requirement: Вкладка «Спеки»
Вкладка «Спеки» SHALL показывать спецификации `openspec/specs/*/spec.md` из рабочей копии
проекта — что система умеет сейчас: имя, назначение, число требований и текст.
#### Scenario: Есть спеки
- **GIVEN** в рабочей копии есть `openspec/specs/web-auth/spec.md` с двумя требованиями
- **WHEN** пользователь открывает вкладку «Спеки»
- **THEN** виден пункт «web-auth» с назначением и «2 требования»
#### Scenario: Спек нет
- **GIVEN** в рабочей копии нет `openspec/specs`
- **WHEN** пользователь открывает вкладку «Спеки»
- **THEN** видно «Спек ещё нет — они появляются после archive первого change»
### Requirement: Вкладка «PR»
Вкладка «PR» SHALL показывать открытые PR репозитория со ссылками; у PR стори — ключ стори и
сводку проверок (`taskCiSummary`).
#### Scenario: PR стори
- **GIVEN** открыт PR из ветки `task/PAY-3`, проверки головного коммита: 2 из 2 пройдены
- **WHEN** пользователь открывает вкладку «PR»
- **THEN** виден PR со ссылкой на стори PAY-3 и «Проверки: 2 из 2 пройдены»
#### Scenario: Открытых PR нет
- **GIVEN** в репозитории нет открытых PR
- **WHEN** пользователь открывает вкладку «PR»
- **THEN** видно «Открытых PR нет»
### Requirement: Настройки проекта
«⋯ Настройки проекта» SHALL содержать репозиторий, участников, эпики (создать,
переименовать, описание, в архив) и настройки багов (подключение отслеживания ошибок,
политика, окружения). Вкладка «Баги» показывает список инцидентов.
#### Scenario: Новый эпик
- **GIVEN** проект PAY без эпиков
- **WHEN** PM в «⋯» добавляет эпик «Оплата картой»
- **THEN** эпик доступен в «+ Стори» и в фильтре доски
#### Scenario: Эпик в архив
- **GIVEN** эпик «Оплата картой» со стори PAY-1
- **WHEN** PM отправляет эпик в архив
- **THEN** эпика нет в «+ Стори» и в фильтре, стори PAY-1 не изменилась
### Requirement: Слово «стори»
Интерфейс (веб, бот Telegram, описания MCP-инструментов и инструкции сервера, «Помощь»)
SHALL называть задачи Пеппы «стори», а группы стори — «эпиками»; пункты `tasks.md` OpenSpec
change остаются «задачами». Имена MCP-инструментов не меняются.
#### Scenario: Сообщение «готово к ревью»
- **GIVEN** стори PAY-3 переходит в ревью
- **WHEN** бот отправляет PM уведомление
- **THEN** в тексте стоит «стори PAY-3», а не «задача PAY-3»
#### Scenario: Имя инструмента
- **WHEN** клиент MCP запрашивает список инструментов
- **THEN** `create_task` есть, а его описание говорит о стори

View File

@ -0,0 +1,20 @@
# Tasks: PEP-66
## 1. Эпики
- [x] 1.1 core: `createEpic`/`listEpics`/`updateEpic` поверх целей; Bugsink-«Стабильность» описана как эпик
- [x] 1.2 MCP PM: `list_epics`/`create_epic`/`update_epic`, `epic_id` в `create_task`/`update_task`, алиасы `*_goal(s)`/`goal_id`; агентский MCP `list_epics` + алиас; `get_task` — «Эпик»
- [x] 1.3 Веб: эпик в «+ Стори», тег на карточке, фильтр `?epic=` на доске, управление эпиками в «⋯»; server actions с проверкой доступа
## 2. Вкладки
- [x] 2.1 core Gitea: `listBranches`, `listCommits`, `readme`, `listPulls`; mock-gitea: ветки, коммиты
- [x] 2.2 runner: `repoOverview` (README, ветки, коммиты, кэш, таймаут), `openPulls` (PR → стори + `taskCiSummary`); core `listSpecs`
- [x] 2.3 Веб: вкладки «Код», «Спеки», «PR»; настройки багов в «⋯», вкладка «Баги» — список
## 3. Стори
- [x] 3.1 Тексты веба (доска, страница стори, Главная, раннеры, проекты, «Помощь», OAuth-согласие)
- [x] 3.2 Бот и уведомления (core/runner), промпты агенту
- [x] 3.3 Описания MCP-инструментов и `instructions`
## 4. Проверка
- [x] 4.1 Тесты: эпики (MCP, алиасы, фильтр), repoOverview/openPulls на mock-gitea, listSpecs
- [x] 4.2 `pnpm typecheck`, e2e, `next build`; UI своим `next dev` на копии базы

View File

@ -64,25 +64,6 @@ MCP SHALL позволять менять название и описание
- **WHEN** не передано ни `title`, ни `description`, или задача из чужого проекта
- **THEN** ошибка, задача не меняется
### Requirement: Цели через MCP
MCP SHALL позволять создавать цели в проекте пользователя и менять их название,
описание и статус (открыта, достигнута, в архиве).
#### Scenario: Новая цель и задачи под ней
- **WHEN** клиент создаёт цель и затем задачу с её `goal_id`
- **THEN** цель видна в списке целей проекта, задача — под этой целью
#### Scenario: Цель достигнута
- **WHEN** клиент меняет статус цели на «достигнута»
- **THEN** цель пропадает из списка открытых целей, её задачи не меняются
### Requirement: Цель задачи
`update_task` SHALL позволять перенести задачу в другую цель своего проекта или отвязать от цели, не меняя остальное.
#### Scenario: Перенос в другую цель
- **WHEN** клиент вызывает `update_task` с `goal_id` другой цели проекта
- **THEN** задача относится к этой цели, статус и название прежние
### Requirement: Создание проекта через MCP
MCP SHALL создавать проект так же, как веб: новый или существующий репозиторий в
пространстве пользователя или его организации, от имени пользователя.
@ -92,8 +73,43 @@ MCP SHALL создавать проект так же, как веб: новый
- **THEN** проект создан с пользователем-владельцем и виден в `list_projects`
### Requirement: Инструкции сервера
MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться инструментами.
MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться
инструментами, в терминах проект → эпики → стори → доска.
#### Scenario: Подключение
- **WHEN** клиент инициализирует соединение
- **THEN** получает инструкции сервера с моделью проект → цели → задачи → доска
- **THEN** получает инструкции сервера с моделью проект → эпики → стори → доска
### Requirement: Эпики через MCP
MCP SHALL позволять создавать эпики в проекте пользователя (`create_epic`), видеть открытые
(`list_epics`) и менять их название, описание и статус (`update_epic`: открыт, завершён, в
архиве). `list_goals` / `create_goal` / `update_goal` SHALL работать как алиасы.
#### Scenario: Новый эпик и стори в нём
- **GIVEN** проект PAY пользователя
- **WHEN** клиент вызывает `create_epic` «Оплата картой» и затем `create_task` с его `epic_id`
- **THEN** эпик виден в `list_epics`, стори относится к этому эпику
#### Scenario: Эпик завершён
- **GIVEN** открытый эпик «Оплата картой»
- **WHEN** клиент вызывает `update_epic` со статусом `done`
- **THEN** эпик пропадает из `list_epics`, его стори не меняются
#### Scenario: Алиас цели
- **GIVEN** открытый эпик «Оплата картой»
- **WHEN** клиент вызывает `list_goals`
- **THEN** получает тот же список, что `list_epics`
### Requirement: Эпик стори
`update_task` SHALL позволять перенести стори в другой эпик своего проекта (`epic_id`, алиас
`goal_id`) или отвязать от эпика (`null`), не меняя остальное.
#### Scenario: Перенос в другой эпик
- **GIVEN** стори PAY-3 в эпике «А» и эпик «Б» того же проекта
- **WHEN** клиент вызывает `update_task` с `epic_id` эпика «Б»
- **THEN** стори относится к «Б», статус и название прежние, `get_task` показывает «Эпик: #… Б»
#### Scenario: Эпик чужого проекта
- **GIVEN** эпик принадлежит другому проекту
- **WHEN** клиент вызывает `update_task` с его `epic_id`
- **THEN** ошибка, стори не меняется

View File

@ -1,7 +1,7 @@
# web-workspace Specification
## Purpose
Определяет, что пользователь делает в вебе со своими проектами: ведёт цели и задачи, следит за сессиями агентов и управляет ими, отвечает на вопросы агентов.
Определяет, что пользователь делает в вебе со своими проектами: ведёт стори и эпики, следит за сессиями агентов и управляет ими, отвечает на вопросы агентов.
## Requirements
@ -13,14 +13,6 @@
- **WHEN** у пользователя есть неотвеченные вопросы в его проектах
- **THEN** на главной каждый виден с задачей, типом (одобрение, вопрос, разрешение, «ждёт тебя»), текстом и формой ответа
### Requirement: Цели и задачи
Пользователь SHALL создавать цели и задачи в своём проекте и видеть задачи
сгруппированными по целям со статусами. Номер задачи выдаётся так же, как через MCP и CLI.
#### Scenario: Новая задача под целью
- **WHEN** пользователь создаёт задачу с названием и описанием под целью
- **THEN** задача получает следующий номер проекта (`KEY-N`), статус `backlog` и видна под этой целью
### Requirement: Страница задачи
Страница задачи SHALL показывать описание, цель, статус, PR, артефакты OpenSpec change
(proposal, design, tasks — как текст из рабочей копии), вопросы с ответами, сессии и
@ -64,18 +56,30 @@
- **THEN** вопрос появляется на странице в течение 10 секунд
### Requirement: Доска задач
Страница проекта SHALL показывать задачи доской с колонками Бэклог, В работе, Ревью,
Готово; карточку можно перенести перетаскиванием или кнопкой. Перенос в «В работе»
запускает агента по задаче, если активной сессии нет; перенос в «Бэклог» или «Готово»
останавливает активную сессию.
Вкладка «Доска» страницы проекта SHALL показывать стори доской с колонками Бэклог, В
работе, Ревью, Готово; карточку можно перенести перетаскиванием или кнопкой. Перенос в «В
работе» запускает агента по стори, если активной сессии нет; перенос в «Бэклог» или «Готово»
останавливает активную сессию. Доску можно отфильтровать по эпику.
#### Scenario: Карточку в работу
- **WHEN** PM переносит карточку из «Бэклог» в «В работе»
- **THEN** задача получает статус `in_progress` и по ней запускается сессия агента
- **GIVEN** стори PAY-3 в «Бэклог» без активной сессии
- **WHEN** PM переносит карточку в «В работе»
- **THEN** стори получает статус `in_progress` и по ней запускается сессия агента
#### Scenario: Карточку в готово
- **WHEN** PM переносит карточку из «Ревью» в «Готово»
- **THEN** задача `done`, активная сессия по ней остановлена
- **GIVEN** стори PAY-3 в «Ревью» с активной сессией
- **WHEN** PM переносит карточку в «Готово»
- **THEN** стори `done`, активная сессия по ней остановлена
#### Scenario: Фильтр по эпику
- **GIVEN** стори PAY-1 в эпике «Оплата картой» и PAY-2 без эпика
- **WHEN** PM выбирает над доской эпик «Оплата картой»
- **THEN** на доске только PAY-1, адрес страницы содержит `?epic=<id>`
#### Scenario: Чужой эпик в фильтре
- **GIVEN** эпик с id 999 принадлежит другому проекту
- **WHEN** PM открывает доску PAY с `?epic=999`
- **THEN** доска показывает все стори проекта без фильтра
### Requirement: Помощь
Веб SHALL иметь страницу «Помощь», доступную из меню, с описанием понятий Пеппы,
@ -178,3 +182,106 @@
- **GIVEN** пользователь переключил тему на светлую
- **WHEN** он закрывает и снова открывает веб
- **THEN** страница в светлой теме без мигания тёмной
### Requirement: Стори и эпики
Пользователь SHALL создавать стори (задачи Пеппы) в своём проекте и относить их к
необязательному эпику проекта. Номер стори выдаётся так же, как через MCP и CLI. Отдельного
экрана целей нет: эпики — метки стори.
#### Scenario: Новая стори в эпике
- **GIVEN** в проекте PAY есть эпик «Оплата картой»
- **WHEN** пользователь в «+ Стори» вводит название «Форма оплаты» и выбирает эпик «Оплата картой»
- **THEN** стори получает следующий номер проекта (`PAY-N`), статус `backlog`
- **AND** на её карточке на доске виден тег «Оплата картой»
#### Scenario: Стори без эпика
- **GIVEN** проект PAY
- **WHEN** пользователь создаёт стори, оставив эпик «без эпика»
- **THEN** стори создана без эпика, на карточке тега нет
### Requirement: Вкладки проекта
Страница проекта SHALL иметь вкладки Доска · Код · Спеки · PR · Релизы · Баги · Сессии
(параметр `?tab=`), кнопку «+ Стори» и «⋯ Настройки проекта» в заголовке. Неизвестная вкладка
открывает Доску.
#### Scenario: Переход на вкладку
- **GIVEN** проект PAY
- **WHEN** пользователь открывает `/p/PAY?tab=code`
- **THEN** активна вкладка «Код»
#### Scenario: Неизвестная вкладка
- **WHEN** пользователь открывает `/p/PAY?tab=nope`
- **THEN** активна вкладка «Доска»
### Requirement: Вкладка «Код»
Вкладка «Код» SHALL показывать README ветки по умолчанию, ссылку на репозиторий в Gitea,
ветки и последние коммиты (сообщение, автор, время, короткий SHA). Gitea спрашивается не чаще
раза в минуту на проект; если Gitea недоступна, вкладка показывает ссылку на репозиторий и
сообщение, страница не падает.
#### Scenario: Репозиторий с кодом
- **GIVEN** в репозитории PAY ветки `main` и `task/PAY-3`, в `main` есть README.md «# Pay»
- **WHEN** пользователь открывает вкладку «Код»
- **THEN** видны текст README «# Pay», ветки `main` и `task/PAY-3` и последний коммит `main`
#### Scenario: Gitea недоступна
- **GIVEN** Gitea не отвечает
- **WHEN** пользователь открывает вкладку «Код»
- **THEN** видна ссылка на репозиторий и «Gitea сейчас не отвечает»
### Requirement: Вкладка «Спеки»
Вкладка «Спеки» SHALL показывать спецификации `openspec/specs/*/spec.md` из рабочей копии
проекта — что система умеет сейчас: имя, назначение, число требований и текст.
#### Scenario: Есть спеки
- **GIVEN** в рабочей копии есть `openspec/specs/web-auth/spec.md` с двумя требованиями
- **WHEN** пользователь открывает вкладку «Спеки»
- **THEN** виден пункт «web-auth» с назначением и «2 требования»
#### Scenario: Спек нет
- **GIVEN** в рабочей копии нет `openspec/specs`
- **WHEN** пользователь открывает вкладку «Спеки»
- **THEN** видно «Спек ещё нет — они появляются после archive первого change»
### Requirement: Вкладка «PR»
Вкладка «PR» SHALL показывать открытые PR репозитория со ссылками; у PR стори — ключ стори и
сводку проверок (`taskCiSummary`).
#### Scenario: PR стори
- **GIVEN** открыт PR из ветки `task/PAY-3`, проверки головного коммита: 2 из 2 пройдены
- **WHEN** пользователь открывает вкладку «PR»
- **THEN** виден PR со ссылкой на стори PAY-3 и «Проверки: 2 из 2 пройдены»
#### Scenario: Открытых PR нет
- **GIVEN** в репозитории нет открытых PR
- **WHEN** пользователь открывает вкладку «PR»
- **THEN** видно «Открытых PR нет»
### Requirement: Настройки проекта
«⋯ Настройки проекта» SHALL содержать репозиторий, участников, эпики (создать,
переименовать, описание, в архив) и настройки багов (подключение отслеживания ошибок,
политика, окружения). Вкладка «Баги» показывает список инцидентов.
#### Scenario: Новый эпик
- **GIVEN** проект PAY без эпиков
- **WHEN** PM в «⋯» добавляет эпик «Оплата картой»
- **THEN** эпик доступен в «+ Стори» и в фильтре доски
#### Scenario: Эпик в архив
- **GIVEN** эпик «Оплата картой» со стори PAY-1
- **WHEN** PM отправляет эпик в архив
- **THEN** эпика нет в «+ Стори» и в фильтре, стори PAY-1 не изменилась
### Requirement: Слово «стори»
Интерфейс (веб, бот Telegram, описания MCP-инструментов и инструкции сервера, «Помощь»)
SHALL называть задачи Пеппы «стори», а группы стори — «эпиками»; пункты `tasks.md` OpenSpec
change остаются «задачами». Имена MCP-инструментов не меняются.
#### Scenario: Сообщение «готово к ревью»
- **GIVEN** стори PAY-3 переходит в ревью
- **WHEN** бот отправляет PM уведомление
- **THEN** в тексте стоит «стори PAY-3», а не «задача PAY-3»
#### Scenario: Имя инструмента
- **WHEN** клиент MCP запрашивает список инструментов
- **THEN** `create_task` есть, а его описание говорит о стори

View File

@ -36,6 +36,16 @@ export interface GiteaPull {
head: { ref: string; sha: string; repo?: { full_name: string } | null };
base: { ref: string };
}
export interface GiteaBranch {
name: string;
commit: { id: string; message: string; timestamp: string; author?: { name: string } };
}
export interface GiteaCommit {
sha: string;
html_url: string;
commit: { message: string; author: { name: string; date: string } };
author?: { login: string } | null;
}
export interface GiteaCommitStatus {
context: string;
status: "pending" | "success" | "error" | "failure" | "warning";
@ -171,11 +181,34 @@ export class GiteaClient {
return this.request<GiteaPull>("GET", `${this.repoPath(owner, repo)}/pulls/${n}`);
}
/** Open pull requests, newest first. */
listOpenPulls(owner: string, repo: string) {
return this.request<GiteaPull[]>("GET", `${this.repoPath(owner, repo)}/pulls?state=open&sort=recentupdate&limit=50`);
}
async openPullForBranch(owner: string, repo: string, branch: string): Promise<GiteaPull | null> {
const pulls = await this.request<GiteaPull[]>("GET", `${this.repoPath(owner, repo)}/pulls?state=open&limit=50`);
const pulls = await this.listOpenPulls(owner, repo);
return pulls.find((p) => p.head.ref === branch) ?? null;
}
listBranches(owner: string, repo: string) {
return this.request<GiteaBranch[]>("GET", `${this.repoPath(owner, repo)}/branches?limit=50`);
}
/** Latest commits of `ref` (no diffs, no stats). */
listCommits(owner: string, repo: string, ref: string, limit = 10) {
return this.request<GiteaCommit[]>("GET", `${this.repoPath(owner, repo)}/commits?sha=${encodeURIComponent(ref)}&limit=${limit}&stat=false&verification=false&files=false`);
}
/** README of `ref` (README.md, then other common names); null if there is none. */
async readme(owner: string, repo: string, ref: string): Promise<{ path: string; text: string } | null> {
for (const path of ["README.md", "readme.md", "README", "README.txt"]) {
const text = await this.fileText(owner, repo, path, ref);
if (text !== null) return { path, text };
}
return null;
}
/** Paths changed by a pull request. */
async pullFiles(owner: string, repo: string, n: number): Promise<string[]> {
const files = await this.request<Array<{ filename: string }>>("GET", `${this.repoPath(owner, repo)}/pulls/${n}/files?limit=100`);

View File

@ -21,9 +21,9 @@ export { incidentPolicies, incidentStatuses, type IncidentPolicy };
export const INCIDENT_STATUS_RU: Record<IncidentStatus, string> = {
new: "новая",
open: "без задачи",
open: "без стори",
pending: "ждёт разбора",
task: "задача",
task: "стори",
ignored: "игнорируется",
resolved: "исправлена",
regressed: "вернулась",
@ -31,8 +31,8 @@ export const INCIDENT_STATUS_RU: Record<IncidentStatus, string> = {
export const POLICY_RU: Record<IncidentPolicy, string> = {
notify: "только уведомить",
backlog: "задача в бэклог",
start: "задача сразу в работу",
backlog: "стори в бэклог",
start: "стори сразу в работу",
ask: "спросить в Telegram",
triage: "решает агент-триажёр",
};
@ -52,11 +52,11 @@ export async function incidentSettingsBySecret(db: Db, secret: string): Promise<
return row ?? null;
}
/** Turns error tracking on: webhook secret, default policy and the «Стабильность» goal. */
/** Turns error tracking on: webhook secret, default policy and the «Стабильность» epic. */
export async function enableIncidents(db: Db, projectId: number, o: { webhookAuto?: boolean } = {}): Promise<IncidentSettings> {
const existing = await getIncidentSettings(db, projectId);
if (existing) return existing;
const goal = (await listGoals(db, projectId)).find((g) => g.title === STABILITY_GOAL) ?? (await createGoal(db, projectId, STABILITY_GOAL, "Ошибки из работающего продукта (Bugsink): задачи-баги создаются здесь."));
const goal = (await listGoals(db, projectId)).find((g) => g.title === STABILITY_GOAL) ?? (await createGoal(db, projectId, STABILITY_GOAL, "Ошибки из работающего продукта (Bugsink): стори-баги создаются в этом эпике."));
const [row] = await db
.insert(incidentSettings)
.values({ projectId, hookSecret: randomBytes(24).toString("base64url"), goalId: goal.id, webhookAuto: o.webhookAuto ?? false })
@ -300,13 +300,13 @@ export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i:
if (i.url) lines.push(`<a href="${esc(i.url)}">Открыть в Bugsink</a>`);
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
if (m.kind === "task") {
lines.push("", m.started ? `▶️ Агент взялся: ${taskLink(m.task)}` : `📥 Задача в бэклоге: ${taskLink(m.task)}`);
lines.push("", m.started ? `▶️ Агент взялся: ${taskLink(m.task)}` : `📥 Стори в бэклоге: ${taskLink(m.task)}`);
if (m.reason) lines.push(`🤖 Триажёр: ${esc(clip(m.reason, 500))}`);
} else if (m.kind === "ask") {
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
lines.push("", "Что делаем?");
} else if (m.kind === "regressed") {
lines.push("", m.task ? `Задача ${taskLink(m.task)} снова в бэклоге.` : "Задачи нет — реши, что делать.");
lines.push("", m.task ? `Стори ${taskLink(m.task)} снова в бэклоге.` : "Стори нет — реши, что делать.");
} else {
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">Ошибки проекта</a>`);
}

View File

@ -19,3 +19,4 @@ export * from "./incidents.ts";
export * from "./ci.ts";
export * from "./egov.ts";
export * from "./local-users.ts";
export * from "./specs.ts";

View File

@ -71,3 +71,12 @@ export async function updateGoal(db: Db, projectId: number, goalId: number, patc
const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning();
return row!;
}
// PEP-66: goals are shown as «эпики» — optional labels that group stories. Same table and
// rows (no migration); these are the names new code should use.
export type Epic = Goal;
export type EpicPatch = GoalPatch;
export const createEpic = createGoal;
export const listEpics = listGoals;
export const getEpic = getGoal;
export const updateEpic = updateGoal;

View File

@ -0,0 +1,27 @@
// «Спеки» tab (PEP-66): what the system can do now — openspec/specs/*/spec.md of the
// project's working copy.
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import type { Project } from "./projects.ts";
export interface SpecSummary {
/** Capability name: the folder under openspec/specs. */
name: string;
purpose: string;
requirements: number;
text: string;
}
export function parseSpec(name: string, text: string): SpecSummary {
const purpose = text.match(/^## Purpose\s*\n([\s\S]*?)(?=^## |(?![\s\S]))/m)?.[1]?.trim() ?? "";
return { name, purpose: /^TBD\b/.test(purpose) ? "" : purpose, requirements: (text.match(/^### Requirement:/gm) ?? []).length, text };
}
export function listSpecs(project: Pick<Project, "workspacePath">): SpecSummary[] {
const dir = join(project.workspacePath, "openspec", "specs");
if (!existsSync(dir)) return [];
return readdirSync(dir, { withFileTypes: true })
.filter((d) => d.isDirectory() && existsSync(join(dir, d.name, "spec.md")))
.map((d) => parseSpec(d.name, readFileSync(join(dir, d.name, "spec.md"), "utf8")))
.sort((a, b) => a.name.localeCompare(b.name));
}

View File

@ -5,9 +5,9 @@ const NEXT_STEP: Record<TaskStatus, string> = {
proposing: "Допиши артефакты, `openspec validate`, затем сразу Apply (update_task status: in_progress). request_approval — только для архитектурных стопперов.",
awaiting_approval: "Ты запросил одобрение архитектурного решения. Ничего не реализуй — жди ответа PM, закончи ход.",
in_progress: "Apply: продолжай с первого невыполненного пункта tasks.md (workflow openspec-apply-change), report_progress по ходу. В конце — archive, PR, update_task(status: review).",
review: "Задача в ревью у PM. Если в вопросах ниже есть замечания — доделай их; иначе ничего не делай.",
done: "Задача завершена — ничего делать не нужно.",
blocked: "Задача заблокирована — выясни причину в вопросах ниже или спроси PM через ask_pm.",
review: "Стори в ревью у PM. Если в вопросах ниже есть замечания — доделай их; иначе ничего не делай.",
done: "Стори завершена — ничего делать не нужно.",
blocked: "Стори заблокирована — выясни причину в вопросах ниже или спроси PM через ask_pm.",
};
export function formatTask(d: TaskDetails): string {
@ -17,14 +17,14 @@ export function formatTask(d: TaskDetails): string {
"",
`- Проект: ${d.project.name} (${d.project.key})`,
`- Статус: **${task.status}**`,
`- Цель: ${goal ? `#${goal.id} ${goal.title}` : "—"}`,
`- Эпик: ${goal ? `#${goal.id} ${goal.title}` : "—"}`,
`- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`,
];
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
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}` : ""}`);
lines.push("", "## Описание", "", task.description?.trim() || "_нет описания_");
if (goal?.description) lines.push("", `## Цель #${goal.id}: ${goal.title}`, "", goal.description.trim());
if (goal?.description) lines.push("", `## Эпик #${goal.id}: ${goal.title}`, "", goal.description.trim());
if (d.incident) lines.push("", "## Инцидент", "", formatIncident(d.incident));
if (d.questions.length) {
lines.push("", "## Вопросы к PM");

View File

@ -1,5 +1,5 @@
// Peppa MCP server: gives Claude sessions inside a project access to its goals, tasks
// and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
// Peppa MCP server: gives Claude sessions inside a project access to its epics, stories
// (tasks in the tool names) and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
@ -11,7 +11,7 @@ import {
getTaskDetails,
incidentStatuses,
listIncidents,
listGoals,
listEpics,
listTasks,
loadSharedRules,
PeppaError,
@ -53,7 +53,7 @@ function tool<S extends z.ZodRawShape>(
const taskArg = z
.string()
.describe(`Task key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
.describe(`Story key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
const projectArg = z
.string()
.optional()
@ -67,53 +67,56 @@ async function projectOrDefault(p?: string) {
tool(
"get_rules",
"Get Peppa's shared agent rules (task workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
"Get Peppa's shared agent rules (story workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
{},
async () => (await loadSharedRules()).text,
);
tool("get_task", "Get a Peppa task: description, goal, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a task number.", { task: taskArg }, async ({ task }) =>
tool("get_task", "Get a Peppa story (one business story = one OpenSpec change): description, epic, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a story number.", { task: taskArg }, async ({ task }) =>
formatTask(await getTaskDetails(db, await resolveTask(db, task, defaultKey))),
);
tool(
"list_tasks",
"List tasks in a project, optionally filtered by status or goal.",
{ project: projectArg, status: z.enum(TASK_STATUSES).optional(), goal_id: z.number().int().optional() },
async ({ project, status, goal_id }) => {
"List stories in a project, optionally filtered by status or epic.",
{ 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: goal_id, statuses: status ? [status] : undefined });
if (!rows.length) return "No tasks.";
return rows.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`).join("\n");
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");
},
);
tool("list_goals", "List the open top-level goals of a project.", { project: projectArg }, async ({ project }) => {
const listEpicsText = async ({ project }: { project?: string }) => {
const p = await projectOrDefault(project);
const rows = await listGoals(db, p.id);
if (!rows.length) return "No open goals.";
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");
});
};
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);
tool(
"create_task",
"Create a new task (e.g. follow-up work discovered outside the current change's scope). Link it to a goal when possible.",
"Create a new story (e.g. follow-up work discovered outside the current change's scope). Label it with an epic when one fits.",
{
title: z.string().min(3),
description: z.string().optional(),
goal_id: z.number().int().optional(),
epic_id: z.number().int().optional(),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
project: projectArg,
},
async ({ title, description, goal_id, project }) => {
async ({ title, description, epic_id, goal_id, project }) => {
const p = await projectOrDefault(project);
const ref = await createTask(db, { projectId: p.id, goalId: goal_id, title, description });
const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description });
return `Created ${ref.key}: ${title}`;
},
);
tool(
"update_task",
"Update a task's status, OpenSpec change name, PR URL, title or description.",
"Update a story's status, OpenSpec change name, PR URL, title or description.",
{
task: taskArg,
status: z.enum(TASK_STATUSES).optional(),
@ -125,7 +128,7 @@ tool(
async ({ task, status, openspec_change, pr_url, title, description }) => {
const ref = await resolveTask(db, task, defaultKey);
// Acceptance stays with the PM: agents can't mark work done or approve themselves.
if (status === "done") throw new PeppaError("Only the PM marks a task done. Open a PR and set status: review.");
if (status === "done") throw new PeppaError("Only the PM marks a story done. Open a PR and set status: review.");
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
}
@ -143,7 +146,7 @@ tool(
tool(
"request_approval",
"Ask the PM to approve an ARCHITECTURAL decision in a task's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
"Ask the PM to approve an ARCHITECTURAL decision in a story's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
{ task: taskArg, summary: z.string().min(10).describe("What, why, risks, open questions — readable on a phone") },
async ({ task, summary }) => {
const ref = await resolveTask(db, task, defaultKey);
@ -169,7 +172,7 @@ tool(
tool(
"report_progress",
"Log a short progress note on a task (visible to the PM in the web UI / Telegram digest).",
"Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
{ task: taskArg, text: z.string().min(3) },
async ({ task, text }) => {
const ref = await resolveTask(db, task, defaultKey);
@ -180,19 +183,19 @@ tool(
tool(
"list_incidents",
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked task.",
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
async ({ project, status }) => {
const p = await projectOrDefault(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return "No incidents.";
return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · task #${i.taskId}` : ""}`).join("\n");
return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · story #${i.taskId}` : ""}`).join("\n");
},
);
tool(
"get_incident",
"Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug task made from an incident: first write a test reproducing this stack.",
"Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug story made from an incident: first write a test reproducing this stack.",
{ id: z.number().int() },
async ({ id }) => {
const i = await getIncident(db, id);

View File

@ -2,14 +2,14 @@
// user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
createGoal,
createEpic,
createTask,
getGoal,
updateGoal,
getEpic,
updateEpic,
getProject,
getQuestion,
getTaskDetails,
listGoals,
listEpics,
listMembers,
listTasks,
listUserProjects,
@ -41,16 +41,16 @@ const COLUMNS = ["backlog", "in_progress", "review", "done"] as const;
const COLUMN_NAME: Record<BoardColumn, string> = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
/** Sent to clients on initialize: how Peppa is organised and how to use the tools. */
export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement tasks in Gitea repos, following OpenSpec.
export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement stories in Gitea repos, following OpenSpec.
Model: project (a Gitea repo, key like PEP) → goals (top-level objectives) → tasks (PEP-12, one deliverable each) → board columns Backlog / In progress / Review / Done.
- Moving a task to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the task to review. backlog/done stop the agent.
- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed task).
Model: project (a Gitea repo, key like PEP) → epics (optional labels that group stories) → stories (PEP-12: one business story = one OpenSpec change; the tools call them "tasks") → board columns Backlog / In progress / Review / Done. Note: "tasks" inside an OpenSpec change (tasks.md) are the agent's checklist items, not stories.
- Moving a story to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the story to review. backlog/done stop the agent.
- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed story).
Good habits:
- Before creating, look: list_projects, list_goals, list_tasks. Don't duplicate — fix with update_task / update_goal.
- Put tasks under a goal (goal_id). Write task descriptions with context and a "Definition of done" list; the agent works from them.
- Only move a task to in_progress when the user asks to start the work.
- 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.
- 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.
- 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.
@ -75,10 +75,10 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
await projectForUser(db, user.id, ref.project.id);
return ref;
};
const taskArg = z.string().describe("Task key, e.g. PEP-3");
const taskArg = z.string().describe("Story key, e.g. PEP-3");
const projectArg = z.string().describe("Project key (e.g. PEP) or slug");
tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo URL, task counts by board column).", {}, true, async () => {
tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo URL, story counts by board column).", {}, true, async () => {
const ps = await listUserProjects(db, user.id);
if (!ps.length) return "No projects yet. Create one at " + webUrl + "/projects/new";
const lines = [];
@ -124,43 +124,35 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
tool("list_goals", "List open top-level goals of a project.", { project: projectArg }, true, async ({ project }) => {
// Epics (PEP-66) live in the goals table; the *_goal(s) tools and goal_id stay as aliases.
const listEpicsText = async ({ project }: { project: string }) => {
const p = await ownedProject(project);
const gs = await listGoals(db, p.id);
return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals.";
});
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 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 }) => {
const p = await ownedProject(project);
const g = await createEpic(db, p.id, title, description);
return `Created epic #${g.id} in ${p.key}: ${g.title}`;
};
const epicPatch = { title: z.string().trim().min(3).optional(), description: z.string().optional(), status: z.enum(["open", "done", "archived"]).optional() };
const updateEpicText = async (a: { project: string; epic_id?: number; goal_id?: number; title?: string; description?: string; status?: "open" | "done" | "archived" }) => {
const { project, title, description, status } = a;
const id = a.epic_id ?? a.goal_id!;
if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status");
const p = await ownedProject(project);
await getEpic(db, p.id, id).catch(() => { throw new PeppaError("Не найдено"); });
const g = await updateEpic(db, p.id, id, { title, description, status });
return `Epic #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
};
tool(
"create_goal",
"Create a top-level goal in a project (an objective that groups tasks).",
{ project: projectArg, title: z.string().trim().min(3), description: z.string().optional() },
false,
async ({ project, title, description }) => {
const p = await ownedProject(project);
const g = await createGoal(db, p.id, title, description);
return `Created goal #${g.id} in ${p.key}: ${g.title}`;
},
);
tool(
"update_goal",
"Edit a goal: title, description and/or status (open, done = achieved, archived). Its tasks are not changed.",
{
project: projectArg,
goal_id: z.number().int(),
title: z.string().trim().min(3).optional(),
description: z.string().optional(),
status: z.enum(["open", "done", "archived"]).optional(),
},
false,
async ({ project, goal_id, title, description, status }) => {
if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status");
const p = await ownedProject(project);
await getGoal(db, p.id, goal_id).catch(() => { throw new PeppaError("Не найдено"); });
const g = await updateGoal(db, p.id, goal_id, { title, description, status });
return `Goal #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
},
);
tool("list_epics", "List open epics of a project: labels that group stories (like GitHub labels/milestones).", { project: projectArg }, true, listEpicsText);
tool("create_epic", "Create an epic in a project: a label that groups stories.", createEpicShape, false, createEpicText);
tool("update_epic", "Edit an epic: title, description and/or status (open, done, archived — hidden from the board filter). Its stories are not changed.", { project: projectArg, epic_id: z.number().int(), ...epicPatch }, false, updateEpicText);
tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, true, listEpicsText);
tool("create_goal", "Alias of create_epic (goals were renamed to epics).", createEpicShape, false, createEpicText);
tool("update_goal", "Alias of update_epic with goal_id (goals were renamed to epics).", { project: projectArg, goal_id: z.number().int(), ...epicPatch }, false, updateEpicText);
tool(
"create_project",
@ -168,7 +160,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
{
name: z.string().trim().min(2).describe("Human name, e.g. Payments"),
slug: z.string().describe("Repo name: a-z, 0-9, dashes"),
key: z.string().describe("Task key prefix, 2–10 letters/digits, e.g. PAY"),
key: z.string().describe("Story key prefix, 2–10 letters/digits, e.g. PAY"),
owner: z.string().optional().describe("Gitea namespace: your login (default) or an org"),
existing: z.boolean().optional().describe("Connect an existing repo owner/slug instead of creating one"),
visibility: z.enum(["private", "public"]).optional().describe("New repo visibility (default private: only the namespace owner/org members with access, peppa-bot and project members see it)"),
@ -187,7 +179,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"list_tasks",
"List tasks 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.",
{ project: projectArg, column: z.enum(COLUMNS).optional() },
true,
async ({ project, column }) => {
@ -196,43 +188,51 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
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 ? ` (goal #${t.goalId})` : ""} ${t.title}`));
out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`));
}
return out.join("\n");
},
);
tool("get_task", "Get a task: description, goal, status, OpenSpec change, PM questions, progress.", { task: taskArg }, true, async ({ task }) => {
tool("get_task", "Get a story: description, epic, status, OpenSpec change, PM questions, progress, CI checks.", { task: taskArg }, true, async ({ task }) => {
const ref = await ownedTask(task);
return `${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`;
});
tool(
"create_task",
"Create a task in a project (lands in Backlog). Link it to a goal when possible.",
{ project: projectArg, title: z.string().min(3), description: z.string().optional(), goal_id: z.number().int().optional() },
"Create a story in a project (lands in Backlog). Label it with an epic when one fits.",
{
project: projectArg,
title: z.string().min(3),
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"),
},
false,
async ({ project, title, description, goal_id }) => {
async ({ project, title, description, epic_id, goal_id }) => {
const p = await ownedProject(project);
const ref = await createTask(db, { projectId: p.id, title, description, goalId: goal_id });
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}`;
},
);
tool(
"update_task",
"Edit a task: title, description and/or goal (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 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.",
{
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)"),
goal_id: z.number().int().nullable().optional().describe("Move to this goal of the same project; null detaches the task from its goal"),
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"),
},
false,
async ({ task, title, description, goal_id }) => {
if (title === undefined && description === undefined && goal_id === undefined) throw new PeppaError("Nothing to update: pass title, description and/or goal_id");
async ({ task, title, description, epic_id, goal_id }) => {
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");
const ref = await ownedTask(task);
await updateTask(db, ref, { title, description, goalId: goal_id });
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}`;
},
@ -240,7 +240,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"move_task",
"Move a task card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.",
"Move a story card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.",
{ task: taskArg, to: z.enum(COLUMNS), provider: z.enum(["claude", "codex"]).optional().describe("Agent for in_progress (default claude)") },
false,
async ({ task, to, provider }) => {
@ -250,7 +250,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, tasks, who deployed).", { project: projectArg }, true, async ({ project }) => {
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)]);
const head = (["staging", "prod"] as const).map((e) => `${e}: ${cur[e] ? `${cur[e]!.sha.slice(0, 7)}${cur[e]!.host ? ` https://${cur[e]!.host}` : ""}` : "—"}`).join(" · ");
@ -266,7 +266,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
async ({ project }) => {
const p = await ownedProject(project);
const r = await deployProd(db, p, user.login);
return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (tasks ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`;
return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (stories ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`;
},
);
@ -291,7 +291,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"answer_question",
"Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the task's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the task, any other text goes back to the agent.",
"Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the story's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the story, any other text goes back to the agent.",
{ question_id: z.number().int(), answer: z.string().min(1) },
false,
async ({ question_id, answer }) => {
@ -316,7 +316,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"list_incidents",
"Production errors of a project (from Bugsink): id, status (pending = waits for the user's decision), title, where, environment, release, events, task.",
"Production errors of a project (from Bugsink): id, status (pending = waits for the user's decision), title, where, environment, release, events, story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
true,
async ({ project, status }) => {
@ -334,7 +334,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"decide_incident",
"Decide what to do with a production error: backlog (bug task in the backlog), start (bug task + agent starts on it), ignore.",
"Decide what to do with a production error: backlog (bug story in the backlog), start (bug story + agent starts on it), ignore.",
{ id: z.number().int(), action: z.enum(["backlog", "start", "ignore"]) },
false,
async ({ id, action }) => {
@ -346,7 +346,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"resolve_incident",
"Mark a production error fixed (until CI/CD closes them by release). Also resolves it in Bugsink; if it comes back, the incident reopens and its task returns to the backlog.",
"Mark a production error fixed (until CI/CD closes them by release). Also resolves it in Bugsink; if it comes back, the incident reopens and its story returns to the backlog.",
{ id: z.number().int(), release: z.string().optional().describe("Release (commit SHA) with the fix, if known") },
false,
async ({ id, release }) => {
@ -356,7 +356,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
tool("get_incident_policy", "A project's incident policy: what happens to a new production error, triage prompt, environments, daily task limit, ignore pattern.", { project: projectArg }, true, async ({ project }) => {
tool("get_incident_policy", "A project's incident policy: what happens to a new production error, triage prompt, environments, daily story limit, ignore pattern.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const s = await getIncidentSettings(db, p.id);
if (!s) return "Error tracking is not connected for this project.";
@ -364,14 +364,14 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
`Policy: ${s.policy} — ${POLICY_RU[s.policy]}`,
`Triage prompt: ${s.triagePrompt ?? "—"}`,
`Environments: ${s.environments.join(", ")}`,
`Daily task limit: ${s.dailyLimit}`,
`Daily story limit: ${s.dailyLimit}`,
`Ignore pattern: ${s.ignorePattern ?? "—"}`,
].join("\n");
});
tool(
"set_incident_policy",
"Change what happens to new production errors: notify (Telegram only), backlog (bug task, default), start (bug task + agent), ask (Telegram buttons), triage (a triage agent decides by triage_prompt — the user's own words on how to decide; falls back to ask when unsure).",
"Change what happens to new production errors: notify (Telegram only), backlog (bug story, default), start (bug story + agent), ask (Telegram buttons), triage (a triage agent decides by triage_prompt — the user's own words on how to decide; falls back to ask when unsure).",
{
project: projectArg,
policy: z.enum(incidentPolicies).optional(),

View File

@ -126,7 +126,7 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str
"- команды проверок — в `.peppa/project.json` → `checks` (`install`, `lint`, `typecheck`, `test`, `build`); пустая команда = шаг пропущен.",
"- деплой (preview на PR, staging на мерж, прод по кнопке PM) — `.peppa/project.json` → `deploy` + `Dockerfile` (заготовки в `deploy/`); без `deploy` шаг пропускается.",
"",
"Заполнить `checks` — первая задача агента в проекте. Изменение конвейера требует ревью PM.",
"Заполнить `checks` — первая стори агента в проекте. Изменение конвейера требует ревью PM.",
].join("\n"),
}));
return { ...setup, prUrl: pr.html_url };

101
packages/runner/src/code.ts Normal file
View File

@ -0,0 +1,101 @@
// Project page tabs «Код» and «PR» (PEP-66): what the repo holds right now, asked from Gitea
// with the same clients as describeRepo (owner first, then peppa-bot), cached for a minute,
// never failing the page.
import { taskCiSummary, taskForCheck, type CiSummary, type GiteaClient, type Project } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { repoAdmins } from "./share.ts";
const TIMEOUT_MS = 5000;
const CACHE_MS = 60_000;
const cache = new Map<string, { at: number; value: unknown }>();
export interface RepoOverview {
url: string;
defaultBranch: string | null;
readme: { path: string; text: string } | null;
branches: Array<{ name: string; sha: string; message: string; date: string | null }>;
commits: Array<{ sha: string; message: string; author: string; date: string; url: string }>;
/** Set when Gitea could not be asked: the tab shows the link and this message. */
error: string | null;
}
export interface OpenPull {
number: number;
title: string;
url: string;
branch: string;
/** Story of the PR (branch `task/<KEY>-<n>` or the story's pr_url) and its checks. */
task: { key: string; title: string; status: string; ci: CiSummary } | null;
}
/** Asks Gitea with the first client that answers in time; `null` if none did. */
async function withRepoClient<T>(db: Db, project: Project, ask: (c: GiteaClient) => Promise<T>): Promise<T | null> {
for (const c of await repoAdmins(db, project)) {
const timeout = new Promise<null>((r) => setTimeout(() => r(null), TIMEOUT_MS).unref());
const v = await Promise.race([ask(c), timeout]).catch(() => null);
if (v !== null) return v;
}
return null;
}
async function cached<T extends { error?: string | null }>(key: string, fresh: boolean | undefined, load: () => Promise<T>): Promise<T> {
const hit = cache.get(key);
if (!fresh && hit && Date.now() - hit.at < CACHE_MS) return hit.value as T;
const value = await load();
if (!value.error) cache.set(key, { at: Date.now(), value });
return value;
}
const firstLine = (s: string) => s.split("\n")[0]!.trim();
/** README of the default branch, branches and the latest commits («Код»). */
export function repoOverview(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<RepoOverview> {
const url = `${loadEnv().GITEA_URL}/${project.giteaOwner}/${project.giteaRepo}`;
return cached(`code:${project.id}`, opts.fresh, async () => {
const o = project.giteaOwner;
const r = project.giteaRepo;
const got = await withRepoClient(db, project, async (c) => {
const repo = await c.getRepo(o, r);
if (!repo) return { missing: true as const };
if (repo.empty) return { missing: false as const, repo, readme: null, branches: [], commits: [] };
const ref = repo.default_branch || "main";
const [readme, branches, commits] = await Promise.all([c.readme(o, r, ref), c.listBranches(o, r), c.listCommits(o, r, ref, 10)]);
return { missing: false as const, repo, readme, branches, commits };
});
if (!got) return { url, defaultBranch: null, readme: null, branches: [], commits: [], error: "Gitea сейчас не отвечает" };
if (got.missing) return { url, defaultBranch: null, readme: null, branches: [], commits: [], error: "Репозиторий не найден в Gitea" };
const def = got.repo.default_branch || "main";
return {
url: got.repo.html_url || url,
defaultBranch: def,
readme: got.readme,
branches: got.branches
.map((b) => ({ name: b.name, sha: b.commit.id, message: firstLine(b.commit.message ?? ""), date: b.commit.timestamp ?? null }))
.sort((a, b) => (a.name === def ? -1 : b.name === def ? 1 : (b.date ?? "").localeCompare(a.date ?? ""))),
commits: got.commits.map((c) => ({ sha: c.sha, message: firstLine(c.commit.message), author: c.author?.login ?? c.commit.author.name, date: c.commit.author.date, url: c.html_url })),
error: null,
};
});
}
/** Open PRs of the repo; a story's PR carries the story and its checks («PR»). */
export async function openPulls(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<{ pulls: OpenPull[]; error: string | null }> {
const listed = await cached(`pulls:${project.id}`, opts.fresh, async () => {
const pulls = await withRepoClient(db, project, (c) => c.listOpenPulls(project.giteaOwner, project.giteaRepo));
return pulls ? { pulls, error: null } : { pulls: [], error: "Gitea сейчас не отвечает" };
});
// Story and checks come from Peppa's own DB on every call: they change faster than a minute.
const pulls: OpenPull[] = [];
for (const p of listed.pulls) {
const ref = await taskForCheck(db, project, p.head.ref, p.number);
pulls.push({
number: p.number,
title: p.title,
url: p.html_url,
branch: p.head.ref,
task: ref ? { key: ref.key, title: ref.task.title, status: ref.task.status, ci: await taskCiSummary(db, ref) } : null,
});
}
return { pulls, error: listed.error };
}

View File

@ -106,7 +106,7 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
}
async function notifyRelease(db: Db, project: Project, rel: Release) {
const tasks = rel.tasks.length ? ` · задачи: ${rel.tasks.join(", ")}` : "";
const tasks = rel.tasks.length ? ` · стори: ${rel.tasks.join(", ")}` : "";
const log = runLink(rel.runUrl);
if (rel.status === "rolled_back" || rel.status === "failed") {
const back = rel.status === "rolled_back" ? ` — возвращён ${short(rel.previousSha)}` : "";

View File

@ -65,7 +65,7 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
*/
export async function acceptTask(db: Db, questionId: number, via: NonNullable<Question["answeredVia"]>): Promise<TaskRef> {
const q = await getQuestion(db, questionId);
if (!q.taskId) throw new PeppaError("Вопрос не привязан к задаче");
if (!q.taskId) throw new PeppaError("Вопрос не привязан к стори");
if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${q.answer}`);
const [t] = await db
.select({ key: projects.key, number: tasks.number })

View File

@ -163,7 +163,7 @@ async function askQuestion(db: Db, s: SessionView, input: HookInput) {
}
const NUDGE = (key: string) =>
`Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда задача готова — PR и update_task(status: review).`;
`Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда стори готова — PR и update_task(status: review).`;
/**
* The agent finished a turn. Pending question → PM already has it. Task in review →
@ -180,7 +180,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
}
const [task] = s.taskId ? await db.select().from(tasks).where(eq(tasks.id, s.taskId)) : [];
if (task?.status === "review") {
await raiseSessionQuestion(db, s, "attention", clip(`✅ ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${text ?? ""}`.trim()));
await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${text ?? ""}`.trim()));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
@ -188,7 +188,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
if (canContinue && working && s.autoNudges < MAX_AUTO_NUDGES) {
await updateSession(db, s.id, { autoNudges: s.autoNudges + 1, status: "running", lastActivityAt: new Date() });
await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 });
return { decision: "block", reason: NUDGE(s.taskKey ?? "задачей") };
return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") };
}
await raiseSessionQuestion(db, s, "attention", clip(text ?? "Сессия закончила ход и ждёт ввода."));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });

View File

@ -117,7 +117,7 @@ async function execute(
}
const today = await autoIncidentTasksToday(db, i.projectId, o.now);
if (today >= s.dailyLimit) {
const limitNote = `Суточный предел задач из ошибок (${s.dailyLimit}) исчерпан — задача не создана${by === "triage" ? `; триажёр предлагал «${ACTION_RU[action]}»: ${reason}` : ""}.`;
const limitNote = `Суточный предел стори из ошибок (${s.dailyLimit}) исчерпан — стори не создана${by === "triage" ? `; триажёр предлагал «${ACTION_RU[action]}»: ${reason}` : ""}.`;
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
return row;
@ -146,7 +146,7 @@ export async function decideIncident(db: Db, incidentId: number, action: "backlo
const i = await getIncident(db, incidentId);
const already = async () => {
const ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
return new PeppaError(ref ? `Уже решено: задача ${ref.key}` : `Уже решено: ${INCIDENT_STATUS_RU[i.status]}`);
return new PeppaError(ref ? `Уже решено: стори ${ref.key}` : `Уже решено: ${INCIDENT_STATUS_RU[i.status]}`);
};
const open: Incident["status"][] = action === "ignore" ? ["new", "open", "pending", "regressed"] : ["new", "open", "pending", "regressed", "ignored"];
if (i.taskId || !open.includes(i.status)) throw await already();

View File

@ -16,3 +16,4 @@ export * from "./triage.ts";
export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./platform-release.ts";
export * from "./code.ts";

View File

@ -96,7 +96,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro
rmSync(tpl, { recursive: true, force: true });
}
if (!existsSync(join(dest, "README.md"))) {
writeFileSync(join(dest, "README.md"), `# ${o.name}\n\nПроект Пеппы. Ключ задач: \`${key}\`. Правила — в [AGENTS.md](AGENTS.md).\n`);
writeFileSync(join(dest, "README.md"), `# ${o.name}\n\nПроект Пеппы. Ключ стори: \`${key}\`. Правила — в [AGENTS.md](AGENTS.md).\n`);
}
mkdirSync(join(dest, ".peppa"), { recursive: true });
if (!existsSync(join(dest, ".peppa/project.json"))) {

View File

@ -49,7 +49,7 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider });
const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
const prompt = [`Работай над задачей ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n");
const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n");
return launch(db, await getSession(db, session.id), cwd, { ...opts, prompt });
}
@ -68,7 +68,7 @@ export async function resumeSession(db: Db, sessionId: number, opts: StartOption
const cwd = realpathSync(project!.workspacePath);
if (s.provider === "claude") trustWorkspace(cwd);
const prompt = [
`Продолжай работу${s.taskKey ? ` над задачей ${s.taskKey}` : ""}: сессия была прервана. Сверься с peppa.get_task и tasks.md.`,
`Продолжай работу${s.taskKey ? ` над стори ${s.taskKey}` : ""}: сессия была прервана. Сверься с peppa.get_task и tasks.md.`,
opts.prompt,
]
.filter(Boolean)

View File

@ -23,9 +23,9 @@ export function triagePrompt(project: Pick<Project, "key" | "name">, i: Incident
return [
"Ты — триажёр ошибок софтвейр-фабрики Пеппа. Новая ошибка пришла из работающего продукта.",
"Реши, что с ней делать, строго по правилам PM ниже. Варианты:",
'- "start" — завести задачу и сразу отдать агенту;',
'- "backlog" — завести задачу в бэклог;',
'- "notify" — только сообщить PM, задачу не заводить;',
'- "start" — завести стори и сразу отдать агенту;',
'- "backlog" — завести стори в бэклог;',
'- "notify" — только сообщить PM, стори не заводить;',
'- "ignore" — игнорировать;',
'- "ask" — спросить PM (если правила не дают ясного ответа).',
"",

View File

@ -156,7 +156,7 @@ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: stri
await expireSessionQuestions(db, s.id, "(лимит сброшен — раннер продолжил сам)");
const alive = (await tmux.hasSession(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
if (alive) {
await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "задачей"} с того места, где остановился (tasks.md).`);
await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "стори"} с того места, где остановился (tasks.md).`);
await updateSession(db, s.id, { ...counters, status: "running", lastActivityAt: now });
} else {
await updateSession(db, s.id, counters);

View File

@ -383,6 +383,32 @@ export class MockGitea {
return { status: 201, body: {} };
}
if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) };
if (method === "GET" && sub === "branches") {
const out = execFileSync("git", ["--git-dir", r.path, "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(authorname)%09%(committerdate:iso-strict)%09%(contents:subject)", "refs/heads"], { encoding: "utf8" }).trim();
return {
status: 200,
body: out ? out.split("\n").map((l) => {
const [name, id, author, timestamp, message] = l.split("\t");
return { name, commit: { id, message, timestamp, author: { name: author } } };
}) : [],
};
}
if (method === "GET" && sub === "commits") {
const ref = q.get("sha") ?? "main";
let out = "";
try {
out = execFileSync("git", ["--git-dir", r.path, "log", `-${Number(q.get("limit") ?? 30)}`, "--format=%H%x09%an%x09%aI%x09%s", ref], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
} catch {
return { status: 404, body: { message: "ref not found" } };
}
return {
status: 200,
body: out ? out.split("\n").map((l) => {
const [sha, name, date, message] = l.split("\t");
return { sha, html_url: `${this.url}/${r.owner}/${r.name}/commit/${sha}`, commit: { message, author: { name, date } }, author: null };
}) : [],
};
}
if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) {
try {
const text = execFileSync("git", ["--git-dir", r.path, "show", `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });

View File

@ -241,7 +241,7 @@ describe("Политика инцидентов проекта", () => {
assert.ok(t.description!.includes(i.url!));
assert.match(t.description!, /Условия готовности/);
const m = await waitPm("TypeError: amount is undefined", (x) => x.text.includes(t.key));
assert.match(m.text, /Задача в бэклоге/);
assert.match(m.text, /Стори в бэклоге/);
assert.ok(m.text.includes(`http://peppa.test/t/${t.key}`));
});
@ -371,7 +371,7 @@ describe("Политика инцидентов проекта", () => {
assert.equal(i.taskId, null);
assert.equal((await tasksOf(c)).filter((t) => t.title.startsWith("Ошибка:")).length, 5);
const m = await waitPm("TypeError: limit 6");
assert.match(m.text, /Суточный предел задач из ошибок \(5\) исчерпан/);
assert.match(m.text, /Суточный предел стори из ошибок \(5\) исчерпан/);
assert.equal(buttons(m).length, 3);
// The PM's own decision isn't capped.
const r = await runner.decideIncident(db, i.id, "backlog", "mock-pm");

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_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "update_goal", "update_task"]);
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_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", "update_epic", "update_goal", "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);
@ -154,7 +154,7 @@ describe("update_task over MCP", () => {
const r3 = await call("update_task", { task: ref.key, title: "Оба поля", description: "оба описания" });
assert.match(r3.text, /Оба поля/);
assert.match(r3.text, /оба описания/);
assert.match(r3.text, /Цель: #\d+ Цель для правки/);
assert.match(r3.text, /Эпик: #\d+ Цель для правки/);
assert.deepEqual(await snapshot(), { title: "Оба поля", description: "оба описания", goalId: goal.id, status: "backlog", sessions: 0 });
assert.ok((await call("update_task", { task: ref.key })).isError, "nothing to update");
@ -171,7 +171,7 @@ describe("update_task over MCP", () => {
describe("goals, task goal and project creation over MCP", () => {
test("server instructions explain the model", async () => {
const { client } = await mcpAs(owner);
assert.match(client.getInstructions() ?? "", /project .*goals .*tasks/s);
assert.match(client.getInstructions() ?? "", /project .*epics .*stories/s);
});
test("create/update goals; move a task between goals and detach; foreign goal refused", async () => {
@ -179,14 +179,14 @@ describe("goals, task goal and project creation over MCP", () => {
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const { call } = await mcpAs(owner);
const g1 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
const g2 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
const g1 = Number(/epic #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
const g2 = Number(/epic #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
assert.match((await call("list_goals", { project: p.key })).text, /Цель один[\s\S]*Цель два/);
assert.match((await call("update_goal", { project: p.key, goal_id: g1, title: "Цель первая" })).text, /Цель первая \[open\]/);
const t = await call("create_task", { project: p.key, title: "Задача в цели", goal_id: g1 });
const key = /Created (\S+):/.exec(t.text)![1]!;
assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Цель: #\d+ Цель два/);
assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Эпик: #\d+ Цель два/);
const moved = (await core.resolveTask(db, key)).task;
assert.equal(moved.goalId, g2);
assert.equal(moved.title, "Задача в цели");
@ -203,6 +203,41 @@ describe("goals, task goal and project creation over MCP", () => {
assert.doesNotMatch((await call("list_goals", { project: p.key })).text, /Цель первая/);
});
test("Scenario: Новый эпик и стори в нём; Эпик завершён; Алиас цели; Перенос в другой эпик; Эпик чужого проекта", async () => {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const { call, client } = await mcpAs(owner);
const createTask = (await client.listTools()).tools.find((t) => t.name === "create_task");
assert.match(createTask?.description ?? "", /story/i, "tool name stays, the text speaks of stories");
const a = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Оплата картой", description: "Приём оплат" })).text)![1]);
assert.ok((await call("create_epic", { project: p.key, title: "Б" })).isError, "title of at least 3 chars");
const b = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Эпик Б" })).text)![1]);
const t = await call("create_task", { project: p.key, title: "Форма оплаты", epic_id: a });
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.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}\\)`));
const r = await call("update_task", { task: key, epic_id: b });
assert.match(r.text, /Эпик: #\d+ Эпик Б/);
assert.equal((await core.resolveTask(db, key)).task.status, "backlog");
assert.match((await call("get_task", { task: key })).text, /Эпик: #\d+ Эпик Б/);
const other = await project({ turns: [] });
const foreign = await core.createEpic(db, (await core.getProject(db, other.key)).id, "Чужой эпик");
assert.ok((await call("update_task", { task: key, epic_id: foreign.id })).isError);
assert.ok((await call("create_task", { project: p.key, title: "С чужим эпиком", epic_id: foreign.id })).isError);
assert.equal((await core.resolveTask(db, key)).task.goalId, b);
assert.match((await call("update_epic", { project: p.key, epic_id: a, status: "done" })).text, /\[done\]/);
assert.doesNotMatch((await call("list_epics", { project: p.key })).text, /Оплата картой/);
assert.ok((await call("update_epic", { project: p.key, epic_id: a })).isError, "nothing to update");
});
test("create_project through MCP, owned by the user", async () => {
const { MockGitea } = await import("../src/mock-gitea.ts");
const { mkdtempSync } = await import("node:fs");

View File

@ -0,0 +1,155 @@
// PEP-66: project page tabs «Код», «Спеки», «PR» (mock-gitea + real git) and epics in core.
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { core, db, runner, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
const TMP = mkdtempSync(join(tmpdir(), "peppa-tabs-"));
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(TMP, "gitea"));
const ALICE = { id: 71, login: "mock-tabs-alice", token: "mock-token-tabs-alice" };
const BOT = { id: 72, login: "peppa-bot", token: "mock-token-tabs-bot" };
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(ALICE);
gitea.addUser(BOT);
alice = await core.upsertUserFromGitea(db, ALICE, { access_token: ALICE.token });
});
after(async () => {
await gitea.stop();
await teardown();
});
/** A project on a mock repo; the working copy holds .peppa/project.json (checks) and specs. */
async function tabsProject(key: string, files: Record<string, string> | null, workspace: Record<string, string> = {}) {
const slug = `mock-tabs-${key.toLowerCase()}`;
if (files) gitea.addRepo(ALICE.login, slug, { files, admins: [ALICE.login] });
const ws = join(TMP, "ws", slug);
for (const [f, text] of Object.entries(workspace)) {
mkdirSync(join(ws, f, ".."), { recursive: true });
writeFileSync(join(ws, f), text);
}
mkdirSync(ws, { recursive: true });
return core.createProject(db, { slug, key, name: `Mock ${key}`, giteaOwner: ALICE.login, workspacePath: ws, ownerId: alice.id });
}
describe("Вкладка «Код»", () => {
test("Scenario: Репозиторий с кодом — README, ветки main и task/…, последний коммит main", async () => {
const p = await tabsProject("MTCODE", { "README.md": "# Pay\n\nПлатежи.", "src/index.ts": "export {};\n" });
gitea.commit(ALICE.login, p.giteaRepo, "main", { "src/pay.ts": "export const pay = 1;\n" }, "Оплата картой");
gitea.commit(ALICE.login, p.giteaRepo, "task/MTCODE-3", { "src/form.ts": "export {};\n" }, "MTCODE-3: форма");
const code = await runner.repoOverview(db, p, { fresh: true });
assert.equal(code.error, null);
assert.equal(code.defaultBranch, "main");
assert.match(code.readme!.text, /^# Pay/);
assert.equal(code.readme!.path, "README.md");
assert.deepEqual(code.branches.map((b) => b.name), ["main", "task/MTCODE-3"], "default branch first");
assert.equal(code.commits[0]!.message, "Оплата картой");
assert.equal(code.commits[0]!.sha, gitea.sha(ALICE.login, p.giteaRepo, "main"));
assert.equal(code.commits.length, 2);
assert.equal(code.url, `${gitea.url}/${ALICE.login}/${p.giteaRepo}`);
});
test("Scenario: Gitea недоступна — ссылка на репозиторий и «Gitea сейчас не отвечает», без исключения", async () => {
const p = await tabsProject("MTDOWN", { "README.md": "# Down" });
const url = process.env.GITEA_URL;
process.env.GITEA_URL = "http://127.0.0.1:9";
try {
const code = await runner.repoOverview(db, p, { fresh: true });
assert.equal(code.error, "Gitea сейчас не отвечает");
assert.equal(code.url, `http://127.0.0.1:9/${ALICE.login}/${p.giteaRepo}`);
assert.equal(code.readme, null);
assert.equal((await runner.openPulls(db, p, { fresh: true })).error, "Gitea сейчас не отвечает");
} finally {
process.env.GITEA_URL = url;
}
// A failure is not cached: the next call asks Gitea again.
assert.equal((await runner.repoOverview(db, p)).error, null);
});
test("репозиторий без README и пустой репозиторий", async () => {
const p = await tabsProject("MTNORD", { "src/a.ts": "1" });
const code = await runner.repoOverview(db, p, { fresh: true });
assert.equal(code.readme, null);
assert.equal(code.error, null);
const missing = await tabsProject("MTMISS", null);
assert.equal((await runner.repoOverview(db, missing, { fresh: true })).error, "Репозиторий не найден в Gitea");
});
});
describe("Вкладка «PR»", () => {
test("Scenario: PR стори — ключ стори и «Проверки: 2 из 2 пройдены»; PR без стори — без проверок", async () => {
const p = await tabsProject("MTPR", { "README.md": "# PR" }, { ".peppa/project.json": JSON.stringify({ key: "MTPR", checks: { test: "pnpm test", build: "pnpm build" } }) });
const ref = await core.createTask(db, { projectId: p.id, title: "Форма оплаты" });
const sha = gitea.commit(ALICE.login, p.giteaRepo, `task/${ref.key}`, { "f.ts": "1" });
gitea.openPull(ALICE.login, p.giteaRepo, `task/${ref.key}`, `${ref.key}: форма оплаты`);
gitea.commit(ALICE.login, p.giteaRepo, "chore/deps", { "g.ts": "1" });
gitea.openPull(ALICE.login, p.giteaRepo, "chore/deps", "Обновить зависимости");
for (const check of ["test", "build"]) await core.upsertCheckRun(db, p, ref.task.id, { sha, check, state: "success", branch: `task/${ref.key}` });
const { pulls, error } = await runner.openPulls(db, p, { fresh: true });
assert.equal(error, null);
assert.equal(pulls.length, 2);
const story = pulls.find((x) => x.branch === `task/${ref.key}`)!;
assert.equal(story.task?.key, ref.key);
assert.equal(story.task?.ci.label, "Проверки: 2 из 2 пройдены");
assert.match(story.url, /\/pulls\/1$/);
assert.equal(pulls.find((x) => x.branch === "chore/deps")!.task, null);
});
test("Scenario: Открытых PR нет", async () => {
const p = await tabsProject("MTNOPR", { "README.md": "# none" });
assert.deepEqual(await runner.openPulls(db, p, { fresh: true }), { pulls: [], error: null });
});
});
describe("Вкладка «Спеки»", () => {
const SPEC = "# web-auth Specification\n\n## Purpose\nВход в веб через Gitea.\n\n## Requirements\n\n### Requirement: Вход\nтекст\n\n#### Scenario: a\n- **WHEN** x\n\n### Requirement: Выход\nтекст\n";
test("Scenario: Есть спеки — имя, назначение и число требований", async () => {
const p = await tabsProject("MTSPEC", null, { "openspec/specs/web-auth/spec.md": SPEC, "openspec/specs/billing/spec.md": "# billing\n\n## Purpose\nTBD - created by archiving change x.\n\n## Requirements\n\n### Requirement: Счёт\n" });
const specs = core.listSpecs(p);
assert.deepEqual(specs.map((s) => [s.name, s.purpose, s.requirements]), [
["billing", "", 1],
["web-auth", "Вход в веб через Gitea.", 2],
]);
assert.match(specs[1]!.text, /### Requirement: Выход/);
});
test("Scenario: Спек нет — пустой список", async () => {
const p = await tabsProject("MTNOSP", null);
assert.deepEqual(core.listSpecs(p), []);
});
});
describe("Эпики (цели как метки стори)", () => {
test("Scenario: Новая стори в эпике; Стори без эпика; Эпик в архив — стори не меняется", async () => {
const p = await tabsProject("MTEPIC", null);
const epic = await core.createEpic(db, p.id, "Оплата картой", "Приём оплат");
const withEpic = await core.createTask(db, { projectId: p.id, title: "Форма оплаты", goalId: epic.id });
const without = await core.createTask(db, { projectId: p.id, title: "Без эпика" });
assert.equal(withEpic.task.goalId, epic.id);
assert.equal(without.task.goalId, null);
assert.deepEqual((await core.listEpics(db, p.id)).map((e) => e.title), ["Оплата картой"]);
assert.match((await import("../../mcp/src/format.ts")).formatTask(await core.getTaskDetails(db, withEpic)), /## Эпик #\d+: Оплата картой\n\nПриём оплат/);
await core.updateEpic(db, p.id, epic.id, { status: "archived" });
assert.deepEqual(await core.listEpics(db, p.id), []);
assert.equal((await core.resolveTask(db, withEpic.key)).task.goalId, epic.id, "the story keeps its epic");
});
test("эпик чужого проекта не ставится на стори", async () => {
const a = await tabsProject("MTEPA", null);
const b = await tabsProject("MTEPB", null);
const foreign = await core.createEpic(db, b.id, "Чужой");
await assert.rejects(core.createTask(db, { projectId: a.id, title: "x", goalId: foreign.id }));
});
});