peppa/packages/mcp/src/format.ts
2026-11-15 19:57:05 +05:00

114 lines
9.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { agentAutonomyNote, describeBudget, fmtCost, fmtHours, fmtPct, fmtTokens, PROVIDER_NAMES, type MetricsBucket, type ProjectMetrics, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
const NEXT_STEP: Record<TaskStatus, string> = {
backlog: "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → если нет архитектурных решений, сразу update_task(status: in_progress) и Apply в этом же ходе.",
proposing: "Допиши артефакты, `openspec validate`, затем сразу Apply (update_task status: in_progress). Технические решения принимай сам и пиши в design.md — PM их не одобряет.",
awaiting_approval: "Ты запросил одобрение архитектурного решения. Ничего не реализуй — жди ответа PM, закончи ход.",
in_progress: "Apply: продолжай с первого невыполненного пункта tasks.md (workflow openspec-apply-change), report_progress по ходу. В конце — archive, PR, update_task(status: review).",
review: "Стори в ревью у PM. Если в вопросах ниже есть замечания — доделай их; иначе ничего не делай.",
done: "Стори завершена — ничего делать не нужно.",
blocked: "Стори заблокирована — выясни причину в вопросах ниже или продуктовый вопрос — ask_pm простыми словами, не жди ответа.",
};
export function formatTask(d: TaskDetails): string {
const { task, goal } = d;
const lines = [
`# ${d.key}: ${task.title}`,
"",
`- Проект: ${d.project.name} (${d.project.key})`,
`- Статус: **${task.status}**`,
`- Эпик: ${goal ? `#${goal.id} ${goal.title}` : "—"}`,
`- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`,
];
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
if (d.preview?.issueUrl) lines.push(`- Issue Gitea: ${d.preview.issueUrl}`);
if (d.preview?.previewUrl) lines.push(`- Превью: ${d.preview.previewUrl}${d.preview.screenshots.length ? ` (скриншотов: ${d.preview.screenshots.length})` : ""}`);
if (task.archivedAt) lines.push(`- В архиве с ${task.archivedAt.toISOString().slice(0, 10)} (не видна на доске, диспетчер её не берёт)`);
if (d.blockers?.length) {
const open = d.blockers.filter((b) => b.open);
lines.push(`- Ждёт: ${d.blockers.map((b) => `${b.key} [${b.status}]${b.open ? "" : " ✓"}`).join(", ")}${open.length ? " — заблокирована, пока они не в review/done" : " — разблокирована"}`);
}
if (d.dependents?.length) lines.push(`- Её ждут: ${d.dependents.map((t) => `${t.key} [${t.status}]`).join(", ")}`);
lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`);
for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`);
if (d.review) {
lines.push(`- ${reviewLabel(d.review)} (коммит ${d.review.sha.slice(0, 7)})`);
if (d.review.verdict === "changes") lines.push(formatFindings(d.review.findings).replace(/^/gm, " "));
}
// PEP-43/5: spend against the budget («≈» = estimated cost, «∞» = no limit).
lines.push(`- Расход: ${describeBudget(d.budget)}${d.budget.source === "none" ? " (бюджета нет)" : d.budget.source === "project" ? " (бюджет проекта)" : ""}`);
if (d.budget.paused) lines.push(" - ⏸ Бюджет исчерпан: стори на паузе до решения PM — закончи ход.");
lines.push("", "## Описание", "", task.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");
for (const q of d.questions) {
lines.push("", `- [${q.kind} #${q.id}] ${q.text}`, q.answer ? ` - Ответ (${q.answeredVia}): ${q.answer}` : " - _ожидает ответа_");
}
}
// PEP-112: what the owner still has to give before the product is real.
if (d.needs?.length) {
lines.push("", "## Чтобы продукт работал по-настоящему (declare_needs)");
for (const n of d.needs) lines.push(`- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}${n.story ? ` · ${n.story}` : ""}`);
if (d.needs.some((n) => n.open)) lines.push("", "Пока пункт открыт, продукт работает на моке — не называй стори готовой молча.");
}
// PEP-32: the PM's comments on the story — instructions to take into account.
if (d.comments?.length) {
lines.push("", "## Комментарии PM");
for (const c of d.comments.slice(-10)) lines.push("", `- ${c.createdAt.toISOString().slice(0, 16).replace("T", " ")} ${c.login}: ${c.text.replace(/\n/g, "\n ")}`);
}
const progress = d.recentEvents.filter((e) => e.type === "progress");
if (progress.length) {
lines.push("", "## Последний прогресс");
for (const e of progress.slice(-5)) lines.push(`- ${e.createdAt.toISOString().slice(0, 16)} ${(e.payload as { text: string }).text}`);
}
// PEP-23: the project's autonomy changes the next step (PM approves every proposal).
const pmApproves = d.autonomy?.proposal === "pm" && (task.status === "backlog" || task.status === "proposing");
const next = pmApproves
? "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → в этом проекте PM одобряет каждый proposal: request_approval и конец хода. Apply — только после одобрения."
: NEXT_STEP[task.status];
lines.push("", "## Следующий шаг", "", next);
const note = d.autonomy ? agentAutonomyNote(d.autonomy) : null;
if (note) lines.push("", "## Автономность проекта", "", note);
return lines.join("\n");
}
/** A production error (PEP-58) as agents and the PM see it. */
export function formatIncident(i: Incident): string {
const fmt = (d: Date) => `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
const lines = [
`- Инцидент #${i.id} [${i.status} — ${INCIDENT_STATUS_RU[i.status]}]: ${i.title}`,
`- Место: ${i.culprit ?? "—"}`,
`- Источник: ${i.source}, окружение: ${i.environment ?? "—"}, уровень: ${i.level ?? "—"}`,
`- Релиз: ${i.lastRelease ?? "—"}${i.firstRelease && i.firstRelease !== i.lastRelease ? ` (впервые в ${i.firstRelease})` : ""}`,
`- Событий: ${i.events}; впервые ${fmt(i.firstSeen)}, последний раз ${fmt(i.lastSeen)}`,
];
if (i.regressions) lines.push(`- Возвращалась: ${i.regressions} раз`);
if (i.resolvedAt) lines.push(`- Отмечена исправленной: ${fmt(i.resolvedAt)}${i.resolvedRelease ? ` в релизе ${i.resolvedRelease}` : ""}`);
if (i.decision) lines.push(`- Решение: ${i.decision} (${i.decidedBy})${i.decisionReason ? ` — ${i.decisionReason}` : ""}`);
if (i.url) lines.push(`- Bugsink: ${i.url}`);
lines.push("", "Верх стека (внутренний кадр первым):", "", "```", i.stack ?? "(стек недоступен — смотри Bugsink)", "```");
return lines.join("\n");
}
/** PEP-47: factory metrics as text for the remote MCP. */
export function formatMetrics(m: ProjectMetrics): string {
const line = (b: MetricsBucket) =>
`готово ${b.done} · цикл (медиана) ${fmtHours(b.cycleHoursMedian)} · с первого раза ${fmtPct(b.firstPassRate)} · возвраты с ревью ${fmtPct(b.reviewReturnRate)} · вопросов на стори ${b.questionsPerStory == null ? "—" : b.questionsPerStory.toFixed(1)} · раннеры ${fmtHours(b.runnerHours)} · ждали PM ${fmtHours(b.pmWaitHours)} · лимитов ${b.limitHits} · ${fmtTokens(b.spend.tokens)} токенов · ${fmtCost(b.spend.usage)}`;
const day = (d: Date) => d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" });
return [
`## Итого за ${m.weeks} нед.`,
line(m.summary),
"",
"## По неделям",
...m.weekly.map((b) => `- ${day(b.from)}: ${line(b)}`),
"",
"## По агентам",
...(m.byProvider.length ? m.byProvider.map((p) => `- ${PROVIDER_NAMES[p.provider as keyof typeof PROVIDER_NAMES] ?? p.provider}: сессий ${p.sessions}, стори ${p.stories}, ${fmtHours(p.hours)}, ${fmtTokens(p.spend.tokens)} токенов, ${fmtCost(p.spend.usage)}`) : ["- нет сессий"]),
"",
"## По эпикам",
...m.byEpic.map((e) => `- ${e.title}: стори ${e.stories} (готово ${e.done}), ${fmtHours(e.spend.minutes / 60)}, ${fmtTokens(e.spend.tokens)} токенов, ${fmtCost(e.spend.usage)}`),
].join("\n");
}