PEP-66: epics (goals as story labels), tabs Код/Спеки/PR, bug settings in ⋯

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 03:21:20 +05:00
parent f9bc156321
commit 328900e254
16 changed files with 710 additions and 204 deletions

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

@ -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

@ -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

@ -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

@ -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 })

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(),

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

@ -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

@ -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"] });