PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens, sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage - PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM: extend x2 / remove limit / stop), start/resume guard, budget on the story card - PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics - PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered, /journal for superadmins, project journal tab, authors in the story feed - Migration 0007_usage_audit; OpenSpec changes archived Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
68ccef697c
commit
14916079bc
@ -43,6 +43,7 @@
|
||||
- **Доска, зависимости, планировщик, палитра (PEP-34/42/52)**: порядок стори = приоритет — `tasks.position` (REAL, общий для проекта; `reorderTask` в core, `reorderBoardTask` в runner/flow.ts с колонкой; `listTasks` идёт по позиции и без архивных); архив `tasks.archived_at` (`archiveTask` останавливает агента; удаления нет); `epicProgress` — «готово/всего». Зависимости — таблица `task_deps` (core/deps.ts: блокирует, пока предшественник не в review/done и не в архиве; циклы и чужие проекты отклоняются); диспетчер PEP-24 и пуш простоя берут `readyBacklog` (runner/autonomy.ts). Планировщик — runner/planner.ts: `planEpic` (`$PEPPA_PLANNER_BIN -p`, `${PEPPA_PLANNER_MODEL:-sonnet}`, через `claudePrint`) → черновик в `settings` `planner.draft:<epicId>` → `applyPlan`; веб `/p/<KEY>/plan/<epicId>`, мок `mock-planner` (`MOCK_PLANNER_SCENARIO`). Веб-экшены — `app/(app)/board-actions.ts`. MCP PM: `reorder_task`, `archive_task`, `set_dependencies`, `plan_epic`, `apply_plan`, `blocked_by` в create/update_task. Палитра ⌘K — `components/CommandPalette.tsx` (данные `GET /api/palette` → `paletteItems` в core, ранжирование `@peppa/shared/palette` — чистый модуль для браузера), горячие клавиши через `data-hotkey-search|item|answer`, список — `lib/shortcuts.ts` и `/help/shortcuts`
|
||||
- **Агент-ревьюер (PEP-26)**: настройка проекта `review_settings` (вкл/выкл, по умолчанию выкл; `max_iterations` = 2; `rules` PM) — веб «⋯ Настройки проекта → Ревьюер». Агент зовёт MCP `update_task(status: review)`, гейт PEP-57 пройден → `requestReview` (runner/reviewer.ts): ставит `code_reviews` (queued, головной SHA PR) и сразу запускает в процессе MCP, агенту — «закончи ход» (стори остаётся `in_progress`; Stop-хук не подгоняет, пока `pendingReview`). Ревью: дифф `GiteaClient.pullDiff` → `$PEPPA_REVIEW_BIN -p --output-format json --model ${PEPPA_REVIEW_MODEL:-sonnet}` (общий запуск `runner/claude-print.ts`, токен пула проекта, как триаж). `changes` → замечания агенту (`sendToSession` или новый раннер), `ok`/ошибка → стори в `review` и «готово к ревью» с резюме (если ход агента ещё идёт — его шлёт Stop-хук с той же заметкой `reviewNote`). Тот же одобренный SHA не ревьюится повторно; после `max_iterations` возвратов — к PM с последними замечаниями. Зависшие/непринятые — `reviewTick` в вачдоге (раз в минуту). Карточка и `get_task` — последнее ревью. PM, двигающий карточку сам, ревьюера не зовёт. Мок `mock-reviewer` (`MOCK_REVIEW_SCENARIO`)
|
||||
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
|
||||
- **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:<id>|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` терпим к вариантам полей — формат live-CLI не сверен, `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:<id>` / `budget.task:<id>` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:<taskId>`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой
|
||||
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
|
||||
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
|
||||
- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже
|
||||
|
||||
@ -3,6 +3,11 @@
|
||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||
import {
|
||||
accountUsageForUser,
|
||||
describeUsage,
|
||||
usageTotals,
|
||||
describeAccount,
|
||||
enterActor,
|
||||
acceptPairing,
|
||||
beat,
|
||||
checkServices,
|
||||
@ -237,8 +242,11 @@ export function createBot(o: BotOptions) {
|
||||
const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
|
||||
const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
|
||||
const lines = [`<b>Активные сессии: ${sessions.length}</b>`];
|
||||
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`);
|
||||
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})${usageTotals(s.usage).hasData ? ` · ${esc(describeUsage(s.usage))}` : ""}`);
|
||||
lines.push("", `<b>Открытых вопросов: ${open.length}</b>`);
|
||||
// PEP-5: subscription limit windows.
|
||||
const accounts = await accountUsageForUser(db, user);
|
||||
lines.push("", "<b>Лимиты</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : ["нет данных о лимитах"]));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
@ -384,6 +392,8 @@ export function createBot(o: BotOptions) {
|
||||
}
|
||||
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
|
||||
if (!user) return "ignored";
|
||||
// PEP-48: what follows is done by this user through Telegram.
|
||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||
|
||||
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
|
||||
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
|
||||
@ -421,6 +431,7 @@ export function createBot(o: BotOptions) {
|
||||
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
|
||||
return "ignored";
|
||||
}
|
||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||
const parts = (c.data ?? "").split(":");
|
||||
if (parts[0] === "d" || parts[0] === "t") {
|
||||
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка"));
|
||||
|
||||
@ -43,13 +43,18 @@ import {
|
||||
listSessions,
|
||||
setProjectRunnerSettings,
|
||||
setTaskRunnerSettings,
|
||||
cleanBudget,
|
||||
logEvent,
|
||||
setProjectBudget,
|
||||
setTaskBudget,
|
||||
type Budget,
|
||||
} from "@peppa/core";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { acceptStory, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner } from "@peppa/runner";
|
||||
import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
@ -78,7 +83,7 @@ async function ownedSession(userId: number, sessionId: number) {
|
||||
}
|
||||
|
||||
export async function answerQuestion(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const q = await getQuestion(db, Number(str(f, "questionId")));
|
||||
await projectForUser(db, user.id, q.projectId);
|
||||
@ -94,7 +99,7 @@ export async function answerQuestion(f: FormData) {
|
||||
}
|
||||
|
||||
export async function addTask(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (!str(f, "title")) throw new PeppaError("Нужно название стори");
|
||||
@ -106,7 +111,7 @@ export async function addTask(f: FormData) {
|
||||
|
||||
/** Epics (PEP-66): labels that group stories; stored in the goals table. */
|
||||
export async function addEpic(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(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("Нужно название эпика");
|
||||
@ -115,7 +120,7 @@ export async function addEpic(f: FormData) {
|
||||
}
|
||||
|
||||
export async function editEpic(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const id = Number(str(f, "epicId"));
|
||||
@ -177,7 +182,7 @@ async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof require
|
||||
}
|
||||
|
||||
export async function startTaskSession(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
@ -246,7 +251,7 @@ export async function setRunnerSettingsAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function stopTaskSession(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||
await stopSession(db, s.id);
|
||||
@ -254,7 +259,7 @@ export async function stopTaskSession(f: FormData) {
|
||||
}
|
||||
|
||||
export async function resumeTaskSession(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||
await resumeSession(db, s.id);
|
||||
@ -262,7 +267,7 @@ export async function resumeTaskSession(f: FormData) {
|
||||
}
|
||||
|
||||
export async function messageSession(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||
if (!str(f, "text")) throw new PeppaError("Пустое сообщение");
|
||||
@ -271,7 +276,7 @@ export async function messageSession(f: FormData) {
|
||||
}
|
||||
|
||||
export async function createProjectAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await provisionProject(db, {
|
||||
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
|
||||
@ -287,7 +292,7 @@ export async function createProjectAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function deployProdAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, (await getProjectByKey(db, str(f, "projectKey"))).id);
|
||||
await deployProd(db, p, user.login);
|
||||
@ -295,7 +300,7 @@ export async function deployProdAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function moveTaskCard(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
@ -306,21 +311,21 @@ export async function moveTaskCard(f: FormData) {
|
||||
}
|
||||
|
||||
export async function revokeConnectedApp(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await revokeApp(db, user.id, str(f, "clientId"));
|
||||
});
|
||||
}
|
||||
|
||||
export async function unlinkEgov(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await linkEgovIin(db, user.id, null);
|
||||
});
|
||||
}
|
||||
|
||||
export async function addProjectMember(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await shareProject(db, user, p, str(f, "login"));
|
||||
@ -329,7 +334,7 @@ export async function addProjectMember(f: FormData) {
|
||||
}
|
||||
|
||||
export async function grantRepoAccessToMembers(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await grantRepoAccess(db, user, p);
|
||||
@ -338,7 +343,7 @@ export async function grantRepoAccessToMembers(f: FormData) {
|
||||
}
|
||||
|
||||
export async function setProjectVisibilityAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await setProjectVisibility(db, p, str(f, "visibility") === "private" ? "private" : "public", { actor: user });
|
||||
@ -347,7 +352,7 @@ export async function setProjectVisibilityAction(f: FormData) {
|
||||
|
||||
/** PEP-23: project autonomy — a preset level, or the individual settings (owner or member). */
|
||||
export async function setAutonomyAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const level = str(f, "level");
|
||||
@ -373,7 +378,7 @@ export async function setAutonomyAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function removeProjectMember(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const login = str(f, "login");
|
||||
@ -384,7 +389,7 @@ export async function removeProjectMember(f: FormData) {
|
||||
}
|
||||
|
||||
export async function pairTelegram(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
|
||||
@ -394,7 +399,7 @@ export async function pairTelegram(f: FormData) {
|
||||
}
|
||||
|
||||
export async function unpairTelegramAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await unpairTelegram(db, user.id);
|
||||
});
|
||||
@ -404,7 +409,7 @@ export async function unpairTelegramAction(f: FormData) {
|
||||
|
||||
/** «Настройки → Уведомления»: events × channels, quiet hours, timezone, digest, sound, projects. */
|
||||
export async function saveNotifyPrefsAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const cur = await getNotifyPrefs(db, user.id);
|
||||
const d = defaultPrefs();
|
||||
@ -434,14 +439,14 @@ export async function saveNotifyPrefsAction(f: FormData) {
|
||||
|
||||
/** The browser subscribed to Web Push (called from the client with PushSubscription.toJSON()). */
|
||||
export async function savePushSubscriptionAction(sub: { endpoint: string; keys: { p256dh: string; auth: string } }, userAgent: string | null) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await savePushSubscription(db, user.id, { ...sub, userAgent });
|
||||
revalidatePath("/settings");
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function deletePushSubscriptionAction(endpoint: string) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await deletePushSubscription(db, user.id, endpoint);
|
||||
revalidatePath("/settings");
|
||||
return { ok: true };
|
||||
@ -449,7 +454,7 @@ export async function deletePushSubscriptionAction(endpoint: string) {
|
||||
|
||||
/** Test notification to this browser, sent right away (doesn't depend on the bot). */
|
||||
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
|
||||
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
|
||||
const prefs = await getNotifyPrefs(db, user.id);
|
||||
@ -469,7 +474,7 @@ async function incidentInProject(userId: number, f: FormData) {
|
||||
}
|
||||
|
||||
export async function connectErrorTrackingAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (p.ownerId !== user.id) throw new PeppaError("Подключает владелец проекта");
|
||||
@ -478,7 +483,7 @@ export async function connectErrorTrackingAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function saveIncidentSettings(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await updateIncidentSettings(db, p.id, {
|
||||
@ -494,7 +499,7 @@ export async function saveIncidentSettings(f: FormData) {
|
||||
// ── reviewer agent (PEP-26) ──────────────────────────────────────────────────────
|
||||
|
||||
export async function saveReviewSettingsAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await setReviewSettings(db, p.id, {
|
||||
@ -506,7 +511,7 @@ export async function saveReviewSettingsAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function decideIncidentAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const i = await incidentInProject(user.id, f);
|
||||
const action = str(f, "action");
|
||||
@ -516,7 +521,7 @@ export async function decideIncidentAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function resolveIncidentAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const i = await incidentInProject(user.id, f);
|
||||
await resolveIncident(db, i.id, { who: user.login, release: str(f, "release") || null });
|
||||
@ -527,7 +532,7 @@ export async function resolveIncidentAction(f: FormData) {
|
||||
|
||||
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
|
||||
async function requireSuperadmin() {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
|
||||
return user;
|
||||
}
|
||||
@ -561,7 +566,7 @@ export async function setUserDisabledAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function changePasswordAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
if (!isLocalUser(user)) throw new PeppaError("Вы входите через Gitea — пароль меняется там");
|
||||
const next = String(f.get("newPassword") ?? "");
|
||||
@ -570,3 +575,29 @@ export async function changePasswordAction(f: FormData) {
|
||||
return "/settings?password=changed";
|
||||
});
|
||||
}
|
||||
|
||||
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
|
||||
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
|
||||
|
||||
export async function saveTaskBudgetAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTaskById(db, Number(str(f, "taskId")));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const mode = str(f, "mode");
|
||||
const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f);
|
||||
await setTaskBudget(db, ref.task.id, budget);
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } });
|
||||
await budgetChanged(db, ref.task.id);
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveProjectBudgetAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const budget = budgetFrom(f);
|
||||
await setProjectBudget(db, p.id, budget);
|
||||
await logEvent(db, { projectId: p.id, type: "project_budget_changed", payload: { budget } });
|
||||
});
|
||||
}
|
||||
|
||||
@ -21,6 +21,8 @@ const TOOLS: Array<[string, string]> = [
|
||||
["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"],
|
||||
["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"],
|
||||
["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"],
|
||||
["get_usage", "лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали"],
|
||||
["get_metrics", "метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"],
|
||||
["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое"],
|
||||
["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"],
|
||||
];
|
||||
@ -123,6 +125,20 @@ export default async function Help() {
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Расход, бюджеты, метрики, журнал">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
<b>Лимиты</b>: полоса над каждой страницей показывает самое загруженное окно лимитов подписки (5 ч и 7 дней) и время сброса — Claude Code сам
|
||||
сообщает их строке статуса раннера. Пока ни один раннер не сообщал — «нет данных о лимитах»; Codex и OpenCode расход не сообщают. На карточке
|
||||
раннера — токены, стоимость и заполненность контекста; «≈» — стоимость оценена по прайсу API, а не сообщена агентом.{" "}
|
||||
<b>Бюджет</b>: «⋯ Настройки проекта» → «Бюджет стори» (по умолчанию для всех стори) или карточка стори (свой бюджет) — минуты раннеров,
|
||||
токены, перезапуски, стоимость; по умолчанию без предела. Превышение прерывает ход агента (разговор сохраняется) и присылает вопрос «Продлить ×2 /
|
||||
Снять лимит / Остановить»; пока вы не ответили, стори не запускается.{" "}
|
||||
<b>Метрики</b>: вкладка «Метрики» проекта — время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, сколько агенты
|
||||
ждали вас, расход по неделям, агентам и эпикам.{" "}
|
||||
<b>Журнал</b>: вкладка «Журнал» проекта и раздел «Журнал» суперадмина — кто что сделал: человек (веб, Telegram, MCP-клиент, CLI), агент или Пеппа.
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="CI/CD">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "}
|
||||
|
||||
35
apps/web/app/(app)/journal/page.tsx
Normal file
35
apps/web/app/(app)/journal/page.tsx
Normal file
@ -0,0 +1,35 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { getProject, isSuperadmin, JOURNAL_NOISE, listJournal, listProjects, type ActorChannel, type ActorKind } from "@peppa/core";
|
||||
import { JournalFilters, JournalList } from "@/components/Accounting";
|
||||
import { PageHeader } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
|
||||
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
|
||||
const me = await requireUser();
|
||||
if (!(await isSuperadmin(db, me))) notFound();
|
||||
const { project, actor, channel, all } = await searchParams;
|
||||
const projects = await listProjects(db);
|
||||
const p = project ? await getProject(db, project).catch(() => null) : null;
|
||||
const entries = await listJournal(db, {
|
||||
projectId: p?.id ?? (project ? -1 : undefined),
|
||||
actorKind: (actor || undefined) as ActorKind | undefined,
|
||||
channel: (channel || undefined) as ActorChannel | undefined,
|
||||
excludeTypes: all ? undefined : JOURNAL_NOISE,
|
||||
limit: 300,
|
||||
});
|
||||
return (
|
||||
<Workspace aside={null}>
|
||||
<PageHeader title="Журнал действий">
|
||||
Кто что сделал: люди (веб, Telegram, MCP-клиенты, CLI, терминал), агенты и сама Пеппа. Новые сверху, последние 300.
|
||||
{!all && " Служебные события хуков скрыты."}
|
||||
</PageHeader>
|
||||
<div className="mb-4">
|
||||
<JournalFilters action="/journal" projects={projects.map((x) => ({ key: x.key, name: x.name }))} value={{ project, actor, channel }} />
|
||||
</div>
|
||||
<JournalList entries={entries} />
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
@ -1,11 +1,12 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { getNotifyPrefs, isSuperadmin } from "@peppa/core";
|
||||
import { accountUsageForUser, getNotifyPrefs, isSuperadmin } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { navCounts } from "@/lib/queries";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import { AttentionBadge } from "@/components/AttentionBadge";
|
||||
import { CommandPalette } from "@/components/CommandPalette";
|
||||
import { UsageStrip } from "@/components/Accounting";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@ -14,11 +15,17 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
const user = await requireUser();
|
||||
const counts = await navCounts(user.id);
|
||||
const { sound } = await getNotifyPrefs(db, user.id);
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
// PEP-5: subscription limit windows over every page.
|
||||
const accounts = await accountUsageForUser(db, user).catch(() => []);
|
||||
return (
|
||||
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
|
||||
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
|
||||
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={await isSuperadmin(db, user)} />
|
||||
<div className="flex min-w-0 flex-col pb-16 md:pb-0">{children}</div>
|
||||
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={superadmin} />
|
||||
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
|
||||
<UsageStrip accounts={accounts} admin={superadmin} />
|
||||
{children}
|
||||
</div>
|
||||
<CommandPalette />
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
|
||||
import { DEFAULT_RUNNER_SETTINGS, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { DEFAULT_RUNNER_SETTINGS, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Board, type Card } from "@/components/Board";
|
||||
@ -22,6 +22,8 @@ import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||||
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
|
||||
import { CodeTab, EpicsPanel, ProgressBar, PullsTab, SpecsTab } from "./tabs";
|
||||
import { setProjectPoolAction } from "../../subscriptions/actions";
|
||||
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
|
||||
import { saveProjectBudgetAction } from "../../actions";
|
||||
|
||||
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
|
||||
deploying: { label: "выкатывается", tone: "info" },
|
||||
@ -39,6 +41,8 @@ const TABS = [
|
||||
{ id: "releases", label: "Релизы" },
|
||||
{ id: "bugs", label: "Баги" },
|
||||
{ id: "sessions", label: "Сессии" },
|
||||
{ id: "metrics", label: "Метрики" },
|
||||
{ id: "journal", label: "Журнал" },
|
||||
] as const;
|
||||
|
||||
function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
|
||||
@ -61,10 +65,10 @@ 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; epic?: string }> }) {
|
||||
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { key } = await params;
|
||||
const { error, created, tab: tabParam, epic: epicParam } = await searchParams;
|
||||
const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel } = await searchParams;
|
||||
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
@ -119,6 +123,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
// 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) : [];
|
||||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||||
const metrics = tab === "metrics" ? await projectMetrics(db, p.id, { weeks: Number(weeks) || 8 }) : null;
|
||||
const journal = tab === "journal" ? await listJournal(db, { projectId: p.id, actorKind: (actor || undefined) as ActorKind | undefined, channel: (channel || undefined) as ActorChannel | undefined, limit: 200 }) : [];
|
||||
const projectBudget = await getProjectBudget(db, p.id);
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
@ -172,6 +180,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<EpicsPanel projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Бюджет стори">
|
||||
<ProjectBudgetPanel projectId={p.id} budget={projectBudget} back={back} action={saveProjectBudgetAction} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Ревьюер">
|
||||
<form action={saveReviewSettingsAction} className="flex flex-col gap-2.5">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
@ -441,6 +453,14 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<IncidentsSection projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
|
||||
)}
|
||||
|
||||
{tab === "metrics" && metrics && <MetricsTab m={metrics} projectKey={p.key} />}
|
||||
|
||||
{tab === "journal" && (
|
||||
<Section title="Журнал действий" actions={<JournalFilters action={`/p/${p.key}`} value={{ tab: "journal", actor, channel }} />}>
|
||||
<JournalList entries={journal} showProject={false} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{tab === "sessions" && (
|
||||
<Section
|
||||
title="Сессии"
|
||||
|
||||
@ -86,10 +86,13 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Button asChild size="sm">
|
||||
<a href="/subscriptions">Подписки</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/journal">Журнал</a>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
Локальные пользователи без Gitea: создать, сбросить пароль, отключить. Подписки агентов и пулы для ротации.
|
||||
Локальные пользователи без Gitea: создать, сбросить пароль, отключить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
|
||||
</Row>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
@ -5,7 +5,7 @@ import { createPool, deletePool, getProject, PeppaError, requireSuperadmin, setP
|
||||
import { addSubscription, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
@ -14,7 +14,7 @@ const BASE = "/subscriptions";
|
||||
|
||||
/** Runs a superadmin action; errors come back as ?error=… (redirect stays outside try). */
|
||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
let target = str(f, "back") || BASE;
|
||||
try {
|
||||
await requireSuperadmin(db, user);
|
||||
@ -31,7 +31,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
}
|
||||
|
||||
export async function addSubscriptionAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const provider = str(f, "provider") as SubscriptionProvider;
|
||||
if (!["claude", "codex", "opencode"].includes(provider)) throw new PeppaError("Неизвестный провайдер");
|
||||
@ -92,7 +92,7 @@ export async function deleteSubscriptionAction(f: FormData) {
|
||||
}
|
||||
|
||||
export async function createPoolAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await createPool(db, { name: str(f, "name"), subscriptionIds: ids(f, "subscription"), createdBy: user.id });
|
||||
return `${BASE}#pools`;
|
||||
|
||||
@ -6,9 +6,13 @@ import { Archive, ArchiveRestore, CircleCheck, CircleX, GitPullRequest, Hourglas
|
||||
import {
|
||||
blockersOf,
|
||||
dependentsOf,
|
||||
actorLabel,
|
||||
FINISHED_SESSION_STATUSES,
|
||||
getTaskRunnerSettings,
|
||||
resolveRunnerSettings,
|
||||
getProjectBudget,
|
||||
listJournal,
|
||||
taskBudgetView,
|
||||
getEpic,
|
||||
isSuperadmin,
|
||||
latestReview,
|
||||
@ -42,7 +46,8 @@ import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { taskActivity, taskForUser } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { editStoryAction, startTaskSession } from "../../actions";
|
||||
import { editStoryAction, saveTaskBudgetAction, startTaskSession } from "../../actions";
|
||||
import { BudgetPanel } from "@/components/Accounting";
|
||||
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
|
||||
import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -96,10 +101,17 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
tasks: progress?.total ? `${progress.done}/${progress.total}` : undefined,
|
||||
comments: openQuestions || undefined,
|
||||
};
|
||||
// PEP-43: spend against the budget; PEP-48: who did each event.
|
||||
const budget = await taskBudgetView(db, task);
|
||||
const projectBudget = await getProjectBudget(db, project.id);
|
||||
const authors = new Map((await listJournal(db, { taskId: task.id, limit: 200 })).map((e) => [e.id, actorLabel(e)]));
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
<ReviewPreview preview={preview} />
|
||||
<PanelSection title="Расход и бюджет">
|
||||
<BudgetPanel view={budget} taskId={task.id} projectBudget={projectBudget} back={back} action={saveTaskBudgetAction} paused={!!budget.paused} />
|
||||
</PanelSection>
|
||||
<PanelSection title="Зависимости">
|
||||
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">Стори ни от чего не зависит.</p>}
|
||||
{blockers.length > 0 && (
|
||||
@ -162,7 +174,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
<p className="m-0 text-sm text-muted-foreground">Событий нет.</p>
|
||||
) : (
|
||||
<>
|
||||
<ActivityTab events={events.slice(0, 8)} />
|
||||
<ActivityTab events={events.slice(0, 8)} authors={authors} />
|
||||
<Link href={tabHref("activity")} className="text-xs text-primary">
|
||||
Вся активность →
|
||||
</Link>
|
||||
@ -360,7 +372,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
{tab === "comments" && <CommentsTab taskKey={ref.key} taskStatus={task.status} questions={[...questions].reverse()} comments={comments} back={back} hasLive={!!live} />}
|
||||
{tab === "tests" && <TestsTab ci={ci} runs={runs} review={review} />}
|
||||
{tab === "merge" && <MergeTab taskKey={ref.key} taskStatus={task.status} prUrl={task.prUrl} pull={gate?.pull ?? null} gate={gate} back={back} />}
|
||||
{tab === "activity" && <ActivityTab events={events} />}
|
||||
{tab === "activity" && <ActivityTab events={events} authors={authors} />}
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
|
||||
@ -370,7 +370,11 @@ export interface ActivityEvent {
|
||||
}
|
||||
|
||||
/** Who did it: a PM by login, the agent of a session, or Peppa itself. */
|
||||
export function eventAuthor(e: ActivityEvent): { label: string; tone: "pm" | "agent" | "system" } {
|
||||
export function eventAuthor(e: ActivityEvent, authors?: Map<number, string | null>): { label: string; tone: "pm" | "agent" | "system" } {
|
||||
// PEP-48: the recorded author (person + channel, agent, Peppa) when the event has one.
|
||||
const kind = (e as { actorKind?: string | null }).actorKind;
|
||||
const recorded = authors?.get(e.id);
|
||||
if (kind && recorded) return { label: recorded, tone: kind === "user" ? "pm" : kind === "agent" ? "agent" : "system" };
|
||||
const login = (e.payload as { login?: unknown } | null)?.login;
|
||||
if (typeof login === "string" && login) return { label: login, tone: "pm" };
|
||||
if (e.sessionId) return { label: `агент · #${e.sessionId}`, tone: "agent" };
|
||||
@ -387,12 +391,12 @@ function changeLine(e: ActivityEvent): string {
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
export function ActivityTab({ events }: { events: ActivityEvent[] }) {
|
||||
export function ActivityTab({ events, authors }: { events: ActivityEvent[]; authors?: Map<number, string | null> }) {
|
||||
if (!events.length) return <Empty>Событий нет.</Empty>;
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col gap-0 border-l p-0 pl-4">
|
||||
{events.map((e) => {
|
||||
const a = eventAuthor(e);
|
||||
const a = eventAuthor(e, authors);
|
||||
return (
|
||||
<li key={e.id} className="relative py-1.5 text-sm [overflow-wrap:anywhere]">
|
||||
<span className={cn("absolute top-3 -left-[1.3rem] size-2 rounded-full", a.tone === "pm" ? "bg-primary" : a.tone === "agent" ? "bg-info" : "bg-muted-foreground")} />
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { enterActor } from "@peppa/core";
|
||||
import { handleGiteaHook } from "@peppa/runner";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
@ -8,6 +9,8 @@ export const dynamic = "force-dynamic";
|
||||
* signed (X-Gitea-Signature, HMAC-SHA256 of the body) with the project's secret.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
// PEP-48: CI results and Gitea events act as Peppa itself.
|
||||
enterActor({ kind: "system", channel: "gitea" });
|
||||
const body = await req.text();
|
||||
const r = await handleGiteaHook(db, {
|
||||
event: req.headers.get("x-peppa-event") ?? req.headers.get("x-gitea-event") ?? "",
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import { getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
|
||||
import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
|
||||
import { createManagerServer } from "@peppa/mcp/manager";
|
||||
import { publicOrigin } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
@ -20,6 +20,8 @@ export async function POST(req: Request) {
|
||||
const auth = await verifyAccessToken(db, token);
|
||||
const user = auth && (await getUser(db, auth.userId));
|
||||
if (!user || !(await isUserAllowed(db, user))) return unauthorized();
|
||||
// PEP-48: everything this request does is done by the user through this OAuth client.
|
||||
enterActor({ kind: "user", userId: user.id, channel: "mcp", clientId: auth.clientId });
|
||||
const server = createManagerServer(db, user, await publicOrigin());
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
||||
await server.connect(transport);
|
||||
|
||||
419
apps/web/components/Accounting.tsx
Normal file
419
apps/web/components/Accounting.tsx
Normal file
@ -0,0 +1,419 @@
|
||||
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { Gauge } from "lucide-react";
|
||||
import {
|
||||
accountPeak,
|
||||
actorLabel,
|
||||
ACTOR_CHANNEL_NAMES,
|
||||
ACTOR_KIND_NAMES,
|
||||
BUDGET_KINDS,
|
||||
BUDGET_LABELS,
|
||||
describeUsage,
|
||||
fmtCost,
|
||||
fmtHours,
|
||||
fmtPct,
|
||||
fmtTokens,
|
||||
formatBudgetValue,
|
||||
PROVIDER_NAMES,
|
||||
usageTotals,
|
||||
type AccountUsage,
|
||||
type Budget,
|
||||
type JournalEntry,
|
||||
type MetricsBucket,
|
||||
type ProjectMetrics,
|
||||
type SessionUsage,
|
||||
type TaskBudgetView,
|
||||
type WindowView,
|
||||
} from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { eventLine } from "@/components/RunnerConsole";
|
||||
import { LocalTime } from "@/components/LocalTime";
|
||||
import { ago, Empty } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const tone = (pct: number) => (pct >= 90 ? "bg-destructive" : pct >= 70 ? "bg-warn" : "bg-primary");
|
||||
|
||||
function Meter({ pct, className }: { pct: number; className?: string }) {
|
||||
return (
|
||||
<span className={cn("relative inline-block h-1.5 w-16 overflow-hidden rounded-full bg-muted align-middle", className)} aria-hidden>
|
||||
<span className={cn("absolute inset-y-0 left-0 rounded-full", tone(pct))} style={{ width: `${Math.max(2, Math.min(100, pct))}%` }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function WindowCell({ label, w }: { label: string; w: WindowView | null }) {
|
||||
if (!w) return null;
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 whitespace-nowrap">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
{w.reset ? (
|
||||
<span className="text-muted-foreground">сброшено</span>
|
||||
) : (
|
||||
<>
|
||||
<Meter pct={w.pct!} />
|
||||
<span className="font-mono tabular-nums">{Math.round(w.pct!)}%</span>
|
||||
{w.resetsAt && (
|
||||
<span className="text-muted-foreground">
|
||||
сброс <LocalTime iso={w.resetsAt.toISOString()} />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function accountTitle(a: AccountUsage): string {
|
||||
const w = (l: string, v: WindowView | null) => (!v ? `${l}: нет данных` : v.reset ? `${l}: сброшено` : `${l}: ${Math.round(v.pct!)}%`);
|
||||
return `${a.name} — ${w("5 ч", a.fiveHour)}, ${w("7 д", a.sevenDay)}${a.limitedUntil ? ", в лимите" : ""}${a.at ? `, обновлено ${a.at.toLocaleString("ru-RU")}` : ""}`;
|
||||
}
|
||||
|
||||
/** PEP-5: thin bar above every page — the most loaded limit window of the user's accounts. */
|
||||
export function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admin: boolean }) {
|
||||
const withData = accounts.filter((a) => a.fiveHour || a.sevenDay || a.limitedUntil);
|
||||
const top = withData[0];
|
||||
const limited = accounts.filter((a) => a.limitedUntil);
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-label="Лимиты подписок"
|
||||
title={accounts.map(accountTitle).join("\n") || undefined}
|
||||
className="flex min-h-8 flex-wrap items-center gap-x-4 gap-y-1 border-b bg-sidebar/40 px-4 py-1 text-xs md:px-8"
|
||||
>
|
||||
<span className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Gauge className="size-3.5" />
|
||||
Лимиты
|
||||
</span>
|
||||
{!top ? (
|
||||
<span className="text-muted-foreground">нет данных о лимитах</span>
|
||||
) : (
|
||||
<>
|
||||
{withData.length > 1 && <span className="font-medium">{top.name}</span>}
|
||||
<WindowCell label="5 ч" w={top.fiveHour} />
|
||||
<WindowCell label="7 д" w={top.sevenDay} />
|
||||
{top.stale && top.at && <span className="text-warn">устарело ({ago(top.at)})</span>}
|
||||
</>
|
||||
)}
|
||||
{limited.map((a) => (
|
||||
<span key={a.key} className="whitespace-nowrap text-destructive">
|
||||
{a.name}: лимит до <LocalTime iso={a.limitedUntil!.toISOString()} />
|
||||
</span>
|
||||
))}
|
||||
{withData.length > 1 && (
|
||||
<span className="text-muted-foreground">
|
||||
+{withData.length - 1} {admin ? <Link href="/subscriptions" className="text-muted-foreground underline-offset-2 hover:text-foreground">подписки</Link> : "аккаунт"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const usagePeakSort = (a: AccountUsage[]) => [...a].sort((x, y) => accountPeak(y) - accountPeak(x));
|
||||
|
||||
/** PEP-5: one line under a runner card. */
|
||||
export function SessionUsageLine({ usage, provider }: { usage: SessionUsage | null; provider: string }) {
|
||||
const t = usageTotals(usage);
|
||||
if (!t.hasData) return <p className="m-0 text-xs text-muted-foreground">Расход: нет данных{provider !== "claude" ? ` (${provider} не сообщает)` : ""}</p>;
|
||||
return (
|
||||
<p className="m-0 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground">
|
||||
<span>Расход: {describeUsage(usage)}</span>
|
||||
{t.context && (
|
||||
<span className="flex items-center gap-1.5">
|
||||
контекст <Meter pct={t.context.pct} className="w-12" /> {fmtTokens(t.context.used)} / {fmtTokens(t.context.size)}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PEP-43: budget ────────────────────────────────────────────────────────────────
|
||||
const spentOf = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? (v.spend.costUsd ?? 0) : v.spend[k]);
|
||||
const spentText = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? fmtCost(v.spend.usage) : formatBudgetValue(k, v.spend[k]));
|
||||
|
||||
export function BudgetFields({ budget, placeholder }: { budget: Budget; placeholder?: Budget }) {
|
||||
const field = (k: (typeof BUDGET_KINDS)[number], label: string, step = "1") => (
|
||||
<label className="flex flex-col gap-1 text-xs text-muted-foreground">
|
||||
{label}
|
||||
<Input
|
||||
type="number"
|
||||
name={k}
|
||||
min={0}
|
||||
step={step}
|
||||
defaultValue={budget[k] ?? ""}
|
||||
placeholder={placeholder?.[k] != null ? String(placeholder[k]) : "∞"}
|
||||
aria-label={label}
|
||||
className="h-8 w-full"
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{field("minutes", "Минуты раннеров")}
|
||||
{field("tokens", "Токены")}
|
||||
{field("restarts", "Перезапуски")}
|
||||
{field("costUsd", "Стоимость, $", "0.01")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise<void>; paused: boolean }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{paused && <p className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-2.5 py-1.5 text-xs text-destructive">Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).</p>}
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0 text-sm">
|
||||
{BUDGET_KINDS.map((k) => {
|
||||
const limit = view.budget[k];
|
||||
const pct = limit ? (spentOf(view, k) / limit) * 100 : null;
|
||||
return (
|
||||
<li key={k} className="flex items-center gap-2">
|
||||
<span className="w-24 shrink-0 text-xs text-muted-foreground">{BUDGET_LABELS[k]}</span>
|
||||
<span className="font-mono text-xs tabular-nums">{spentText(view, k)}</span>
|
||||
<span className="text-xs text-muted-foreground">из {formatBudgetValue(k, limit)}</span>
|
||||
{pct != null && <Meter pct={pct} className="ml-auto w-14" />}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{view.source === "task" ? "Свой бюджет стори." : view.source === "project" ? "Бюджет проекта по умолчанию." : "Без бюджета."} Сессий {view.spend.sessions}
|
||||
{view.spend.costEstimated && " · ≈ — оценка по прайсу API"}.
|
||||
</p>
|
||||
<details className="text-sm">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground">Изменить бюджет стори</summary>
|
||||
<form action={action} className="mt-2 flex flex-col gap-2">
|
||||
<Hidden fields={{ taskId, back }} />
|
||||
<BudgetFields budget={view.source === "task" ? view.budget : {}} placeholder={projectBudget} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" name="mode" value="set">Сохранить</Button>
|
||||
<Button size="sm" variant="outline" name="mode" value="unlimited">Без лимита</Button>
|
||||
{view.source === "task" && (
|
||||
<Button size="sm" variant="ghost" name="mode" value="inherit">Как в проекте</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise<void> }) {
|
||||
return (
|
||||
<form action={action} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<BudgetFields budget={budget} />
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PEP-47: metrics ───────────────────────────────────────────────────────────────
|
||||
function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5 rounded-lg border bg-card px-3 py-2.5" title={hint}>
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<span className="font-mono text-lg font-semibold tabular-nums">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const day = (d: Date) => d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" });
|
||||
|
||||
function Bar({ value, max }: { value: number; max: number }) {
|
||||
return (
|
||||
<span className="relative inline-block h-1.5 w-full min-w-10 overflow-hidden rounded-full bg-muted align-middle" aria-hidden>
|
||||
<span className="absolute inset-y-0 left-0 rounded-full bg-primary/70" style={{ width: `${max > 0 ? Math.max(value > 0 ? 3 : 0, (value / max) * 100) : 0}%` }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: string }) {
|
||||
const s = m.summary;
|
||||
const maxDone = Math.max(...m.weekly.map((w) => w.done), 0);
|
||||
const maxHours = Math.max(...m.weekly.map((w) => w.runnerHours), 0);
|
||||
const cols: Array<[string, (b: MetricsBucket) => ReactNode]> = [
|
||||
["Цикл", (b) => fmtHours(b.cycleHoursMedian)],
|
||||
["1-й проход", (b) => fmtPct(b.firstPassRate)],
|
||||
["Возвраты", (b) => fmtPct(b.reviewReturnRate)],
|
||||
["Вопр./стори", (b) => (b.questionsPerStory == null ? "—" : b.questionsPerStory.toFixed(1))],
|
||||
["Ждали PM", (b) => fmtHours(b.pmWaitHours)],
|
||||
["Лимиты", (b) => b.limitHits],
|
||||
["Токены", (b) => fmtTokens(b.spend.tokens)],
|
||||
["Стоимость", (b) => fmtCost(b.spend.usage)],
|
||||
];
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground">Период:</span>
|
||||
{[4, 8, 12].map((w) => (
|
||||
<Link key={w} href={`/p/${projectKey}?tab=metrics&weeks=${w}`} aria-current={m.weeks === w ? "page" : undefined} className={cn("rounded-md border px-2 py-0.5 text-xs", m.weeks === w ? "border-primary text-foreground" : "text-muted-foreground")}>
|
||||
{w} нед.
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<Stat label="Готово стори" value={s.done} />
|
||||
<Stat label="Время цикла (медиана)" value={fmtHours(s.cycleHoursMedian)} hint="От «В работу» до «Готово»" />
|
||||
<Stat label="Приняты с первого раза" value={fmtPct(s.firstPassRate)} hint="Без возврата из ревью и без замечаний ревьюера" />
|
||||
<Stat label="Возвраты с ревью" value={fmtPct(s.reviewReturnRate)} />
|
||||
<Stat label="Вопросов PM на стори" value={s.questionsPerStory == null ? "—" : s.questionsPerStory.toFixed(1)} hint="Вопросы, разрешения и одобрения; уведомления не считаются" />
|
||||
<Stat label="Часы раннеров" value={fmtHours(s.runnerHours)} />
|
||||
<Stat label="Агенты ждали PM" value={fmtHours(s.pmWaitHours)} hint="Сумма времени от вопроса агента до ответа человека" />
|
||||
<Stat label="Упоры в лимит" value={s.limitHits} />
|
||||
<Stat label="Токены" value={fmtTokens(s.spend.tokens)} />
|
||||
<Stat label="Стоимость" value={fmtCost(s.spend.usage)} hint="≈ — оценка по прайсу API, если агент не сообщил стоимость" />
|
||||
</div>
|
||||
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">По неделям</h2>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full min-w-[760px] border-collapse text-sm">
|
||||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">Неделя</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Готово</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Раннеры</th>
|
||||
{cols.map(([h]) => (
|
||||
<th key={h} className="px-3 py-2 text-right font-medium whitespace-nowrap">{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...m.weekly].reverse().map((w) => (
|
||||
<tr key={w.from.toISOString()} className="border-t">
|
||||
<td className="px-3 py-1.5 font-mono text-xs whitespace-nowrap">{day(w.from)}</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<span className="flex items-center gap-2"><span className="w-5 font-mono tabular-nums">{w.done}</span><Bar value={w.done} max={maxDone} /></span>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<span className="flex items-center gap-2"><span className="w-16 shrink-0 font-mono text-xs whitespace-nowrap tabular-nums">{fmtHours(w.runnerHours)}</span><Bar value={w.runnerHours} max={maxHours} /></span>
|
||||
</td>
|
||||
{cols.map(([h, f]) => (
|
||||
<td key={h} className="px-3 py-1.5 text-right font-mono text-xs tabular-nums whitespace-nowrap">{f(w)}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-2">
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">По агентам</h2>
|
||||
{m.byProvider.length === 0 ? (
|
||||
<Empty>Сессий за период не было.</Empty>
|
||||
) : (
|
||||
<SimpleTable
|
||||
head={["Агент", "Сессий", "Стори", "Часы", "Токены", "Стоимость"]}
|
||||
rows={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)])}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">По эпикам (всё время)</h2>
|
||||
{m.byEpic.length === 0 ? (
|
||||
<Empty>Стори нет.</Empty>
|
||||
) : (
|
||||
<SimpleTable
|
||||
head={["Эпик", "Стори", "Готово", "Время", "Токены", "Стоимость"]}
|
||||
rows={m.byEpic.map((e) => [
|
||||
e.goalId ? <Link key="t" href={`/p/${projectKey}?epic=${e.goalId}`}>{e.title}</Link> : e.title,
|
||||
e.stories,
|
||||
e.done,
|
||||
fmtHours(e.spend.minutes / 60),
|
||||
fmtTokens(e.spend.tokens),
|
||||
fmtCost(e.spend.usage),
|
||||
])}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SimpleTable({ head, rows }: { head: string[]; rows: ReactNode[][] }) {
|
||||
return (
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||||
<tr>
|
||||
{head.map((h, i) => (
|
||||
<th key={h} className={cn("px-3 py-2 font-medium", i === 0 ? "text-left" : "text-right")}>{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr key={i} className="border-t">
|
||||
{r.map((c, j) => (
|
||||
<td key={j} className={cn("px-3 py-1.5", j === 0 ? "text-left" : "text-right font-mono text-xs tabular-nums")}>{c}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PEP-48: journal ───────────────────────────────────────────────────────────────
|
||||
const KIND_TONE = { user: "info", agent: "ok", system: "muted" } as const;
|
||||
|
||||
export function JournalList({ entries, showProject = true }: { entries: JournalEntry[]; showProject?: boolean }) {
|
||||
if (!entries.length) return <Empty>Действий нет.</Empty>;
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col divide-y rounded-lg border p-0">
|
||||
{entries.map((e) => {
|
||||
const who = actorLabel(e);
|
||||
const line = eventLine(e);
|
||||
return (
|
||||
<li key={e.id} className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1 px-3 py-2 text-sm">
|
||||
<span className="w-14 shrink-0 font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span>
|
||||
{e.actorKind ? <Badge variant={KIND_TONE[e.actorKind]}>{who}</Badge> : <Badge variant="muted">автор не записан</Badge>}
|
||||
<span className="font-mono text-xs text-primary">{e.type}</span>
|
||||
{showProject && !e.taskKey && <Link href={`/p/${e.projectKey}`} className="font-mono text-xs">{e.projectKey}</Link>}
|
||||
{e.taskKey && <Link href={`/t/${e.taskKey}`} className="font-mono text-xs">{e.taskKey}</Link>}
|
||||
{line && <span className="min-w-0 flex-[1_1_16rem] text-xs text-muted-foreground [overflow-wrap:anywhere]">{line.length > 300 ? `${line.slice(0, 300)}…` : line}</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
export function JournalFilters({ action, projects, value }: { action: string; projects?: Array<{ key: string; name: string }>; value: { project?: string; actor?: string; channel?: string; tab?: string } }) {
|
||||
return (
|
||||
<form action={action} method="get" className="flex flex-wrap items-center gap-2 text-sm">
|
||||
{value.tab && <input type="hidden" name="tab" value={value.tab} />}
|
||||
{projects && (
|
||||
<select name="project" defaultValue={value.project ?? ""} aria-label="Проект" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">Все проекты</option>
|
||||
{projects.map((p) => (
|
||||
<option key={p.key} value={p.key}>{p.key} — {p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<select name="actor" defaultValue={value.actor ?? ""} aria-label="Кто" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">Все авторы</option>
|
||||
{Object.entries(ACTOR_KIND_NAMES).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
<select name="channel" defaultValue={value.channel ?? ""} aria-label="Канал" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">Все каналы</option>
|
||||
{Object.entries(ACTOR_CHANNEL_NAMES).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="sm" variant="outline">Показать</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@ -10,6 +10,7 @@ import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards"
|
||||
import { ago, Key, StatusBadge } from "@/components/common";
|
||||
import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { SessionUsageLine } from "@/components/Accounting";
|
||||
import type { InboxItem } from "@/lib/queries";
|
||||
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
@ -45,6 +46,8 @@ export function eventLine(e: { type: string; payload: unknown }): string {
|
||||
if (e.type === "subscription_switched") return switchText(e.payload);
|
||||
if (e.type === "task_updated") return JSON.stringify((e.payload as { to: unknown }).to);
|
||||
if (e.type === "pm_comment") return (e.payload as { text: string }).text;
|
||||
if (e.type === "question_answered") return `ответ на #${(e.payload as { questionId?: number }).questionId}: ${(e.payload as { answer?: string }).answer ?? ""}`;
|
||||
if (e.type === "budget_paused") return `бюджет исчерпан: ${(e.payload as { summary?: string }).summary ?? ""}`;
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -115,6 +118,8 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
{s.taskTitle ?? s.name ?? "без стори"}
|
||||
</h2>
|
||||
{s.name && s.taskTitle && <p className="m-0 text-sm text-muted-foreground">{s.name}</p>}
|
||||
{/* PEP-5: tokens, cost, context of this runner. */}
|
||||
<SessionUsageLine usage={s.usage} provider={s.provider} />
|
||||
{s.status === "rate_limited" && (
|
||||
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">
|
||||
<LimitNote s={s} />
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Bot, FolderKanban, House, KeyRound, LifeBuoy, LogOut, Search, Settings, Users, type LucideIcon } from "lucide-react";
|
||||
import { Bot, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Settings, Users, type LucideIcon } from "lucide-react";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { ThemeToggle } from "@/components/ThemeToggle";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -24,6 +24,7 @@ const ITEMS: Item[] = [
|
||||
{ href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" },
|
||||
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
|
||||
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
|
||||
{ href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
|
||||
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
|
||||
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },
|
||||
];
|
||||
|
||||
@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { ago, Empty, Key, StatusBadge } from "@/components/common";
|
||||
import { AgentSteps } from "@/components/AgentSteps";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { SessionUsageLine } from "@/components/Accounting";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const KIND = {
|
||||
@ -132,6 +133,7 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
|
||||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation} · {ago(s.lastActivityAt)}
|
||||
</span>
|
||||
</header>
|
||||
<SessionUsageLine usage={s.usage} provider={s.provider} />
|
||||
<AttachCommand name={s.tmuxName} />
|
||||
<SessionActions s={s} back={back} />
|
||||
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} />}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { getUser, isUserAllowed, sign, verify, type User } from "@peppa/core";
|
||||
import { enterActor, getUser, isUserAllowed, sign, verify, type User } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
@ -36,6 +36,15 @@ export async function requireUser(): Promise<User> {
|
||||
return u;
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-48: marks the rest of this server action as done by `user` through the web. Synchronous
|
||||
* on purpose — call it in the action body: `const user = asWebActor(await requireUser())`.
|
||||
*/
|
||||
export function asWebActor(user: User): User {
|
||||
enterActor({ kind: "user", userId: user.id, channel: "web" });
|
||||
return user;
|
||||
}
|
||||
|
||||
export function sessionCookie(uid: number) {
|
||||
const exp = Date.now() + SESSION_DAYS * 86400_000;
|
||||
return {
|
||||
|
||||
4
apps/web/next-env.d.ts
vendored
4
apps/web/next-env.d.ts
vendored
@ -1,7 +1,7 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
import "./.next/types/root-params.d.ts";
|
||||
import "./.next/dev/types/routes.d.ts";
|
||||
import "./.next/dev/types/root-params.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
|
||||
29
openspec/changes/archive/2026-11-14-pep-43-budgets/design.md
Normal file
29
openspec/changes/archive/2026-11-14-pep-43-budgets/design.md
Normal file
@ -0,0 +1,29 @@
|
||||
# Design: PEP-43
|
||||
|
||||
## Хранение (без миграций, как автономность PEP-23)
|
||||
- `settings` `budget.project:<projectId>` и `budget.task:<taskId>`:
|
||||
`{ minutes?, tokens?, restarts?, costUsd? }`, `null`/нет поля = без предела. Строка стори
|
||||
целиком заменяет проектную (пустой объект у стори = «без лимита» даже при проектном).
|
||||
- `budget.state:<taskId>` = `{ pausedAt, over: ["tokens", …], questionId }` — пауза до ответа PM.
|
||||
|
||||
## Расход
|
||||
- minutes: Σ (endedAt ?? now − startedAt) сессий стори.
|
||||
- tokens/cost: Σ итогов `sessions.usage` (PEP-5); стоимость «≈», если хоть у одной сессии оценка.
|
||||
- restarts: Σ generation − 1 (каждый запуск/resume увеличивает generation).
|
||||
|
||||
## Пауза, а не убийство
|
||||
Escape в pane прерывает ход Claude, процесс и разговор остаются; сессия → `waiting_input`.
|
||||
Так PM может продлить и продолжить тот же разговор. Ничего не делается молча: событие
|
||||
`budget_paused` на стори и вопрос PM. Codex/OpenCode — то же Escape (их TUI тоже прерывает ход).
|
||||
|
||||
## Ответ PM (реестр `onAnswer`)
|
||||
- «Продлить ×2»: у каждого превышенного предела новый предел = max(предел × 2, расход × 1.5),
|
||||
пишется в бюджет стори; состояние снимается; живому раннеру — «Бюджет продлён, продолжай».
|
||||
- «Снять лимит»: бюджет стори = `{}`; продолжение так же.
|
||||
- «Остановить» / любой другой текст: `stopSession` живых раннеров, состояние снимается
|
||||
(повторный запуск снова упрётся в бюджет и снова спросит).
|
||||
|
||||
## Гард
|
||||
`startSession`/`resumeSession` отказывают стори на паузе («Бюджет стори исчерпан…»);
|
||||
вачдог не делает авто-resume/ротацию такой стори; Stop-хук не подталкивает.
|
||||
Изменение бюджета в карточке снимает паузу, если новый бюджет больше не превышен.
|
||||
@ -0,0 +1,30 @@
|
||||
# Proposal: PEP-43 — бюджеты стори: время, токены, перезапуски, стоимость
|
||||
|
||||
Стори Пеппы: **PEP-43** (эпик «Автономная фабрика»).
|
||||
|
||||
## Why
|
||||
|
||||
Автономный агент (PEP-23/24) может бесконечно жечь лимит на одной стори: перезапуски после
|
||||
лимита, красный CI, подталкивания. Нужен потолок на стори и видимость расхода по стори и эпикам.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Бюджет**: по проекту (по умолчанию для всех стори) и на конкретную стори (заменяет
|
||||
проектный). Пределы: минуты работы раннеров, токены, перезапуски, стоимость $. По умолчанию
|
||||
бюджета нет — поведение как раньше.
|
||||
- **Расход стори** (`taskSpend`): минуты = сумма длительностей сессий стори, токены и
|
||||
стоимость — из расхода сессий (PEP-5, «≈» если оценка), перезапуски = запуски и resume
|
||||
сверх первого.
|
||||
- **Превышение → пауза и вопрос PM**: вачдог видит превышение у стори с живым раннером —
|
||||
прерывает текущий ход (Escape, разговор сохраняется, процесс не убивается), Stop-хук больше
|
||||
не подталкивает, автозапуски (диспетчер, CI, лимиты, ротация) этой стори не стартуют; PM
|
||||
получает вопрос с кнопками «Продлить ×2» / «Снять лимит» / «Остановить». Продление и
|
||||
снятие продолжают раннер сообщением, «Остановить» останавливает раннеры.
|
||||
- **Где видно**: карточка стори (расход против бюджета, форма бюджета, «бюджет исчерпан»),
|
||||
«⋯ Настройки проекта → Бюджет» (по умолчанию), расход по эпикам — во вкладке «Метрики»
|
||||
(PEP-47); MCP `get_task` показывает расход и бюджет.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/core/budgets.ts`, `packages/runner/budgets.ts` (тик, ответ PM, гард запуска),
|
||||
хук Stop, веб (карточка, настройки проекта, server actions), MCP. Миграций нет (`settings`).
|
||||
@ -0,0 +1,52 @@
|
||||
# Spec Delta: story-budgets
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Бюджет стори
|
||||
У проекта SHALL быть необязательный бюджет по умолчанию, у стори — свой, заменяющий проектный:
|
||||
пределы минут работы раннеров, токенов, перезапусков и стоимости. Без бюджета стори SHALL
|
||||
работать без ограничений, как раньше.
|
||||
|
||||
#### Scenario: Бюджет по умолчанию
|
||||
- **GIVEN** у проекта PEP бюджет по умолчанию 100 000 токенов
|
||||
- **AND** у стори PEP-7 своего бюджета нет
|
||||
- **WHEN** PM открывает карточку PEP-7
|
||||
- **THEN** он видит предел 100 000 токенов и потраченное
|
||||
|
||||
#### Scenario: Без бюджета
|
||||
- **GIVEN** у проекта и стори бюджета нет
|
||||
- **WHEN** раннер стори потратил 5 000 000 токенов
|
||||
- **THEN** раннер продолжает работать, вопросов о бюджете нет
|
||||
|
||||
### Requirement: Превышение бюджета ставит стори на паузу и спрашивает PM
|
||||
Когда расход стори с живым раннером превышает предел, вачдог SHALL прервать текущий ход без
|
||||
завершения процесса, не подталкивать агента и не запускать стори автоматически, и SHALL
|
||||
задать PM вопрос «Продлить ×2» / «Снять лимит» / «Остановить».
|
||||
|
||||
#### Scenario: Превышение токенов
|
||||
- **GIVEN** у стори PEP-7 бюджет 1 000 токенов и живой раннер
|
||||
- **WHEN** раннер потратил 1 500 токенов и вачдог сделал тик
|
||||
- **THEN** PM получает вопрос о бюджете PEP-7 с кнопками «Продлить ×2», «Снять лимит», «Остановить»
|
||||
- **AND** tmux-сессия раннера жива
|
||||
- **AND** новый запуск PEP-7 отклоняется с «Бюджет стори исчерпан»
|
||||
|
||||
#### Scenario: PM продлил бюджет
|
||||
- **GIVEN** PEP-7 на паузе с бюджетом 1 000 токенов и расходом 1 500
|
||||
- **WHEN** PM отвечает «Продлить ×2»
|
||||
- **THEN** бюджет токенов PEP-7 становится 2 250
|
||||
- **AND** раннер получает сообщение «Бюджет продлён»
|
||||
|
||||
#### Scenario: PM остановил
|
||||
- **GIVEN** PEP-7 на паузе
|
||||
- **WHEN** PM отвечает «Остановить»
|
||||
- **THEN** раннеры PEP-7 остановлены
|
||||
|
||||
### Requirement: Расход по стори и эпикам
|
||||
Карточка стори SHALL показывать расход (минуты, токены, стоимость с «≈» для оценки,
|
||||
перезапуски) против бюджета; вкладка метрик проекта — расход по эпикам; MCP `get_task` —
|
||||
расход и бюджет.
|
||||
|
||||
#### Scenario: Расход на карточке
|
||||
- **GIVEN** у PEP-7 две сессии по 10 минут и 3 000 токенов
|
||||
- **WHEN** PM открывает карточку
|
||||
- **THEN** он видит «20 мин», «3 000 токенов» и «перезапусков: 1»
|
||||
15
openspec/changes/archive/2026-11-14-pep-43-budgets/tasks.md
Normal file
15
openspec/changes/archive/2026-11-14-pep-43-budgets/tasks.md
Normal file
@ -0,0 +1,15 @@
|
||||
# Tasks: PEP-43
|
||||
|
||||
## 1. Core
|
||||
- [x] 1.1 core/budgets.ts: бюджеты в settings, `taskSpend`, `effectiveBudget`, `budgetOver`, состояние паузы, расход по эпикам
|
||||
|
||||
## 2. Раннер
|
||||
- [x] 2.1 runner/budgets.ts: `budgetTick` (Escape, событие, вопрос PM), `onBudgetAnswer`, гард в start/resume, вачдог не возобновляет стори на паузе
|
||||
- [x] 2.2 Stop-хук не подталкивает стори на паузе
|
||||
|
||||
## 3. Интерфейсы
|
||||
- [x] 3.1 Веб: расход и бюджет на карточке, «Настройки проекта → Бюджет», server actions
|
||||
- [x] 3.2 MCP `get_task`: расход и бюджет
|
||||
|
||||
## 4. Тесты
|
||||
- [x] 4.1 budgets.test.ts: сценарии спеки
|
||||
@ -0,0 +1,18 @@
|
||||
# Design: PEP-47
|
||||
|
||||
## Определения
|
||||
- **Время цикла** стори: от первого перехода в `proposing`/`in_progress` до последнего
|
||||
перехода в `done` (события `task_updated`). Неделя стори — неделя перехода в `done`.
|
||||
- **Принята с первого раза**: готовая стори без перехода `review → proposing|in_progress` и
|
||||
без ревью агента с вердиктом `changes`. **Доля возвратов** = стори с возвратом / стори,
|
||||
дошедшие до `review`.
|
||||
- **Вопросов на стори**: вопросы `question|permission|approval` за период / стори с сессиями
|
||||
за период (уведомления `attention` не считаются).
|
||||
- **Ждали PM**: Σ (answeredAt − createdAt) вопросов от сессий, отвеченных человеком (не `system`).
|
||||
- **Упоры в лимит**: события `usage_limit` и `stop_failure` с `rate_limit`.
|
||||
- **Часы раннеров**: Σ длительностей сессий, начатых в неделе (обрезка по «сейчас»).
|
||||
- Недели — ISO, понедельник 00:00 по часовому поясу сервера.
|
||||
|
||||
## Почему без таблиц-агрегатов
|
||||
Объёмы проекта — сотни стори и тысячи событий; расчёт в JS на запрос страницы укладывается в
|
||||
миллисекунды на SQLite. Кэш не нужен.
|
||||
@ -0,0 +1,25 @@
|
||||
# Proposal: PEP-47 — аналитика фабрики
|
||||
|
||||
Стори Пеппы: **PEP-47** (эпик «Удобство для PM»).
|
||||
|
||||
## Why
|
||||
|
||||
Непонятно, насколько хорошо работает фабрика: сколько идёт стори, как часто возвращается с
|
||||
ревью, сколько агенты ждут PM, сколько уходит лимита.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Вкладка «Метрики»** на странице проекта (`?tab=metrics`): за выбранный период (4/8/12
|
||||
недель) — готово стори, медиана времени цикла («В работу» → «Готово»), доля принятых с
|
||||
первого раза, доля возвратов с ревью, вопросов к PM на стори, часы раннеров, сколько агенты
|
||||
ждали PM, упоры в лимит, токены и стоимость («≈» для оценки).
|
||||
- **Тренд по неделям**: таблица с полосками по тем же метрикам.
|
||||
- **По агентам**: Claude/Codex/OpenCode — сессии, часы, токены, стоимость, стори.
|
||||
- **По эпикам**: стори, готово, минуты, токены, стоимость (расход PEP-43).
|
||||
- MCP удалённого PM: `get_metrics`.
|
||||
- Всё считается из имеющихся данных: события `task_updated` (переходы статуса), вопросы,
|
||||
сессии, ревью (PEP-26), `sessions.usage` (PEP-5). Новых таблиц нет.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/core/analytics.ts`, веб (вкладка проекта), MCP manager, помощь.
|
||||
@ -0,0 +1,29 @@
|
||||
# Spec Delta: factory-metrics
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Метрики проекта
|
||||
Страница проекта SHALL иметь вкладку «Метрики» с итогами за выбранный период: готово стори,
|
||||
медиана времени цикла, доля принятых с первого раза, доля возвратов с ревью, вопросов к PM на
|
||||
стори, часы раннеров, время ожидания PM, упоры в лимит, токены и стоимость.
|
||||
|
||||
#### Scenario: Время цикла и первый проход
|
||||
- **GIVEN** стори PEP-1 перешла в работу в понедельник 10:00 и в «Готово» во вторник 10:00 без возвратов
|
||||
- **AND** стори PEP-2 возвращалась из ревью в работу и закрыта
|
||||
- **WHEN** PM открывает вкладку «Метрики»
|
||||
- **THEN** готово 2 стори, доля принятых с первого раза 50%, доля возвратов 50%
|
||||
- **AND** время цикла PEP-1 учтено как 24 ч
|
||||
|
||||
#### Scenario: Пустой проект
|
||||
- **GIVEN** в проекте нет закрытых стори
|
||||
- **WHEN** PM открывает вкладку «Метрики»
|
||||
- **THEN** вместо медианы и долей показано «—», а не ноль
|
||||
|
||||
### Requirement: Тренд по неделям, агентам и эпикам
|
||||
Вкладка «Метрики» SHALL показывать те же метрики по неделям, расход и работу по провайдерам
|
||||
агентов и расход по эпикам. MCP SHALL отдавать метрики инструментом `get_metrics`.
|
||||
|
||||
#### Scenario: Разбивка по агентам
|
||||
- **GIVEN** в проекте сессия Claude на 2 ч и сессия Codex на 1 ч
|
||||
- **WHEN** PM открывает вкладку «Метрики»
|
||||
- **THEN** в таблице агентов Claude — 2 ч, Codex — 1 ч
|
||||
@ -0,0 +1,11 @@
|
||||
# Tasks: PEP-47
|
||||
|
||||
## 1. Core
|
||||
- [x] 1.1 core/analytics.ts: `projectMetrics` (итоги, недели, агенты, эпики)
|
||||
|
||||
## 2. Интерфейсы
|
||||
- [x] 2.1 Веб: вкладка «Метрики» проекта
|
||||
- [x] 2.2 MCP `get_metrics`, помощь
|
||||
|
||||
## 3. Тесты
|
||||
- [x] 3.1 metrics.test.ts: сценарии спеки
|
||||
@ -0,0 +1,23 @@
|
||||
# Design: PEP-48
|
||||
|
||||
## Как автор попадает в событие
|
||||
Событий пишут всего три функции core (`logSessionEvent`, `updateTask`, `reportProgress`) и
|
||||
новая `logActorEvent`; вызывают их десятки мест. Протаскивать автора параметром через все
|
||||
вызовы (moveTask → startSession → launch → logSessionEvent) — большой и хрупкий дифф.
|
||||
Поэтому автор — контекст `AsyncLocalStorage` (`runAsActor`, `enterActor`, `setDefaultActor`):
|
||||
- веб: `enterActor` синхронно в теле server action сразу после `requireUser()` (контекст
|
||||
запроса Next отдельный, утечки нет);
|
||||
- `/mcp`: `enterActor({ user, channel: "mcp", clientId })` до обработки запроса;
|
||||
- бот: `runAsActor` вокруг обработки ответа/кнопки;
|
||||
- процессы: `setDefaultActor` — MCP агента (`agent`, `mcp`), хук (`agent`, `hook`), вачдог
|
||||
(`system`, `watchdog`), CLI (`system`, `cli`).
|
||||
Без контекста: событие с `sessionId` — агент, иначе система.
|
||||
|
||||
## Хранение
|
||||
Колонки в `events` (а не отдельная таблица аудита): лента стори и журнал — одно и то же,
|
||||
события уже покрывают перемещения, запуски, остановки, прогресс; `question_answered` добавляет
|
||||
ответы. Индекс `events_created_at` для журнала.
|
||||
|
||||
## Доступ
|
||||
`/journal` — только суперадмин (`isSuperadmin`, иначе 404), фильтр `?project=KEY&actor=&channel=`.
|
||||
Вкладка проекта «Журнал» — владелец и участники (через `projectForUser`).
|
||||
@ -0,0 +1,27 @@
|
||||
# Proposal: PEP-48 — журнал действий: кто что сделал
|
||||
|
||||
Стори Пеппы: **PEP-48** (эпик «Безопасность и эксплуатация»).
|
||||
|
||||
## Why
|
||||
|
||||
С шерингом (PEP-12) и удалённым MCP (PEP-8) неясно, кто подвинул карточку или ответил агенту:
|
||||
события пишутся без автора.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Автор события**: у `events` новые колонки `actor_kind` (`user` | `agent` | `system`),
|
||||
`actor_user_id`, `actor_channel` (`web` | `telegram` | `mcp` | `cli` | `terminal` | `hook` |
|
||||
`watchdog` | `gitea`), `actor_client_id` (OAuth-клиент удалённого MCP); миграция 0010.
|
||||
- **Контекст автора** (`core/actor.ts`, AsyncLocalStorage): веб-действия, удалённый MCP
|
||||
(пользователь + клиент), бот (пользователь Telegram), MCP агента (агент, сессия), хуки,
|
||||
вачдог, CLI задают автора; запись события берёт его из контекста. Без контекста: есть сессия —
|
||||
агент, иначе система.
|
||||
- **Ответы PM становятся событиями**: `question_answered` (кто, через что, текст ответа).
|
||||
- **Где видно**: лента событий стори показывает автора; страница «Журнал» (`/journal`) для
|
||||
суперадмина — все действия с фильтрами по проекту, типу автора и каналу; вкладка «Журнал»
|
||||
проекта для его участников.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/db` (миграция 0010), `packages/core` (actor.ts, audit.ts, запись событий), веб
|
||||
(actions, `/mcp`, `/journal`, вкладка проекта, лента стори), бот, MCP, CLI, вачдог, хук.
|
||||
@ -0,0 +1,38 @@
|
||||
# Spec Delta: audit-journal
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Автор каждого события
|
||||
Каждое событие SHALL хранить автора: человек (пользователь и канал — веб, Telegram, MCP с
|
||||
OAuth-клиентом, CLI, терминал), агент (сессия) или система. Ответ на вопрос агента SHALL
|
||||
записываться событием `question_answered` с автором.
|
||||
|
||||
#### Scenario: Карточку подвинул участник через веб
|
||||
- **GIVEN** участник «anna» проекта PEP
|
||||
- **WHEN** она переносит PEP-7 в «Бэклог» в вебе
|
||||
- **THEN** событие `task_updated` PEP-7 записано с автором «anna», канал «веб»
|
||||
|
||||
#### Scenario: Ответ через удалённый MCP
|
||||
- **GIVEN** пользователь «pm» подключил ChatGPT как OAuth-клиент
|
||||
- **WHEN** через MCP `answer_question` он отвечает на вопрос PEP-7
|
||||
- **THEN** событие `question_answered` записано с автором «pm», канал «MCP», клиент «ChatGPT»
|
||||
|
||||
#### Scenario: Действие агента
|
||||
- **GIVEN** раннер стори PEP-7
|
||||
- **WHEN** агент вызывает `report_progress`
|
||||
- **THEN** событие записано с автором «агент» и сессией раннера
|
||||
|
||||
### Requirement: Журнал действий
|
||||
Веб SHALL показывать суперадмину страницу «Журнал» со всеми событиями (новые сверху) и
|
||||
фильтрами по проекту, типу автора и каналу; участникам проекта — вкладку «Журнал» проекта;
|
||||
лента событий стори SHALL показывать автора.
|
||||
|
||||
#### Scenario: Фильтр по проекту
|
||||
- **GIVEN** события в проектах PEP и PAY
|
||||
- **WHEN** суперадмин открывает «Журнал» с фильтром PAY
|
||||
- **THEN** видны только события PAY
|
||||
|
||||
#### Scenario: Не суперадмин
|
||||
- **GIVEN** пользователь не суперадмин
|
||||
- **WHEN** он открывает `/journal`
|
||||
- **THEN** он получает 404
|
||||
@ -0,0 +1,15 @@
|
||||
# Tasks: PEP-48
|
||||
|
||||
## 1. Данные и core
|
||||
- [x] 1.1 Колонки автора в `events` + индекс, миграция 0010
|
||||
- [x] 1.2 core/actor.ts (контекст автора), запись автора во всех вставках событий, `question_answered`
|
||||
- [x] 1.3 core/audit.ts: `listJournal`, подписи автора
|
||||
|
||||
## 2. Источники автора
|
||||
- [x] 2.1 Веб-действия, `/mcp` (клиент OAuth), бот, MCP агента, хук, вачдог, CLI
|
||||
|
||||
## 3. Интерфейсы
|
||||
- [x] 3.1 Веб: `/journal` (суперадмин), вкладка «Журнал» проекта, автор в ленте стори, пункт меню
|
||||
|
||||
## 4. Тесты
|
||||
- [x] 4.1 journal.test.ts: сценарии спеки
|
||||
31
openspec/changes/archive/2026-11-14-pep-5-usage/design.md
Normal file
31
openspec/changes/archive/2026-11-14-pep-5-usage/design.md
Normal file
@ -0,0 +1,31 @@
|
||||
# Design: PEP-5
|
||||
|
||||
## Откуда данные
|
||||
- **statusLine** (Claude Code вызывает команду при обновлении статуса, JSON на stdin):
|
||||
`cost.total_cost_usd` — стоимость текущего процесса (на поколение раннера);
|
||||
`context_window.{context_window_size,current_usage,used_percentage,total_input_tokens,total_output_tokens}`;
|
||||
`rate_limits.{five_hour,seven_day}.{used_percentage,resets_at}`. Названия полей окон
|
||||
разбираем терпимо (`five_hour|fiveHour|5h`, `seven_day|sevenDay|weekly`,
|
||||
`used_percentage|utilization|percent` — доля 0..1 переводится в проценты; `resets_at` —
|
||||
ISO или epoch с/мс).
|
||||
- **transcript** (`transcript_path` в payload хука): строки `type: assistant` с
|
||||
`message.usage`; дедуп по `message.id` (потоковые дубли). Resume продолжает тот же файл,
|
||||
поэтому токены храним по разговору (`convs[conversationId]`), а не по поколению.
|
||||
|
||||
## Хранение
|
||||
- `sessions.usage` JSON: `{ convs: {id: Tokens & {model}}, costByGen: {gen: usd},
|
||||
tokensByGen: {gen: {input,output}}, context: {used,size,pct}, at }`. Итог: токены =
|
||||
сумма convs (иначе tokensByGen), стоимость = сумма costByGen (точная, от Claude), иначе
|
||||
оценка по прайсу (`estimated: true`, в UI «≈»).
|
||||
- Окна аккаунта — `settings` `usage.account:sub:<id>` / `usage.account:machine`
|
||||
`{ fiveHour?, sevenDay?, at, sessionId }`. Отдельная таблица не нужна: одна строка на аккаунт.
|
||||
- Прайс оценки ($/Мтокен): opus 5/25, sonnet 3/15, haiku 1/5; cache read ×0.1, cache write ×1.25.
|
||||
|
||||
## Честность
|
||||
- Окно, у которого `resetsAt` уже прошёл, показывается «сброшено», без процента.
|
||||
- Данные старше 6 ч помечаются «устарело (N ч назад)».
|
||||
- Нет ни одного аккаунта с данными — «нет данных о лимитах».
|
||||
|
||||
## Кто что видит
|
||||
Полоса: суперадмин — все аккаунты; остальные — аккаунты пулов своих проектов и вход машины,
|
||||
если у его проектов нет пула.
|
||||
34
openspec/changes/archive/2026-11-14-pep-5-usage/proposal.md
Normal file
34
openspec/changes/archive/2026-11-14-pep-5-usage/proposal.md
Normal file
@ -0,0 +1,34 @@
|
||||
# Proposal: PEP-5 — расход и лимиты: полоса использования сверху
|
||||
|
||||
Стори Пеппы: **PEP-5** (эпик «Надёжность фабрики на живых агентах»).
|
||||
|
||||
## Why
|
||||
|
||||
PM не видит, сколько осталось от лимитов Claude (окна 5 ч и 7 дней) и сколько съела
|
||||
сессия. Узнаёт об этом только по баннеру лимита (PEP-56). Claude Code сам отдаёт расход:
|
||||
statusLine-команде (контекст, стоимость, окна лимитов) и в transcript (токены каждого ответа).
|
||||
|
||||
## What Changes
|
||||
|
||||
- **statusLine раннера**: в генерируемый `settings.json` добавляется
|
||||
`statusLine: peppa-hook statusline`. Хук читает JSON Claude, печатает короткую строку
|
||||
статуса и сохраняет: контекст и стоимость — на сессии, окна лимитов 5 ч / 7 д (процент,
|
||||
время сброса) — на аккаунте сессии (подписка PEP-67 или «вход машины»). Запись не чаще
|
||||
раза в 20 с, если ничего не изменилось.
|
||||
- **Токены из transcript**: Stop-хук суммирует `message.usage` ответов transcript
|
||||
(input/output/cache) по разговору. Стоимость — из statusLine, если её нет — оценка по
|
||||
прайсу API с пометкой «≈».
|
||||
- **Колонка `sessions.usage`** (JSON, миграция 0010) — расход сессии.
|
||||
- **Веб**: тонкая полоса сверху над каждой страницей: «Claude 5 ч ▓▓░ 42% · сброс 14:30 ·
|
||||
7 д 18%» по самому загруженному аккаунту, подсказка со всеми; подписка в лимите
|
||||
(PEP-56) — «лимит до …»; нет данных — «нет данных о лимитах». Карточка раннера — контекст,
|
||||
токены, стоимость.
|
||||
- **Бот** `/status` и **MCP** (`get_usage` у удалённого MCP, расход в `get_task`) отдают то же.
|
||||
- Codex/OpenCode statusLine и хуков не имеют — честно «нет данных».
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/runner` (run-settings, hook, usage.ts), `packages/core/usage.ts`, `packages/db`
|
||||
(миграция 0010), веб (layout, `UsageStrip`, карточка раннера), бот, MCP, testkit (mock-agent).
|
||||
- Формат statusLine/rate_limits настоящего Claude не сверен на живом CLI — разбор терпимый
|
||||
к вариантам полей, мок повторяет документированный формат.
|
||||
@ -0,0 +1,49 @@
|
||||
# Spec Delta: usage-tracking
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Расход сессии из statusLine и transcript
|
||||
Раннер SHALL подключать к сессиям Claude statusLine-команду Пеппы и сохранять на сессии
|
||||
контекст, стоимость (по поколениям) и токены (по разговору из transcript). Стоимость без
|
||||
данных statusLine SHALL оцениваться по прайсу и помечаться как оценка.
|
||||
|
||||
#### Scenario: Сессия сообщила расход
|
||||
- **GIVEN** раннер PEP-1 на Claude
|
||||
- **WHEN** Claude вызывает statusLine с `cost.total_cost_usd` 0.42 и контекстом 50 000 из 200 000
|
||||
- **AND** transcript содержит ответ с 1 200 входных и 300 выходных токенов
|
||||
- **THEN** у сессии стоимость $0.42 без пометки «≈», контекст 25%, токены 1 500
|
||||
|
||||
#### Scenario: Стоимость неизвестна
|
||||
- **GIVEN** transcript с ответом модели sonnet на 1 000 000 входных токенов и без statusLine
|
||||
- **WHEN** ход заканчивается
|
||||
- **THEN** у сессии стоимость ≈ $3.00 с пометкой «оценка»
|
||||
|
||||
### Requirement: Окна лимитов аккаунта
|
||||
statusLine с окнами лимитов SHALL обновлять процент и время сброса окон 5 ч и 7 д для
|
||||
аккаунта сессии (подписки или входа машины). Прошедшее время сброса SHALL показываться как
|
||||
«сброшено», а не как старый процент.
|
||||
|
||||
#### Scenario: Окна обновились
|
||||
- **GIVEN** сессия на подписке «Claude A»
|
||||
- **WHEN** statusLine сообщает 5 ч — 42% со сбросом в 14:30 и 7 д — 18%
|
||||
- **THEN** у «Claude A» сохранены окна 42% (сброс 14:30) и 18%
|
||||
|
||||
#### Scenario: Сброс прошёл
|
||||
- **GIVEN** у «Claude A» окно 5 ч 90% со сбросом в 14:30
|
||||
- **WHEN** сейчас 14:31
|
||||
- **THEN** окно 5 ч показывается «сброшено»
|
||||
|
||||
### Requirement: Полоса использования в вебе, боте и MCP
|
||||
Веб SHALL показывать над каждой страницей полосу с процентом и временем сброса самого
|
||||
загруженного окна доступных пользователю аккаунтов, подписку в лимите — «лимит до …», а
|
||||
без данных — «нет данных о лимитах». Бот `/status` и MCP SHALL отдавать те же окна.
|
||||
|
||||
#### Scenario: Данные есть
|
||||
- **GIVEN** у «Claude A» окно 5 ч 42% со сбросом 14:30
|
||||
- **WHEN** PM открывает любую страницу
|
||||
- **THEN** сверху видно «5 ч 42%» и «сброс 14:30»
|
||||
|
||||
#### Scenario: Данных нет
|
||||
- **GIVEN** ни одна сессия ещё не присылала statusLine
|
||||
- **WHEN** PM открывает любую страницу
|
||||
- **THEN** сверху написано «нет данных о лимитах»
|
||||
17
openspec/changes/archive/2026-11-14-pep-5-usage/tasks.md
Normal file
17
openspec/changes/archive/2026-11-14-pep-5-usage/tasks.md
Normal file
@ -0,0 +1,17 @@
|
||||
# Tasks: PEP-5
|
||||
|
||||
## 1. Данные
|
||||
- [x] 1.1 Колонка `sessions.usage` + миграция 0010 (вместе с PEP-48)
|
||||
- [x] 1.2 core/usage.ts: разбор statusLine и transcript, итоги сессии, окна аккаунтов, оценка по прайсу
|
||||
|
||||
## 2. Раннер
|
||||
- [x] 2.1 run-settings: statusLine → `peppa-hook statusline`; хук statusline (строка статуса + запись с троттлингом)
|
||||
- [x] 2.2 Stop/SessionEnd: токены из transcript
|
||||
|
||||
## 3. Интерфейсы
|
||||
- [x] 3.1 Веб: полоса использования в layout, расход на карточке раннера
|
||||
- [x] 3.2 Бот `/status`, MCP `get_usage`, расход в `get_task`, помощь
|
||||
|
||||
## 4. Тесты
|
||||
- [x] 4.1 mock-agent: действие `usage` (transcript + statusLine)
|
||||
- [x] 4.2 usage.test.ts: сценарии спеки
|
||||
41
openspec/specs/audit-journal/spec.md
Normal file
41
openspec/specs/audit-journal/spec.md
Normal file
@ -0,0 +1,41 @@
|
||||
# audit-journal Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change pep-48-audit-journal. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Автор каждого события
|
||||
Каждое событие SHALL хранить автора: человек (пользователь и канал — веб, Telegram, MCP с
|
||||
OAuth-клиентом, CLI, терминал), агент (сессия) или система. Ответ на вопрос агента SHALL
|
||||
записываться событием `question_answered` с автором.
|
||||
|
||||
#### Scenario: Карточку подвинул участник через веб
|
||||
- **GIVEN** участник «anna» проекта PEP
|
||||
- **WHEN** она переносит PEP-7 в «Бэклог» в вебе
|
||||
- **THEN** событие `task_updated` PEP-7 записано с автором «anna», канал «веб»
|
||||
|
||||
#### Scenario: Ответ через удалённый MCP
|
||||
- **GIVEN** пользователь «pm» подключил ChatGPT как OAuth-клиент
|
||||
- **WHEN** через MCP `answer_question` он отвечает на вопрос PEP-7
|
||||
- **THEN** событие `question_answered` записано с автором «pm», канал «MCP», клиент «ChatGPT»
|
||||
|
||||
#### Scenario: Действие агента
|
||||
- **GIVEN** раннер стори PEP-7
|
||||
- **WHEN** агент вызывает `report_progress`
|
||||
- **THEN** событие записано с автором «агент» и сессией раннера
|
||||
|
||||
### Requirement: Журнал действий
|
||||
Веб SHALL показывать суперадмину страницу «Журнал» со всеми событиями (новые сверху) и
|
||||
фильтрами по проекту, типу автора и каналу; участникам проекта — вкладку «Журнал» проекта;
|
||||
лента событий стори SHALL показывать автора.
|
||||
|
||||
#### Scenario: Фильтр по проекту
|
||||
- **GIVEN** события в проектах PEP и PAY
|
||||
- **WHEN** суперадмин открывает «Журнал» с фильтром PAY
|
||||
- **THEN** видны только события PAY
|
||||
|
||||
#### Scenario: Не суперадмин
|
||||
- **GIVEN** пользователь не суперадмин
|
||||
- **WHEN** он открывает `/journal`
|
||||
- **THEN** он получает 404
|
||||
32
openspec/specs/factory-metrics/spec.md
Normal file
32
openspec/specs/factory-metrics/spec.md
Normal file
@ -0,0 +1,32 @@
|
||||
# factory-metrics Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change pep-47-factory-metrics. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Метрики проекта
|
||||
Страница проекта SHALL иметь вкладку «Метрики» с итогами за выбранный период: готово стори,
|
||||
медиана времени цикла, доля принятых с первого раза, доля возвратов с ревью, вопросов к PM на
|
||||
стори, часы раннеров, время ожидания PM, упоры в лимит, токены и стоимость.
|
||||
|
||||
#### Scenario: Время цикла и первый проход
|
||||
- **GIVEN** стори PEP-1 перешла в работу в понедельник 10:00 и в «Готово» во вторник 10:00 без возвратов
|
||||
- **AND** стори PEP-2 возвращалась из ревью в работу и закрыта
|
||||
- **WHEN** PM открывает вкладку «Метрики»
|
||||
- **THEN** готово 2 стори, доля принятых с первого раза 50%, доля возвратов 50%
|
||||
- **AND** время цикла PEP-1 учтено как 24 ч
|
||||
|
||||
#### Scenario: Пустой проект
|
||||
- **GIVEN** в проекте нет закрытых стори
|
||||
- **WHEN** PM открывает вкладку «Метрики»
|
||||
- **THEN** вместо медианы и долей показано «—», а не ноль
|
||||
|
||||
### Requirement: Тренд по неделям, агентам и эпикам
|
||||
Вкладка «Метрики» SHALL показывать те же метрики по неделям, расход и работу по провайдерам
|
||||
агентов и расход по эпикам. MCP SHALL отдавать метрики инструментом `get_metrics`.
|
||||
|
||||
#### Scenario: Разбивка по агентам
|
||||
- **GIVEN** в проекте сессия Claude на 2 ч и сессия Codex на 1 ч
|
||||
- **WHEN** PM открывает вкладку «Метрики»
|
||||
- **THEN** в таблице агентов Claude — 2 ч, Codex — 1 ч
|
||||
55
openspec/specs/story-budgets/spec.md
Normal file
55
openspec/specs/story-budgets/spec.md
Normal file
@ -0,0 +1,55 @@
|
||||
# story-budgets Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change pep-43-budgets. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Бюджет стори
|
||||
У проекта SHALL быть необязательный бюджет по умолчанию, у стори — свой, заменяющий проектный:
|
||||
пределы минут работы раннеров, токенов, перезапусков и стоимости. Без бюджета стори SHALL
|
||||
работать без ограничений, как раньше.
|
||||
|
||||
#### Scenario: Бюджет по умолчанию
|
||||
- **GIVEN** у проекта PEP бюджет по умолчанию 100 000 токенов
|
||||
- **AND** у стори PEP-7 своего бюджета нет
|
||||
- **WHEN** PM открывает карточку PEP-7
|
||||
- **THEN** он видит предел 100 000 токенов и потраченное
|
||||
|
||||
#### Scenario: Без бюджета
|
||||
- **GIVEN** у проекта и стори бюджета нет
|
||||
- **WHEN** раннер стори потратил 5 000 000 токенов
|
||||
- **THEN** раннер продолжает работать, вопросов о бюджете нет
|
||||
|
||||
### Requirement: Превышение бюджета ставит стори на паузу и спрашивает PM
|
||||
Когда расход стори с живым раннером превышает предел, вачдог SHALL прервать текущий ход без
|
||||
завершения процесса, не подталкивать агента и не запускать стори автоматически, и SHALL
|
||||
задать PM вопрос «Продлить ×2» / «Снять лимит» / «Остановить».
|
||||
|
||||
#### Scenario: Превышение токенов
|
||||
- **GIVEN** у стори PEP-7 бюджет 1 000 токенов и живой раннер
|
||||
- **WHEN** раннер потратил 1 500 токенов и вачдог сделал тик
|
||||
- **THEN** PM получает вопрос о бюджете PEP-7 с кнопками «Продлить ×2», «Снять лимит», «Остановить»
|
||||
- **AND** tmux-сессия раннера жива
|
||||
- **AND** новый запуск PEP-7 отклоняется с «Бюджет стори исчерпан»
|
||||
|
||||
#### Scenario: PM продлил бюджет
|
||||
- **GIVEN** PEP-7 на паузе с бюджетом 1 000 токенов и расходом 1 500
|
||||
- **WHEN** PM отвечает «Продлить ×2»
|
||||
- **THEN** бюджет токенов PEP-7 становится 2 250
|
||||
- **AND** раннер получает сообщение «Бюджет продлён»
|
||||
|
||||
#### Scenario: PM остановил
|
||||
- **GIVEN** PEP-7 на паузе
|
||||
- **WHEN** PM отвечает «Остановить»
|
||||
- **THEN** раннеры PEP-7 остановлены
|
||||
|
||||
### Requirement: Расход по стори и эпикам
|
||||
Карточка стори SHALL показывать расход (минуты, токены, стоимость с «≈» для оценки,
|
||||
перезапуски) против бюджета; вкладка метрик проекта — расход по эпикам; MCP `get_task` —
|
||||
расход и бюджет.
|
||||
|
||||
#### Scenario: Расход на карточке
|
||||
- **GIVEN** у PEP-7 две сессии по 10 минут и 3 000 токенов
|
||||
- **WHEN** PM открывает карточку
|
||||
- **THEN** он видит «20 мин», «3 000 токенов» и «перезапусков: 1»
|
||||
52
openspec/specs/usage-tracking/spec.md
Normal file
52
openspec/specs/usage-tracking/spec.md
Normal file
@ -0,0 +1,52 @@
|
||||
# usage-tracking Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change pep-5-usage. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Расход сессии из statusLine и transcript
|
||||
Раннер SHALL подключать к сессиям Claude statusLine-команду Пеппы и сохранять на сессии
|
||||
контекст, стоимость (по поколениям) и токены (по разговору из transcript). Стоимость без
|
||||
данных statusLine SHALL оцениваться по прайсу и помечаться как оценка.
|
||||
|
||||
#### Scenario: Сессия сообщила расход
|
||||
- **GIVEN** раннер PEP-1 на Claude
|
||||
- **WHEN** Claude вызывает statusLine с `cost.total_cost_usd` 0.42 и контекстом 50 000 из 200 000
|
||||
- **AND** transcript содержит ответ с 1 200 входных и 300 выходных токенов
|
||||
- **THEN** у сессии стоимость $0.42 без пометки «≈», контекст 25%, токены 1 500
|
||||
|
||||
#### Scenario: Стоимость неизвестна
|
||||
- **GIVEN** transcript с ответом модели sonnet на 1 000 000 входных токенов и без statusLine
|
||||
- **WHEN** ход заканчивается
|
||||
- **THEN** у сессии стоимость ≈ $3.00 с пометкой «оценка»
|
||||
|
||||
### Requirement: Окна лимитов аккаунта
|
||||
statusLine с окнами лимитов SHALL обновлять процент и время сброса окон 5 ч и 7 д для
|
||||
аккаунта сессии (подписки или входа машины). Прошедшее время сброса SHALL показываться как
|
||||
«сброшено», а не как старый процент.
|
||||
|
||||
#### Scenario: Окна обновились
|
||||
- **GIVEN** сессия на подписке «Claude A»
|
||||
- **WHEN** statusLine сообщает 5 ч — 42% со сбросом в 14:30 и 7 д — 18%
|
||||
- **THEN** у «Claude A» сохранены окна 42% (сброс 14:30) и 18%
|
||||
|
||||
#### Scenario: Сброс прошёл
|
||||
- **GIVEN** у «Claude A» окно 5 ч 90% со сбросом в 14:30
|
||||
- **WHEN** сейчас 14:31
|
||||
- **THEN** окно 5 ч показывается «сброшено»
|
||||
|
||||
### Requirement: Полоса использования в вебе, боте и MCP
|
||||
Веб SHALL показывать над каждой страницей полосу с процентом и временем сброса самого
|
||||
загруженного окна доступных пользователю аккаунтов, подписку в лимите — «лимит до …», а
|
||||
без данных — «нет данных о лимитах». Бот `/status` и MCP SHALL отдавать те же окна.
|
||||
|
||||
#### Scenario: Данные есть
|
||||
- **GIVEN** у «Claude A» окно 5 ч 42% со сбросом 14:30
|
||||
- **WHEN** PM открывает любую страницу
|
||||
- **THEN** сверху видно «5 ч 42%» и «сброс 14:30»
|
||||
|
||||
#### Scenario: Данных нет
|
||||
- **GIVEN** ни одна сессия ещё не присылала statusLine
|
||||
- **WHEN** PM открывает любую страницу
|
||||
- **THEN** сверху написано «нет данных о лимитах»
|
||||
@ -50,6 +50,7 @@ import {
|
||||
TASK_STATUSES,
|
||||
updateTask,
|
||||
type TaskStatus,
|
||||
setDefaultActor,
|
||||
} from "@peppa/core";
|
||||
import { createDb, migrateDb } from "@peppa/db";
|
||||
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner } from "@peppa/runner";
|
||||
@ -154,6 +155,8 @@ if (positionals[0] === "db") {
|
||||
console.log(`migrated ${env.PEPPA_DB}`);
|
||||
} else if (positionals[1] === "backup") {
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
// PEP-48: CLI commands are an admin's actions on this machine.
|
||||
setDefaultActor({ kind: "system", channel: "cli" });
|
||||
const r = await backupDb(db, { force: true, file: positionals[2] ? resolve(positionals[2]) : undefined, log: (m) => console.error(m) });
|
||||
db.$client.close();
|
||||
if (!r.file) throw new PeppaError(`backup failed: ${r.error}`);
|
||||
|
||||
48
packages/core/src/actor.ts
Normal file
48
packages/core/src/actor.ts
Normal file
@ -0,0 +1,48 @@
|
||||
// PEP-48: who is acting — a person (and through which channel), an agent, or Peppa itself.
|
||||
// Carried in AsyncLocalStorage, so the few functions that write events stamp the author
|
||||
// without threading it through every call (moveTask → startSession → launch → event).
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import type { actorChannels, actorKinds } from "@peppa/db";
|
||||
|
||||
export type ActorKind = (typeof actorKinds)[number];
|
||||
export type ActorChannel = (typeof actorChannels)[number];
|
||||
|
||||
export interface Actor {
|
||||
kind: ActorKind;
|
||||
userId?: number | null;
|
||||
channel?: ActorChannel | null;
|
||||
/** OAuth client of the remote MCP (PEP-8). */
|
||||
clientId?: string | null;
|
||||
}
|
||||
|
||||
const store = new AsyncLocalStorage<Actor>();
|
||||
let fallback: Actor | null = null;
|
||||
|
||||
/** Runs `fn` with this actor (bot handlers, tests). */
|
||||
export function runAsActor<T>(actor: Actor, fn: () => T): T {
|
||||
return store.run(actor, fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the actor for the rest of the current async context. Call it synchronously in the
|
||||
* body of a request handler / server action (not inside an awaited helper), e.g.
|
||||
* `const user = asWebActor(await requireUser())`.
|
||||
*/
|
||||
export function enterActor(actor: Actor): void {
|
||||
store.enterWith(actor);
|
||||
}
|
||||
|
||||
/** Process-wide default (agent MCP server, hook, watchdog, CLI). */
|
||||
export function setDefaultActor(actor: Actor | null): void {
|
||||
fallback = actor;
|
||||
}
|
||||
|
||||
export function currentActor(): Actor | null {
|
||||
return store.getStore() ?? fallback;
|
||||
}
|
||||
|
||||
/** Event columns for the current actor; without one: the session's agent, else Peppa itself. */
|
||||
export function actorColumns(sessionId?: number | null) {
|
||||
const a = currentActor() ?? (sessionId ? { kind: "agent" as const } : { kind: "system" as const });
|
||||
return { actorKind: a.kind, actorUserId: a.userId ?? null, actorChannel: a.channel ?? null, actorClientId: a.clientId ?? null };
|
||||
}
|
||||
177
packages/core/src/analytics.ts
Normal file
177
packages/core/src/analytics.ts
Normal file
@ -0,0 +1,177 @@
|
||||
// PEP-47: factory metrics of a project — cycle time, first-pass acceptance, review returns,
|
||||
// questions to the PM, runner hours, time agents waited for the PM, limit hits, spend.
|
||||
// Computed from what is already recorded (task_updated events, questions, sessions,
|
||||
// code reviews, sessions.usage); projects are small enough to do it per request.
|
||||
import { codeReviews, events, questions, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { and, eq, gte, inArray } from "drizzle-orm";
|
||||
import { epicSpend, spendOf, type EpicSpend, type Spend } from "./budgets.ts";
|
||||
|
||||
export interface MetricsBucket {
|
||||
/** Monday 00:00 of the week (local time); the period start for the summary. */
|
||||
from: Date;
|
||||
to: Date;
|
||||
done: number;
|
||||
/** Median hours from «in work» to «done»; null without finished stories. */
|
||||
cycleHoursMedian: number | null;
|
||||
/** Share of finished stories accepted without a return from review, 0..1. */
|
||||
firstPassRate: number | null;
|
||||
/** Share of stories that reached review and were sent back, 0..1. */
|
||||
reviewReturnRate: number | null;
|
||||
/** Questions (not notices) per story worked on. */
|
||||
questionsPerStory: number | null;
|
||||
questions: number;
|
||||
storiesWorked: number;
|
||||
runnerHours: number;
|
||||
/** Hours sessions waited for a human answer. */
|
||||
pmWaitHours: number;
|
||||
limitHits: number;
|
||||
spend: Spend;
|
||||
}
|
||||
|
||||
export interface ProviderMetrics {
|
||||
provider: string;
|
||||
sessions: number;
|
||||
stories: number;
|
||||
hours: number;
|
||||
spend: Spend;
|
||||
}
|
||||
|
||||
export interface ProjectMetrics {
|
||||
weeks: number;
|
||||
summary: MetricsBucket;
|
||||
weekly: MetricsBucket[];
|
||||
byProvider: ProviderMetrics[];
|
||||
byEpic: EpicSpend[];
|
||||
}
|
||||
|
||||
const HOUR = 3_600_000;
|
||||
const WORK_STATUSES = new Set(["proposing", "in_progress"]);
|
||||
const BACK_FROM_REVIEW = new Set(["proposing", "in_progress"]);
|
||||
|
||||
/** Monday 00:00 local of the week containing `d`. */
|
||||
export function weekStart(d: Date): Date {
|
||||
const x = new Date(d);
|
||||
x.setHours(0, 0, 0, 0);
|
||||
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
|
||||
return x;
|
||||
}
|
||||
|
||||
function median(xs: number[]): number | null {
|
||||
if (!xs.length) return null;
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
|
||||
}
|
||||
|
||||
interface StoryFacts {
|
||||
taskId: number;
|
||||
started: number | null;
|
||||
doneAt: number | null;
|
||||
reachedReview: boolean;
|
||||
returned: boolean;
|
||||
}
|
||||
|
||||
export async function projectMetrics(db: Db, projectId: number, o: { weeks?: number; now?: Date } = {}): Promise<ProjectMetrics> {
|
||||
const weeks = Math.max(1, Math.min(52, o.weeks ?? 8));
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
const firstWeek = weekStart(new Date(now));
|
||||
firstWeek.setDate(firstWeek.getDate() - 7 * (weeks - 1));
|
||||
const from = firstWeek.getTime();
|
||||
|
||||
const ts = await db.select({ id: tasks.id }).from(tasks).where(eq(tasks.projectId, projectId));
|
||||
const taskIds = ts.map((t) => t.id);
|
||||
// Status history of every story (whole history: a story finished now may have started long ago).
|
||||
const evs = taskIds.length
|
||||
? await db
|
||||
.select({ taskId: events.taskId, payload: events.payload, createdAt: events.createdAt })
|
||||
.from(events)
|
||||
.where(and(eq(events.projectId, projectId), eq(events.type, "task_updated")))
|
||||
.orderBy(events.id)
|
||||
: [];
|
||||
const facts = new Map<number, StoryFacts>();
|
||||
for (const e of evs) {
|
||||
if (e.taskId == null) continue;
|
||||
const p = e.payload as { from?: { status?: string }; to?: { status?: string } } | null;
|
||||
const to = p?.to?.status;
|
||||
if (!to) continue;
|
||||
const f = facts.get(e.taskId) ?? { taskId: e.taskId, started: null, doneAt: null, reachedReview: false, returned: false };
|
||||
const t = e.createdAt.getTime();
|
||||
if (WORK_STATUSES.has(to) && f.started == null) f.started = t;
|
||||
if (to === "review") f.reachedReview = true;
|
||||
if (p?.from?.status === "review" && BACK_FROM_REVIEW.has(to)) f.returned = true;
|
||||
if (to === "done") f.doneAt = t;
|
||||
else if (f.doneAt != null && to !== "done") f.doneAt = null; // reopened
|
||||
facts.set(e.taskId, f);
|
||||
}
|
||||
// Reviewer agent sent it back (PEP-26) — not a first pass either.
|
||||
const rejected = taskIds.length
|
||||
? new Set((await db.select({ taskId: codeReviews.taskId }).from(codeReviews).where(and(eq(codeReviews.projectId, projectId), eq(codeReviews.verdict, "changes")))).map((r) => r.taskId))
|
||||
: new Set<number>();
|
||||
|
||||
const ss = await db.select().from(sessions).where(and(eq(sessions.projectId, projectId), gte(sessions.startedAt, new Date(from))));
|
||||
const qs = await db
|
||||
.select({ taskId: questions.taskId, sessionId: questions.sessionId, kind: questions.kind, createdAt: questions.createdAt, answeredAt: questions.answeredAt, via: questions.answeredVia })
|
||||
.from(questions)
|
||||
.where(and(eq(questions.projectId, projectId), gte(questions.createdAt, new Date(from))));
|
||||
const limits = await db
|
||||
.select({ type: events.type, payload: events.payload, createdAt: events.createdAt })
|
||||
.from(events)
|
||||
.where(and(eq(events.projectId, projectId), inArray(events.type, ["usage_limit", "stop_failure"]), gte(events.createdAt, new Date(from))));
|
||||
|
||||
const bucket = (a: number, b: number): MetricsBucket => {
|
||||
const inRange = (t: number | null | undefined) => t != null && t >= a && t < b;
|
||||
const finished = [...facts.values()].filter((f) => inRange(f.doneAt));
|
||||
const cycles = finished.filter((f) => f.started != null && f.doneAt! >= f.started).map((f) => (f.doneAt! - f.started!) / HOUR);
|
||||
const firstPass = finished.filter((f) => !f.returned && !rejected.has(f.taskId)).length;
|
||||
const reviewed = finished.filter((f) => f.reachedReview);
|
||||
const bSessions = ss.filter((s) => inRange(s.startedAt.getTime()));
|
||||
const bQuestions = qs.filter((q) => inRange(q.createdAt.getTime()) && q.kind !== "attention");
|
||||
const worked = new Set(bSessions.map((s) => s.taskId).filter((x): x is number => x != null));
|
||||
const runnerMs = bSessions.reduce((acc, s) => acc + Math.max(0, Math.min(s.endedAt?.getTime() ?? now, now) - s.startedAt.getTime()), 0);
|
||||
const waitMs = qs
|
||||
.filter((q) => q.sessionId != null && q.answeredAt && q.via !== "system" && inRange(q.createdAt.getTime()))
|
||||
.reduce((acc, q) => acc + (q.answeredAt!.getTime() - q.createdAt.getTime()), 0);
|
||||
const limitHits = limits.filter(
|
||||
(e) => inRange(e.createdAt.getTime()) && (e.type === "usage_limit" || (e.payload as { error?: string } | null)?.error === "rate_limit"),
|
||||
).length;
|
||||
return {
|
||||
from: new Date(a),
|
||||
to: new Date(b),
|
||||
done: finished.length,
|
||||
cycleHoursMedian: median(cycles),
|
||||
firstPassRate: finished.length ? firstPass / finished.length : null,
|
||||
reviewReturnRate: reviewed.length ? reviewed.filter((f) => f.returned || rejected.has(f.taskId)).length / reviewed.length : null,
|
||||
questionsPerStory: worked.size ? bQuestions.length / worked.size : null,
|
||||
questions: bQuestions.length,
|
||||
storiesWorked: worked.size,
|
||||
runnerHours: runnerMs / HOUR,
|
||||
pmWaitHours: waitMs / HOUR,
|
||||
limitHits,
|
||||
spend: spendOf(bSessions, now),
|
||||
};
|
||||
};
|
||||
|
||||
const weekly: MetricsBucket[] = [];
|
||||
for (let i = 0; i < weeks; i++) {
|
||||
const a = new Date(firstWeek);
|
||||
a.setDate(a.getDate() + 7 * i);
|
||||
const b = new Date(a);
|
||||
b.setDate(b.getDate() + 7);
|
||||
weekly.push(bucket(a.getTime(), b.getTime()));
|
||||
}
|
||||
const summary = bucket(from, now + 1);
|
||||
|
||||
const providers = new Map<string, typeof ss>();
|
||||
for (const s of ss) providers.set(s.provider, [...(providers.get(s.provider) ?? []), s]);
|
||||
const byProvider = [...providers.entries()]
|
||||
.map(([provider, rows]) => {
|
||||
const spend = spendOf(rows, now);
|
||||
return { provider, sessions: rows.length, stories: new Set(rows.map((r) => r.taskId).filter(Boolean)).size, hours: spend.minutes / 60, spend };
|
||||
})
|
||||
.sort((a, b) => b.hours - a.hours);
|
||||
|
||||
return { weeks, summary, weekly, byProvider, byEpic: await epicSpend(db, projectId, now) };
|
||||
}
|
||||
|
||||
export const fmtPct = (x: number | null) => (x == null ? "—" : `${Math.round(x * 100)}%`);
|
||||
export const fmtHours = (h: number | null) => (h == null ? "—" : h < 1 ? `${Math.round(h * 60)} мин` : h < 48 ? `${Math.round(h * 10) / 10} ч` : `${Math.round((h / 24) * 10) / 10} дн`);
|
||||
107
packages/core/src/audit.ts
Normal file
107
packages/core/src/audit.ts
Normal file
@ -0,0 +1,107 @@
|
||||
// PEP-48: the journal — events with their authors (person + channel, agent, Peppa itself).
|
||||
import { events, oauthClients, projects, tasks, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, desc, eq, inArray, lt, type SQL } from "drizzle-orm";
|
||||
import { actorColumns, type ActorChannel, type ActorKind } from "./actor.ts";
|
||||
|
||||
/** An event done by the current actor (settings changes and other actions without a session). */
|
||||
export async function logEvent(db: Db, e: { projectId: number; taskId?: number | null; sessionId?: number | null; type: string; payload?: unknown }) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: e.projectId, taskId: e.taskId ?? null, sessionId: e.sessionId ?? null, type: e.type, payload: e.payload ?? null, ...actorColumns(e.sessionId) })
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export const ACTOR_KIND_NAMES: Record<ActorKind, string> = { user: "человек", agent: "агент", system: "Пеппа" };
|
||||
export const ACTOR_CHANNEL_NAMES: Record<ActorChannel, string> = {
|
||||
web: "веб",
|
||||
telegram: "Telegram",
|
||||
mcp: "MCP",
|
||||
cli: "CLI",
|
||||
terminal: "терминал",
|
||||
hook: "хук",
|
||||
watchdog: "вачдог",
|
||||
gitea: "Gitea",
|
||||
};
|
||||
|
||||
export interface JournalEntry {
|
||||
id: number;
|
||||
type: string;
|
||||
payload: unknown;
|
||||
createdAt: Date;
|
||||
projectId: number;
|
||||
projectKey: string;
|
||||
taskId: number | null;
|
||||
taskKey: string | null;
|
||||
sessionId: number | null;
|
||||
actorKind: ActorKind | null;
|
||||
actorChannel: ActorChannel | null;
|
||||
actorLogin: string | null;
|
||||
actorClient: string | null;
|
||||
}
|
||||
|
||||
export interface JournalFilter {
|
||||
/** Restrict to these projects (members' view); undefined = all (superadmin). */
|
||||
projectIds?: number[];
|
||||
projectId?: number;
|
||||
taskId?: number;
|
||||
actorKind?: ActorKind;
|
||||
channel?: ActorChannel;
|
||||
/** Event types to leave out (noisy hook events in the journal). */
|
||||
excludeTypes?: string[];
|
||||
before?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** Hook/watchdog chatter that is not «someone did something». */
|
||||
export const JOURNAL_NOISE = ["turn_end", "notification", "claude_session", "claude_session_end", "input_sent", "auto_continue", "awaiting_review", "awaiting_automerge"];
|
||||
|
||||
export async function listJournal(db: Db, f: JournalFilter = {}): Promise<JournalEntry[]> {
|
||||
if (f.projectIds && !f.projectIds.length) return [];
|
||||
const where: SQL[] = [];
|
||||
if (f.projectIds) where.push(inArray(events.projectId, f.projectIds));
|
||||
if (f.projectId != null) where.push(eq(events.projectId, f.projectId));
|
||||
if (f.taskId != null) where.push(eq(events.taskId, f.taskId));
|
||||
if (f.actorKind) where.push(eq(events.actorKind, f.actorKind));
|
||||
if (f.channel) where.push(eq(events.actorChannel, f.channel));
|
||||
if (f.before) where.push(lt(events.id, f.before));
|
||||
const rows = await db
|
||||
.select({ e: events, projectKey: projects.key, taskNumber: tasks.number, login: users.login, client: oauthClients.name })
|
||||
.from(events)
|
||||
.innerJoin(projects, eq(events.projectId, projects.id))
|
||||
.leftJoin(tasks, eq(events.taskId, tasks.id))
|
||||
.leftJoin(users, eq(events.actorUserId, users.id))
|
||||
.leftJoin(oauthClients, eq(events.actorClientId, oauthClients.id))
|
||||
.where(and(...where))
|
||||
.orderBy(desc(events.id))
|
||||
.limit(Math.min(f.limit ?? 100, 500) * (f.excludeTypes?.length ? 3 : 1));
|
||||
const skip = new Set(f.excludeTypes ?? []);
|
||||
return rows
|
||||
.filter((r) => !skip.has(r.e.type))
|
||||
.slice(0, Math.min(f.limit ?? 100, 500))
|
||||
.map((r) => ({
|
||||
id: r.e.id,
|
||||
type: r.e.type,
|
||||
payload: r.e.payload,
|
||||
createdAt: r.e.createdAt,
|
||||
projectId: r.e.projectId,
|
||||
projectKey: r.projectKey,
|
||||
taskId: r.e.taskId,
|
||||
taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null,
|
||||
sessionId: r.e.sessionId,
|
||||
actorKind: r.e.actorKind,
|
||||
actorChannel: r.e.actorChannel,
|
||||
actorLogin: r.login,
|
||||
actorClient: r.client ?? r.e.actorClientId,
|
||||
}));
|
||||
}
|
||||
|
||||
/** «anna · веб», «pm · MCP (ChatGPT)», «агент · раннер #12», «Пеппа · вачдог». Null for pre-PEP-48 events. */
|
||||
export function actorLabel(e: Pick<JournalEntry, "actorKind" | "actorChannel" | "actorLogin" | "actorClient" | "sessionId">): string | null {
|
||||
if (!e.actorKind) return null;
|
||||
const ch = e.actorChannel ? ACTOR_CHANNEL_NAMES[e.actorChannel] : null;
|
||||
if (e.actorKind === "user") return [e.actorLogin ?? "человек", ch && `${ch}${e.actorClient ? ` (${e.actorClient})` : ""}`].filter(Boolean).join(" · ");
|
||||
if (e.actorKind === "agent") return e.sessionId ? `агент · раннер #${e.sessionId}` : "агент";
|
||||
return ch ? `Пеппа · ${ch}` : "Пеппа";
|
||||
}
|
||||
176
packages/core/src/budgets.ts
Normal file
176
packages/core/src/budgets.ts
Normal file
@ -0,0 +1,176 @@
|
||||
// PEP-43: story budgets (runner minutes, tokens, restarts, cost) and what a story has spent.
|
||||
// Stored in `settings` like autonomy (PEP-23): `budget.project:<id>` is the default for the
|
||||
// project's stories, `budget.task:<id>` replaces it for one story. No row = no limit.
|
||||
import { goals, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { sumTotals, usageTotals, type UsageTotals } from "./usage.ts";
|
||||
|
||||
export const BUDGET_KINDS = ["minutes", "tokens", "restarts", "costUsd"] as const;
|
||||
export type BudgetKind = (typeof BUDGET_KINDS)[number];
|
||||
export type Budget = Partial<Record<BudgetKind, number | null>>;
|
||||
|
||||
export const BUDGET_LABELS: Record<BudgetKind, string> = { minutes: "время", tokens: "токены", restarts: "перезапуски", costUsd: "стоимость" };
|
||||
|
||||
const projectKey = (projectId: number) => `budget.project:${projectId}`;
|
||||
const taskKey = (taskId: number) => `budget.task:${taskId}`;
|
||||
const stateKey = (taskId: number) => `budget.state:${taskId}`;
|
||||
|
||||
/** Keeps positive numbers only; everything else means «no limit». */
|
||||
export function cleanBudget(b: Budget | null | undefined): Budget {
|
||||
const out: Budget = {};
|
||||
for (const k of BUDGET_KINDS) {
|
||||
const v = b?.[k];
|
||||
if (typeof v === "number" && Number.isFinite(v) && v > 0) out[k] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
export const hasLimits = (b: Budget) => BUDGET_KINDS.some((k) => b[k] != null);
|
||||
|
||||
export async function getProjectBudget(db: Db, projectId: number): Promise<Budget> {
|
||||
return cleanBudget(await getSetting<Budget>(db, projectKey(projectId)));
|
||||
}
|
||||
export async function setProjectBudget(db: Db, projectId: number, b: Budget): Promise<void> {
|
||||
const clean = cleanBudget(b);
|
||||
if (hasLimits(clean)) await setSetting(db, projectKey(projectId), clean);
|
||||
else await deleteSetting(db, projectKey(projectId));
|
||||
}
|
||||
|
||||
/** The story's own budget: null = inherits the project's; {} = explicitly unlimited. */
|
||||
export async function getTaskBudget(db: Db, taskId: number): Promise<Budget | null> {
|
||||
const b = await getSetting<Budget>(db, taskKey(taskId));
|
||||
return b ? cleanBudget(b) : null;
|
||||
}
|
||||
export async function setTaskBudget(db: Db, taskId: number, b: Budget | null): Promise<void> {
|
||||
if (b === null) await deleteSetting(db, taskKey(taskId));
|
||||
else await setSetting(db, taskKey(taskId), cleanBudget(b));
|
||||
}
|
||||
|
||||
export interface EffectiveBudget {
|
||||
budget: Budget;
|
||||
source: "task" | "project" | "none";
|
||||
}
|
||||
export async function effectiveBudget(db: Db, task: { id: number; projectId: number }): Promise<EffectiveBudget> {
|
||||
const own = await getTaskBudget(db, task.id);
|
||||
if (own) return { budget: own, source: "task" };
|
||||
const p = await getProjectBudget(db, task.projectId);
|
||||
return { budget: p, source: hasLimits(p) ? "project" : "none" };
|
||||
}
|
||||
|
||||
export interface Spend {
|
||||
minutes: number;
|
||||
tokens: number;
|
||||
costUsd: number | null;
|
||||
costEstimated: boolean;
|
||||
restarts: number;
|
||||
sessions: number;
|
||||
usage: UsageTotals;
|
||||
}
|
||||
|
||||
type SessionRow = Pick<typeof sessions.$inferSelect, "startedAt" | "endedAt" | "generation" | "usage">;
|
||||
|
||||
export function spendOf(rows: SessionRow[], now = Date.now()): Spend {
|
||||
const usage = sumTotals(rows.map((r) => usageTotals(r.usage)));
|
||||
const ms = rows.reduce((a, r) => a + Math.max(0, (r.endedAt?.getTime() ?? now) - r.startedAt.getTime()), 0);
|
||||
const launches = rows.reduce((a, r) => a + Math.max(1, r.generation), 0);
|
||||
return {
|
||||
minutes: Math.round(ms / 60_000),
|
||||
tokens: usage.total,
|
||||
costUsd: usage.costUsd,
|
||||
costEstimated: usage.estimated,
|
||||
restarts: Math.max(0, launches - 1),
|
||||
sessions: rows.length,
|
||||
usage,
|
||||
};
|
||||
}
|
||||
|
||||
export async function taskSpend(db: Db, taskId: number, now = Date.now()): Promise<Spend> {
|
||||
const rows = await db.select().from(sessions).where(eq(sessions.taskId, taskId));
|
||||
return spendOf(rows, now);
|
||||
}
|
||||
|
||||
const spendValue = (s: Spend, k: BudgetKind) => (k === "costUsd" ? (s.costUsd ?? 0) : s[k]);
|
||||
|
||||
/** Limits the story has reached (spent ≥ limit). */
|
||||
export function budgetOver(b: Budget, s: Spend): BudgetKind[] {
|
||||
return BUDGET_KINDS.filter((k) => b[k] != null && spendValue(s, k) >= b[k]!);
|
||||
}
|
||||
|
||||
/** PM pressed «Продлить ×2»: each reached limit grows to max(limit × 2, spent × 1.5). */
|
||||
export function extendBudget(b: Budget, s: Spend): Budget {
|
||||
const out = { ...b };
|
||||
for (const k of budgetOver(b, s)) {
|
||||
const v = Math.max(b[k]! * 2, spendValue(s, k) * 1.5);
|
||||
out[k] = k === "costUsd" ? Math.ceil(v * 100) / 100 : Math.ceil(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface BudgetState {
|
||||
pausedAt: number;
|
||||
over: BudgetKind[];
|
||||
questionId?: number | null;
|
||||
}
|
||||
export async function getBudgetState(db: Db, taskId: number): Promise<BudgetState | null> {
|
||||
return getSetting<BudgetState>(db, stateKey(taskId));
|
||||
}
|
||||
export async function setBudgetState(db: Db, taskId: number, st: BudgetState | null): Promise<void> {
|
||||
if (st) await setSetting(db, stateKey(taskId), st);
|
||||
else await deleteSetting(db, stateKey(taskId));
|
||||
}
|
||||
|
||||
export interface TaskBudgetView extends EffectiveBudget {
|
||||
spend: Spend;
|
||||
over: BudgetKind[];
|
||||
paused: BudgetState | null;
|
||||
}
|
||||
export async function taskBudgetView(db: Db, task: { id: number; projectId: number }, now = Date.now()): Promise<TaskBudgetView> {
|
||||
const eff = await effectiveBudget(db, task);
|
||||
const spend = await taskSpend(db, task.id, now);
|
||||
return { ...eff, spend, over: budgetOver(eff.budget, spend), paused: await getBudgetState(db, task.id) };
|
||||
}
|
||||
|
||||
export function formatBudgetValue(k: BudgetKind, v: number | null | undefined): string {
|
||||
if (v == null) return "∞";
|
||||
if (k === "minutes") return v >= 120 ? `${Math.round((v / 60) * 10) / 10} ч` : `${v} мин`;
|
||||
if (k === "costUsd") return `$${v.toFixed(2)}`;
|
||||
return v.toLocaleString("ru-RU");
|
||||
}
|
||||
|
||||
/** «время 20 мин из 60 мин · токены 3 000 из ∞ · …» */
|
||||
export function describeBudget(v: Pick<TaskBudgetView, "budget" | "spend">): string {
|
||||
return BUDGET_KINDS.map((k) => {
|
||||
const spent = k === "costUsd" ? (v.spend.costUsd == null ? "—" : `${v.spend.costEstimated ? "≈ " : ""}$${v.spend.costUsd.toFixed(2)}`) : formatBudgetValue(k, v.spend[k]);
|
||||
return `${BUDGET_LABELS[k]} ${spent} из ${formatBudgetValue(k, v.budget[k])}`;
|
||||
}).join(" · ");
|
||||
}
|
||||
|
||||
export interface EpicSpend {
|
||||
goalId: number | null;
|
||||
title: string;
|
||||
stories: number;
|
||||
done: number;
|
||||
spend: Spend;
|
||||
}
|
||||
/** Spend per epic of a project (stories without an epic grouped as «без эпика»). */
|
||||
export async function epicSpend(db: Db, projectId: number, now = Date.now()): Promise<EpicSpend[]> {
|
||||
const ts = await db.select({ id: tasks.id, goalId: tasks.goalId, status: tasks.status }).from(tasks).where(eq(tasks.projectId, projectId));
|
||||
const gs = await db.select().from(goals).where(eq(goals.projectId, projectId));
|
||||
const ss = ts.length ? await db.select().from(sessions).where(inArray(sessions.taskId, ts.map((t) => t.id))) : [];
|
||||
const groups = new Map<number | null, { ids: Set<number>; done: number }>();
|
||||
for (const t of ts) {
|
||||
const g = groups.get(t.goalId) ?? { ids: new Set(), done: 0 };
|
||||
g.ids.add(t.id);
|
||||
if (t.status === "done") g.done++;
|
||||
groups.set(t.goalId, g);
|
||||
}
|
||||
return [...groups.entries()]
|
||||
.map(([goalId, g]) => ({
|
||||
goalId,
|
||||
title: goalId == null ? "без эпика" : (gs.find((x) => x.id === goalId)?.title ?? `#${goalId}`),
|
||||
stories: g.ids.size,
|
||||
done: g.done,
|
||||
spend: spendOf(ss.filter((s) => s.taskId != null && g.ids.has(s.taskId)), now),
|
||||
}))
|
||||
.sort((a, b) => b.spend.tokens - a.spend.tokens || b.stories - a.stories);
|
||||
}
|
||||
@ -1,3 +1,4 @@
|
||||
import { actorColumns } from "./actor.ts";
|
||||
// PEP-42: story dependencies. "PAY-3 waits for PAY-2": PAY-3 is blocked until every
|
||||
// predecessor reaches review/done (an archived predecessor doesn't block). Same project only,
|
||||
// no cycles. The backlog dispatcher (PEP-24) skips blocked stories.
|
||||
@ -115,7 +116,7 @@ export async function setDependencies(db: Db, ref: TaskRef, keys: string[]): Pro
|
||||
}
|
||||
|
||||
async function logDeps(db: Db, ref: TaskRef, payload: Record<string, string>) {
|
||||
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_deps", payload });
|
||||
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_deps", payload, ...actorColumns() });
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
}
|
||||
|
||||
|
||||
@ -32,3 +32,8 @@ export * from "./steps.ts";
|
||||
export * from "./preview.ts";
|
||||
export * from "./deps.ts";
|
||||
export * from "./palette.ts";
|
||||
export * from "./actor.ts";
|
||||
export * from "./usage.ts";
|
||||
export * from "./budgets.ts";
|
||||
export * from "./analytics.ts";
|
||||
export * from "./audit.ts";
|
||||
|
||||
@ -3,6 +3,7 @@ import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, desc, eq, inArray, isNull, lte, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { actorColumns } from "./actor.ts";
|
||||
import type { Question, QuestionKind } from "./tasks.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
|
||||
@ -87,7 +88,7 @@ export async function updateSession(
|
||||
export async function logSessionEvent(db: Db, s: Session, type: string, payload?: unknown) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type, payload })
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type, payload, ...actorColumns(s.id) })
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { actorColumns } from "./actor.ts";
|
||||
// What the agent is doing now (PEP-33): every tool call of a Claude runner (PostToolUse hook)
|
||||
// becomes a "step" event of its session. Only the last MAX_STEPS per session are kept, and
|
||||
// steps stay out of the story journal (events of other types).
|
||||
@ -73,7 +74,7 @@ export function describeStep(tool: string, input: Record<string, unknown> = {},
|
||||
|
||||
/** Stores a step and drops what is older than the last MAX_STEPS of the session. */
|
||||
export async function recordStep(db: Db, s: Pick<Session, "id" | "projectId" | "taskId">, step: StepPayload, now = new Date()) {
|
||||
const [row] = await db.insert(events).values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: STEP_EVENT, payload: step, createdAt: now }).returning();
|
||||
const [row] = await db.insert(events).values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: STEP_EVENT, payload: step, createdAt: now, ...actorColumns(s.id) }).returning();
|
||||
// Activity time without notify(): a step is not a status change (the bot needn't wake).
|
||||
await db.update(sessions).set({ lastActivityAt: now }).where(eq(sessions.id, s.id));
|
||||
await db.run(sql`DELETE FROM events WHERE session_id = ${s.id} AND type = ${STEP_EVENT} AND id <= (
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { actorColumns, currentActor, runAsActor } from "./actor.ts";
|
||||
import { events, goals, projects, questions, taskStatus, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, parseTaskKey } from "@peppa/shared";
|
||||
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
|
||||
@ -10,6 +11,7 @@ import { latestReview, type CodeReview } from "./reviews.ts";
|
||||
import { getAutonomy, type AutonomySettings } from "./autonomy.ts";
|
||||
import { reviewPreview, type ReviewPreview } from "./preview.ts";
|
||||
import { blockersOf, dependentsOf, type Blocker } from "./deps.ts";
|
||||
import { taskBudgetView, type TaskBudgetView } from "./budgets.ts";
|
||||
|
||||
export type Task = typeof tasks.$inferSelect;
|
||||
export type TaskStatus = (typeof taskStatus.enumValues)[number];
|
||||
@ -143,7 +145,7 @@ export async function reorderTask(db: Db, ref: TaskRef, r: ReorderTo, columnOf:
|
||||
position = at + 1;
|
||||
}
|
||||
const [task] = await db.update(tasks).set({ position }).where(eq(tasks.id, ref.task.id)).returning();
|
||||
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_reordered", payload: { to: r.to, other: "other" in r ? r.other.key : null } });
|
||||
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_reordered", payload: { to: r.to, other: "other" in r ? r.other.key : null }, ...actorColumns() });
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
return task!;
|
||||
}
|
||||
@ -155,7 +157,7 @@ export async function setTaskArchived(db: Db, ref: TaskRef, archived: boolean):
|
||||
.set({ archivedAt: archived ? new Date() : null, ...(archived ? {} : { position: await nextPosition(db, ref.project.id) }) })
|
||||
.where(eq(tasks.id, ref.task.id))
|
||||
.returning();
|
||||
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: archived ? "task_archived" : "task_restored", payload: {} });
|
||||
await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: archived ? "task_archived" : "task_restored", payload: {}, ...actorColumns() });
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
return task!;
|
||||
}
|
||||
@ -212,6 +214,7 @@ export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, session
|
||||
sessionId,
|
||||
type: "task_updated",
|
||||
payload: { from: pick(ref.task, Object.keys(changed)), to: changed, ...(login ? { login } : {}) },
|
||||
...actorColumns(sessionId),
|
||||
});
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
}
|
||||
@ -240,6 +243,8 @@ export interface TaskDetails {
|
||||
/** PEP-42: stories this one waits for, and stories that wait for it. */
|
||||
blockers: Blocker[];
|
||||
dependents: Array<{ id: number; key: string; title: string; status: TaskStatus }>;
|
||||
/** PEP-43/5: what the story spent and its budget. */
|
||||
budget: TaskBudgetView;
|
||||
}
|
||||
|
||||
export const COMMENT_EVENT = "pm_comment";
|
||||
@ -257,7 +262,7 @@ export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number
|
||||
if (body.length > 8000) throw new PeppaError("Комментарий длиннее 8000 символов");
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body } })
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body }, ...actorColumns() })
|
||||
.returning();
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
return { id: row!.id, login: author.login, text: body, createdAt: row!.createdAt };
|
||||
@ -281,7 +286,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
|
||||
.orderBy(desc(events.id))
|
||||
.limit(20);
|
||||
const incident = await incidentForTask(db, ref.task.id);
|
||||
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref) };
|
||||
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref), budget: await taskBudgetView(db, ref.task) };
|
||||
}
|
||||
|
||||
export interface NewQuestion {
|
||||
@ -329,6 +334,21 @@ export async function answerQuestion(
|
||||
.where(and(eq(questions.id, questionId), isNull(questions.answeredAt)))
|
||||
.returning();
|
||||
if (!row) throw new PeppaError(`Question #${questionId} not found or already answered`);
|
||||
// PEP-48: who answered the agent (Peppa closing its own messages is not an action).
|
||||
if (via !== "system") {
|
||||
const a = currentActor();
|
||||
const actor = a?.kind === "user" ? a : { kind: "user" as const, channel: via };
|
||||
await runAsActor(actor, () =>
|
||||
db.insert(events).values({
|
||||
projectId: row.projectId,
|
||||
taskId: row.taskId,
|
||||
sessionId: row.sessionId,
|
||||
type: "question_answered",
|
||||
payload: { questionId, kind: row.kind, via, answer: answer.length > 500 ? `${answer.slice(0, 500)}…` : answer },
|
||||
...actorColumns(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
await notify(db, { type: "question_answered", questionId });
|
||||
return row;
|
||||
}
|
||||
@ -336,7 +356,7 @@ export async function answerQuestion(
|
||||
export async function reportProgress(db: Db, ref: TaskRef, text: string, sessionId?: number) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "progress", payload: { text } })
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "progress", payload: { text }, ...actorColumns(sessionId) })
|
||||
.returning();
|
||||
await notify(db, { type: "progress", eventId: row!.id });
|
||||
return row!;
|
||||
|
||||
348
packages/core/src/usage.ts
Normal file
348
packages/core/src/usage.ts
Normal file
@ -0,0 +1,348 @@
|
||||
// PEP-5: what agents spend and how much of the subscription limits is left.
|
||||
// Sources: Claude Code's statusLine command (cost, context window, 5h/7d limit windows) and
|
||||
// the session transcript (token usage of every assistant message). Codex/OpenCode report
|
||||
// neither — the UI says «нет данных» rather than inventing numbers.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens } from "@peppa/db";
|
||||
import { eq, inArray, like } from "drizzle-orm";
|
||||
import type { User } from "./users.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
import { isSuperadmin } from "./monitor.ts";
|
||||
|
||||
export type { SessionUsage, UsageTokens };
|
||||
|
||||
export interface UsageWindow {
|
||||
/** Used share of the window, 0..100. */
|
||||
pct: number;
|
||||
resetsAt: number | null;
|
||||
}
|
||||
export interface AccountWindows {
|
||||
fiveHour?: UsageWindow;
|
||||
sevenDay?: UsageWindow;
|
||||
at: number;
|
||||
sessionId?: number;
|
||||
}
|
||||
|
||||
export interface StatusLineData {
|
||||
costUsd?: number;
|
||||
context?: { used: number; size: number; pct: number };
|
||||
tokens?: { input: number; output: number };
|
||||
windows: { fiveHour?: UsageWindow; sevenDay?: UsageWindow };
|
||||
model?: string;
|
||||
}
|
||||
|
||||
const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : undefined);
|
||||
const obj = (v: unknown): Record<string, unknown> | undefined => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined);
|
||||
|
||||
/** ISO string, epoch seconds or epoch ms → ms. */
|
||||
function toMs(v: unknown): number | null {
|
||||
if (typeof v === "string" && !/^\d+(\.\d+)?$/.test(v.trim())) {
|
||||
const t = Date.parse(v);
|
||||
return Number.isNaN(t) ? null : t;
|
||||
}
|
||||
const n = num(v);
|
||||
if (n == null) return null;
|
||||
return n < 1e12 ? Math.round(n * 1000) : Math.round(n);
|
||||
}
|
||||
|
||||
function parseWindow(v: unknown): UsageWindow | undefined {
|
||||
const o = obj(v);
|
||||
if (!o) return undefined;
|
||||
let pct = num(o.used_percentage ?? o.usedPercentage ?? o.percent ?? o.used_percent ?? o.pct);
|
||||
if (pct == null) {
|
||||
const u = num(o.utilization);
|
||||
if (u != null) pct = u <= 1 ? u * 100 : u;
|
||||
}
|
||||
if (pct == null) return undefined;
|
||||
return { pct: Math.max(0, Math.min(100, Math.round(pct * 10) / 10)), resetsAt: toMs(o.resets_at ?? o.resetsAt ?? o.reset_at ?? o.resets) };
|
||||
}
|
||||
|
||||
/** Claude Code statusLine JSON → what Peppa keeps. Tolerant to field name variants (not verified on a live CLI). */
|
||||
export function parseStatusLine(input: unknown): StatusLineData {
|
||||
const j = obj(input) ?? {};
|
||||
const cost = obj(j.cost);
|
||||
const cw = obj(j.context_window ?? j.contextWindow);
|
||||
const rl = obj(j.rate_limits ?? j.rateLimits ?? j.usage_limits);
|
||||
const out: StatusLineData = { windows: {} };
|
||||
const c = num(cost?.total_cost_usd ?? cost?.totalCostUsd);
|
||||
if (c != null) out.costUsd = c;
|
||||
if (cw) {
|
||||
const size = num(cw.context_window_size ?? cw.size);
|
||||
const cur = obj(cw.current_usage);
|
||||
const used = cur ? (num(cur.input_tokens) ?? 0) + (num(cur.cache_read_input_tokens) ?? 0) + (num(cur.cache_creation_input_tokens) ?? 0) : num(cw.used_tokens);
|
||||
const pct = num(cw.used_percentage) ?? (used != null && size ? (used / size) * 100 : undefined);
|
||||
if (size && (used != null || pct != null)) out.context = { used: used ?? Math.round(((pct ?? 0) / 100) * size), size, pct: Math.round((pct ?? 0) * 10) / 10 };
|
||||
const ti = num(cw.total_input_tokens);
|
||||
const to = num(cw.total_output_tokens);
|
||||
if (ti != null || to != null) out.tokens = { input: ti ?? 0, output: to ?? 0 };
|
||||
}
|
||||
if (rl) {
|
||||
const five = parseWindow(rl.five_hour ?? rl.fiveHour ?? rl["5h"] ?? rl.session);
|
||||
const seven = parseWindow(rl.seven_day ?? rl.sevenDay ?? rl["7d"] ?? rl.weekly);
|
||||
if (five) out.windows.fiveHour = five;
|
||||
if (seven) out.windows.sevenDay = seven;
|
||||
}
|
||||
const model = obj(j.model);
|
||||
const m = typeof model?.id === "string" ? model.id : typeof j.model === "string" ? j.model : undefined;
|
||||
if (m) out.model = m;
|
||||
return out;
|
||||
}
|
||||
|
||||
const zero = (): UsageTokens => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
||||
|
||||
/** Sums `message.usage` of assistant entries in a Claude transcript (deduplicated by message id). */
|
||||
export function transcriptUsage(path: string | undefined | null): { tokens: UsageTokens; model?: string } | null {
|
||||
if (!path) return null;
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const byId = new Map<string, UsageTokens>();
|
||||
let model: string | undefined;
|
||||
let anon = 0;
|
||||
for (const line of text.split("\n")) {
|
||||
if (!line.includes('"usage"')) continue;
|
||||
let e: { type?: string; message?: { id?: string; model?: string; usage?: Record<string, unknown> } };
|
||||
try {
|
||||
e = JSON.parse(line);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const u = e.type === "assistant" ? e.message?.usage : undefined;
|
||||
if (!u) continue;
|
||||
if (e.message?.model && e.message.model !== "<synthetic>") model = e.message.model;
|
||||
byId.set(e.message?.id ?? `anon-${anon++}`, {
|
||||
input: num(u.input_tokens) ?? 0,
|
||||
output: num(u.output_tokens) ?? 0,
|
||||
cacheRead: num(u.cache_read_input_tokens) ?? 0,
|
||||
cacheWrite: num(u.cache_creation_input_tokens) ?? 0,
|
||||
});
|
||||
}
|
||||
if (!byId.size) return null;
|
||||
const tokens = zero();
|
||||
for (const t of byId.values()) addTokens(tokens, t);
|
||||
return { tokens, model };
|
||||
}
|
||||
|
||||
function addTokens(a: UsageTokens, b: Partial<UsageTokens>) {
|
||||
a.input += b.input ?? 0;
|
||||
a.output += b.output ?? 0;
|
||||
a.cacheRead += b.cacheRead ?? 0;
|
||||
a.cacheWrite += b.cacheWrite ?? 0;
|
||||
}
|
||||
|
||||
/** API list prices, $ per million tokens — only for an estimate («≈») when Claude reported no cost. */
|
||||
const PRICES: Array<[RegExp, number, number]> = [
|
||||
[/opus/i, 5, 25],
|
||||
[/haiku/i, 1, 5],
|
||||
[/sonnet|claude/i, 3, 15],
|
||||
];
|
||||
export function estimateCost(t: UsageTokens, model?: string): number {
|
||||
const [, inP, outP] = PRICES.find(([re]) => re.test(model ?? "")) ?? PRICES[2]!;
|
||||
return (t.input * inP + t.output * outP + t.cacheRead * inP * 0.1 + t.cacheWrite * inP * 1.25) / 1e6;
|
||||
}
|
||||
|
||||
export const totalTokens = (t: UsageTokens) => t.input + t.output + t.cacheRead + t.cacheWrite;
|
||||
|
||||
export interface UsageTotals {
|
||||
hasData: boolean;
|
||||
tokens: UsageTokens;
|
||||
/** input + output + cache. */
|
||||
total: number;
|
||||
costUsd: number | null;
|
||||
/** The cost is an estimate from list prices, not reported by the agent. */
|
||||
estimated: boolean;
|
||||
context: SessionUsage["context"] | null;
|
||||
}
|
||||
|
||||
export function usageTotals(u: SessionUsage | null | undefined): UsageTotals {
|
||||
const tokens = zero();
|
||||
const convs = Object.values(u?.convs ?? {});
|
||||
for (const c of convs) addTokens(tokens, c);
|
||||
if (!convs.length) for (const g of Object.values(u?.tokensByGen ?? {})) addTokens(tokens, g);
|
||||
const costs = Object.values(u?.costByGen ?? {});
|
||||
const total = totalTokens(tokens);
|
||||
let costUsd: number | null = costs.length ? costs.reduce((a, b) => a + b, 0) : null;
|
||||
let estimated = false;
|
||||
if (costUsd == null && total > 0) {
|
||||
costUsd = convs.length ? convs.reduce((a, c) => a + estimateCost(c, c.model), 0) : estimateCost(tokens, u?.model);
|
||||
estimated = true;
|
||||
}
|
||||
return { hasData: total > 0 || costUsd != null || !!u?.context, tokens, total, costUsd, estimated, context: u?.context ?? null };
|
||||
}
|
||||
|
||||
export function sumTotals(list: UsageTotals[]): UsageTotals {
|
||||
const tokens = zero();
|
||||
let cost: number | null = null;
|
||||
let estimated = false;
|
||||
for (const t of list) {
|
||||
addTokens(tokens, t.tokens);
|
||||
if (t.costUsd != null) cost = (cost ?? 0) + t.costUsd;
|
||||
estimated ||= t.estimated;
|
||||
}
|
||||
return { hasData: list.some((t) => t.hasData), tokens, total: totalTokens(tokens), costUsd: cost, estimated, context: null };
|
||||
}
|
||||
|
||||
/** Applies `fn` to the session's usage inside one write transaction (statusLine and Stop hooks race). */
|
||||
function mutateUsage(db: Db, sessionId: number, fn: (u: SessionUsage) => boolean) {
|
||||
db.transaction(
|
||||
(tx) => {
|
||||
const row = tx.select({ usage: sessions.usage }).from(sessions).where(eq(sessions.id, sessionId)).get();
|
||||
if (!row) return;
|
||||
const u: SessionUsage = structuredClone(row.usage ?? {});
|
||||
if (fn(u)) tx.update(sessions).set({ usage: u }).where(eq(sessions.id, sessionId)).run();
|
||||
},
|
||||
{ behavior: "immediate" },
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_WRITE_MS = 20_000;
|
||||
|
||||
/** statusLine fired: cost and context on the session, limit windows on its account. Throttled. */
|
||||
export async function recordStatusLine(
|
||||
db: Db,
|
||||
s: { id: number; generation: number; subscriptionId: number | null },
|
||||
data: StatusLineData,
|
||||
now = Date.now(),
|
||||
): Promise<boolean> {
|
||||
let wrote = false;
|
||||
mutateUsage(db, s.id, (u) => {
|
||||
const gen = String(s.generation);
|
||||
const prevCost = u.costByGen?.[gen];
|
||||
const changed =
|
||||
(data.costUsd != null && Math.abs((prevCost ?? -1) - data.costUsd) >= 0.01) ||
|
||||
(data.context != null && Math.abs((u.context?.pct ?? -100) - data.context.pct) >= 1) ||
|
||||
(data.tokens != null && u.tokensByGen?.[gen]?.output !== data.tokens.output);
|
||||
if (!changed && now - (u.at ?? 0) < STATUS_WRITE_MS) return false;
|
||||
if (data.costUsd != null) u.costByGen = { ...u.costByGen, [gen]: data.costUsd };
|
||||
if (data.tokens) u.tokensByGen = { ...u.tokensByGen, [gen]: data.tokens };
|
||||
if (data.context) u.context = data.context;
|
||||
if (data.model) u.model = data.model;
|
||||
u.at = now;
|
||||
wrote = true;
|
||||
return true;
|
||||
});
|
||||
if (data.windows.fiveHour || data.windows.sevenDay) {
|
||||
const key = accountKey(s.subscriptionId);
|
||||
const prev = await getAccountWindows(db, key);
|
||||
const same = (a?: UsageWindow, b?: UsageWindow) => (a?.pct ?? null) === (b?.pct ?? null) && (a?.resetsAt ?? null) === (b?.resetsAt ?? null);
|
||||
if (!prev || !same(prev.fiveHour, data.windows.fiveHour) || !same(prev.sevenDay, data.windows.sevenDay) || now - prev.at >= STATUS_WRITE_MS) {
|
||||
const next: AccountWindows = { fiveHour: data.windows.fiveHour ?? prev?.fiveHour, sevenDay: data.windows.sevenDay ?? prev?.sevenDay, at: now, sessionId: s.id };
|
||||
await db
|
||||
.insert(settings)
|
||||
.values({ key, value: next })
|
||||
.onConflictDoUpdate({ target: settings.key, set: { value: next, updatedAt: new Date(now) } });
|
||||
wrote = true;
|
||||
}
|
||||
}
|
||||
return wrote;
|
||||
}
|
||||
|
||||
/** Turn ended: token totals of the conversation from its transcript. */
|
||||
export function recordTranscriptUsage(db: Db, sessionId: number, conversationId: string, usage: { tokens: UsageTokens; model?: string }, now = Date.now()) {
|
||||
mutateUsage(db, sessionId, (u) => {
|
||||
u.convs = { ...u.convs, [conversationId]: { ...usage.tokens, ...(usage.model ? { model: usage.model } : {}) } };
|
||||
if (usage.model) u.model = usage.model;
|
||||
u.at = now;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// ── accounts (subscription or this machine's login) ───────────────────────────────
|
||||
export const accountKey = (subscriptionId: number | null | undefined) => `usage.account:${subscriptionId ? `sub:${subscriptionId}` : "machine"}`;
|
||||
|
||||
export async function getAccountWindows(db: Db, key: string): Promise<AccountWindows | null> {
|
||||
const [row] = await db.select().from(settings).where(eq(settings.key, key));
|
||||
return (row?.value as AccountWindows | undefined) ?? null;
|
||||
}
|
||||
|
||||
export const STALE_USAGE_MS = 6 * 3_600_000;
|
||||
|
||||
export interface WindowView {
|
||||
/** null once the reset time has passed. */
|
||||
pct: number | null;
|
||||
resetsAt: Date | null;
|
||||
reset: boolean;
|
||||
}
|
||||
export function windowView(w: UsageWindow | undefined, now = Date.now()): WindowView | null {
|
||||
if (!w) return null;
|
||||
const reset = w.resetsAt != null && w.resetsAt <= now;
|
||||
return { pct: reset ? null : w.pct, resetsAt: w.resetsAt ? new Date(w.resetsAt) : null, reset };
|
||||
}
|
||||
|
||||
export interface AccountUsage {
|
||||
key: string;
|
||||
subscriptionId: number | null;
|
||||
name: string;
|
||||
provider: string;
|
||||
fiveHour: WindowView | null;
|
||||
sevenDay: WindowView | null;
|
||||
at: Date | null;
|
||||
stale: boolean;
|
||||
/** PEP-56/67: the subscription is marked limited until this time. */
|
||||
limitedUntil: Date | null;
|
||||
}
|
||||
|
||||
/** Highest current window share of an account (for sorting / the top bar). */
|
||||
export const accountPeak = (a: AccountUsage) => Math.max(a.fiveHour?.pct ?? -1, a.sevenDay?.pct ?? -1);
|
||||
|
||||
/**
|
||||
* Accounts a user should see: a superadmin — all; others — the subscriptions of their
|
||||
* projects' pools, plus this machine's login when one of their projects has no pool.
|
||||
*/
|
||||
export async function accountUsageForUser(db: Db, user: Pick<User, "id" | "login">, now = Date.now()): Promise<AccountUsage[]> {
|
||||
const admin = await isSuperadmin(db, user);
|
||||
let subIds: number[] | null = null; // null = all
|
||||
let machine = true;
|
||||
if (!admin) {
|
||||
const ids = await userProjectIds(db, user.id);
|
||||
const ps = ids.length ? await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(inArray(projects.id, ids)) : [];
|
||||
const poolIds = [...new Set(ps.map((p) => p.poolId).filter((x): x is number => x != null))];
|
||||
machine = ps.some((p) => p.poolId == null);
|
||||
subIds = poolIds.length
|
||||
? (await db.select({ id: subscriptionPoolMembers.subscriptionId }).from(subscriptionPoolMembers).where(inArray(subscriptionPoolMembers.poolId, poolIds))).map((r) => r.id)
|
||||
: [];
|
||||
}
|
||||
return listAccountUsage(db, { subscriptionIds: subIds, machine, now });
|
||||
}
|
||||
|
||||
export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] | null; machine?: boolean; now?: number } = {}): Promise<AccountUsage[]> {
|
||||
const now = o.now ?? Date.now();
|
||||
const rows = await db.select().from(settings).where(like(settings.key, "usage.account:%"));
|
||||
const byKey = new Map(rows.map((r) => [r.key, r.value as AccountWindows]));
|
||||
const subs = o.subscriptionIds === undefined || o.subscriptionIds === null ? await db.select().from(subscriptions) : o.subscriptionIds.length ? await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)) : [];
|
||||
const view = (key: string, base: Omit<AccountUsage, "key" | "fiveHour" | "sevenDay" | "at" | "stale">): AccountUsage => {
|
||||
const w = byKey.get(key);
|
||||
return { key, ...base, fiveHour: windowView(w?.fiveHour, now), sevenDay: windowView(w?.sevenDay, now), at: w ? new Date(w.at) : null, stale: !!w && now - w.at > STALE_USAGE_MS };
|
||||
};
|
||||
const out = subs.map((s) =>
|
||||
view(accountKey(s.id), { subscriptionId: s.id, name: s.name, provider: s.provider, limitedUntil: s.status === "limited" && s.limitedUntil && s.limitedUntil.getTime() > now ? s.limitedUntil : null }),
|
||||
);
|
||||
if (o.machine !== false && (byKey.has(accountKey(null)) || !out.length)) {
|
||||
out.push(view(accountKey(null), { subscriptionId: null, name: "Вход машины", provider: "claude", limitedUntil: null }));
|
||||
}
|
||||
return out.sort((a, b) => accountPeak(b) - accountPeak(a));
|
||||
}
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
|
||||
/** «5 ч 42% (сброс 14:30) · 7 д 18%» — one line for the bot and MCP. */
|
||||
export function describeAccount(a: AccountUsage): string {
|
||||
const w = (label: string, v: WindowView | null) => (!v ? null : v.reset ? `${label} сброшено` : `${label} ${Math.round(v.pct!)}%${v.resetsAt ? ` (сброс ${hhmm(v.resetsAt)})` : ""}`);
|
||||
const parts = [w("5 ч", a.fiveHour), w("7 д", a.sevenDay)].filter(Boolean);
|
||||
const limited = a.limitedUntil ? ` · лимит до ${hhmm(a.limitedUntil)}` : "";
|
||||
if (!parts.length) return `${a.name}: нет данных${limited}`;
|
||||
return `${a.name}: ${parts.join(" · ")}${limited}${a.stale && a.at ? ` · устарело (${Math.round((Date.now() - a.at.getTime()) / 3_600_000)} ч назад)` : ""}`;
|
||||
}
|
||||
|
||||
export const fmtTokens = (n: number) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)} млн` : n >= 1e4 ? `${Math.round(n / 1e3)} тыс.` : n.toLocaleString("ru-RU"));
|
||||
export const fmtCost = (t: Pick<UsageTotals, "costUsd" | "estimated">) => (t.costUsd == null ? "—" : `${t.estimated ? "≈ " : ""}$${t.costUsd.toFixed(2)}`);
|
||||
|
||||
/** «1,5 млн токенов · ≈ $3.20 · контекст 34%» — or «нет данных». */
|
||||
export function describeUsage(u: SessionUsage | null | undefined): string {
|
||||
const t = usageTotals(u);
|
||||
if (!t.hasData) return "нет данных";
|
||||
return [t.total ? `${fmtTokens(t.total)} токенов` : null, t.costUsd != null ? fmtCost(t) : null, t.context ? `контекст ${Math.round(t.context.pct)}%` : null].filter(Boolean).join(" · ");
|
||||
}
|
||||
6
packages/db/migrations/0010_usage_audit.sql
Normal file
6
packages/db/migrations/0010_usage_audit.sql
Normal file
@ -0,0 +1,6 @@
|
||||
ALTER TABLE `events` ADD `actor_kind` text;--> statement-breakpoint
|
||||
ALTER TABLE `events` ADD `actor_user_id` integer REFERENCES users(id) ON DELETE set null;--> statement-breakpoint
|
||||
ALTER TABLE `events` ADD `actor_channel` text;--> statement-breakpoint
|
||||
ALTER TABLE `events` ADD `actor_client_id` text;--> statement-breakpoint
|
||||
CREATE INDEX `events_created_at` ON `events` (`created_at`);--> statement-breakpoint
|
||||
ALTER TABLE `sessions` ADD `usage` text;
|
||||
3268
packages/db/migrations/meta/0010_snapshot.json
Normal file
3268
packages/db/migrations/meta/0010_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -71,6 +71,13 @@
|
||||
"when": 1794620281978,
|
||||
"tag": "0009_runners",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "6",
|
||||
"when": 1794621020730,
|
||||
"tag": "0010_usage_audit",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -279,6 +279,9 @@ export const sessions = sqliteTable("sessions", {
|
||||
name: text("name"),
|
||||
// PEP-27: the runner's own git worktree (null = the project's working copy).
|
||||
workspacePath: text("workspace_path"),
|
||||
// PEP-5: tokens (per conversation, from the transcript), cost (per generation, from the
|
||||
// statusLine), context window — see core/usage.ts.
|
||||
usage: text("usage", { mode: "json" }).$type<SessionUsage>(),
|
||||
status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"),
|
||||
lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }),
|
||||
startedAt: createdAt(),
|
||||
@ -327,16 +330,42 @@ export const questions = sqliteTable("questions", {
|
||||
answeredAt: integer("answered_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
export type UsageTokens = { input: number; output: number; cacheRead: number; cacheWrite: number };
|
||||
/** PEP-5: what a session spent (core/usage.ts). */
|
||||
export type SessionUsage = {
|
||||
/** Tokens per Claude conversation, summed from the transcript (resume continues the same file). */
|
||||
convs?: Record<string, UsageTokens & { model?: string }>;
|
||||
/** statusLine `cost.total_cost_usd` per runner generation (the counter restarts with the process). */
|
||||
costByGen?: Record<string, number>;
|
||||
/** statusLine token totals per generation — fallback when there is no transcript. */
|
||||
tokensByGen?: Record<string, { input: number; output: number }>;
|
||||
context?: { used: number; size: number; pct: number };
|
||||
model?: string;
|
||||
at?: number;
|
||||
};
|
||||
|
||||
export const actorKinds = ["user", "agent", "system"] as const;
|
||||
export const actorChannels = ["web", "telegram", "mcp", "cli", "terminal", "hook", "watchdog", "gitea"] as const;
|
||||
|
||||
/** Event log: hook / watchdog events, progress reports, status changes. */
|
||||
export const events = sqliteTable("events", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
||||
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
||||
type: text("type").notNull(),
|
||||
payload: text("payload", { mode: "json" }),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
export const events = sqliteTable(
|
||||
"events",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
||||
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
||||
type: text("type").notNull(),
|
||||
payload: text("payload", { mode: "json" }),
|
||||
// PEP-48: who did it (core/actor.ts). Null on events older than PEP-48.
|
||||
actorKind: text("actor_kind", { enum: actorKinds }),
|
||||
actorUserId: integer("actor_user_id").references(() => users.id, { onDelete: "set null" }),
|
||||
actorChannel: text("actor_channel", { enum: actorChannels }),
|
||||
actorClientId: text("actor_client_id"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("events_created_at").on(t.createdAt)],
|
||||
);
|
||||
|
||||
/** Small key/value store for service state (Telegram offset, pairing, binding). */
|
||||
export const settings = sqliteTable("settings", {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { agentAutonomyNote, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
|
||||
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 в этом же ходе.",
|
||||
@ -35,6 +35,9 @@ export function formatTask(d: TaskDetails): string {
|
||||
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));
|
||||
@ -82,3 +85,23 @@ export function formatIncident(i: Incident): string {
|
||||
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");
|
||||
}
|
||||
|
||||
@ -25,6 +25,7 @@ import {
|
||||
resolveTask,
|
||||
TASK_STATUSES,
|
||||
updateTask,
|
||||
setDefaultActor,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { requestReview, reviewGate } from "@peppa/runner";
|
||||
@ -36,6 +37,8 @@ const projectFile = findProjectFile(process.env.PEPPA_PROJECT_DIR ?? process.cwd
|
||||
const defaultKey = projectFile?.data.key;
|
||||
// Set by the runner for sessions it starts; absent for a manual `claude`.
|
||||
const sessionId = process.env.PEPPA_SESSION_ID ? Number(process.env.PEPPA_SESSION_ID) : undefined;
|
||||
// PEP-48: this server acts for the agent (its tool calls are the agent's actions).
|
||||
setDefaultActor({ kind: "agent", channel: "mcp" });
|
||||
|
||||
const server = new McpServer({ name: "peppa", version: "0.1.0" });
|
||||
|
||||
|
||||
@ -36,13 +36,16 @@ import {
|
||||
progressLabel,
|
||||
setDependencies,
|
||||
type User,
|
||||
accountUsageForUser,
|
||||
describeAccount,
|
||||
projectMetrics,
|
||||
} from "@peppa/core";
|
||||
import { questions, projects, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, loadEnv } from "@peppa/shared";
|
||||
import { applyPlan, archiveTask, planEpic, reorderBoardTask, type PlannedStory, currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
|
||||
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { formatIncident, formatTask } from "./format.ts";
|
||||
import { formatIncident, formatMetrics, formatTask } from "./format.ts";
|
||||
|
||||
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
|
||||
const COLUMNS = ["backlog", "in_progress", "review", "done"] as const;
|
||||
@ -269,6 +272,20 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
|
||||
},
|
||||
);
|
||||
|
||||
// PEP-5: subscription limit windows; PEP-47: factory metrics.
|
||||
tool("get_usage", "Subscription usage limits the user's agents run on: share of the 5-hour and 7-day windows used and when they reset, subscriptions in a limit. «нет данных» = no agent reported it yet.", {}, true, async () => {
|
||||
const accounts = await accountUsageForUser(db, user);
|
||||
return accounts.length ? accounts.map((a) => `- ${describeAccount(a)}`).join("\n") : "нет данных о лимитах";
|
||||
});
|
||||
|
||||
tool(
|
||||
"get_metrics",
|
||||
"Factory metrics of a project for the last N weeks: stories done, median cycle time (in work → done), share accepted on the first pass, review return rate, PM questions per story, runner hours, hours agents waited for the PM, limit hits, tokens and cost («≈» = estimate); weekly trend and split by agent provider and epic.",
|
||||
{ project: projectArg, weeks: z.number().int().min(1).max(52).optional().describe("Period in weeks, default 8") },
|
||||
true,
|
||||
async ({ project, weeks }) => formatMetrics(await projectMetrics(db, (await ownedProject(project)).id, { weeks })),
|
||||
);
|
||||
|
||||
tool("get_task", "Get a story: description, epic, status, OpenSpec change, PM questions and comments, 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}`;
|
||||
|
||||
123
packages/runner/src/budgets.ts
Normal file
123
packages/runner/src/budgets.ts
Normal file
@ -0,0 +1,123 @@
|
||||
// PEP-43: a story over its budget is paused — the current turn is interrupted (the process
|
||||
// and the conversation stay), the agent is not pushed or relaunched automatically, and the
|
||||
// PM decides: extend ×2, remove the limit, or stop. Nothing is killed silently.
|
||||
import {
|
||||
answerQuestion,
|
||||
askPm,
|
||||
budgetOver,
|
||||
describeBudget,
|
||||
effectiveBudget,
|
||||
extendBudget,
|
||||
getBudgetState,
|
||||
hasLimits,
|
||||
listSessions,
|
||||
logSessionEvent,
|
||||
PeppaError,
|
||||
setBudgetState,
|
||||
setTaskBudget,
|
||||
taskSpend,
|
||||
updateSession,
|
||||
BUDGET_LABELS,
|
||||
type Question,
|
||||
type SessionView,
|
||||
} from "@peppa/core";
|
||||
import { tasks, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import * as tmux from "./tmux.ts";
|
||||
import { onAnswer, resolveTaskById, sendToSession, stopSession } from "./sessions.ts";
|
||||
|
||||
export const BUDGET_EXTEND = "➕ Продлить ×2";
|
||||
export const BUDGET_UNLIMIT = "♾ Снять лимит";
|
||||
export const BUDGET_STOP = "⏹ Остановить";
|
||||
|
||||
/** Watchdog: stories with a live runner that reached a budget limit get paused. */
|
||||
export async function budgetTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
const live = await listSessions(db, { active: true });
|
||||
const byTask = new Map<number, SessionView[]>();
|
||||
for (const s of live) if (s.taskId != null && !s.tmuxName.startsWith("pending-")) byTask.set(s.taskId, [...(byTask.get(s.taskId) ?? []), s]);
|
||||
let paused = 0;
|
||||
for (const [taskId, ss] of byTask) {
|
||||
if (await getBudgetState(db, taskId)) continue;
|
||||
const [task] = await db.select({ id: tasks.id, projectId: tasks.projectId }).from(tasks).where(eq(tasks.id, taskId));
|
||||
if (!task) continue;
|
||||
const { budget } = await effectiveBudget(db, task);
|
||||
if (!hasLimits(budget)) continue;
|
||||
const spend = await taskSpend(db, taskId, now);
|
||||
const over = budgetOver(budget, spend);
|
||||
if (!over.length) continue;
|
||||
await pauseStory(db, taskId, ss, over, describeBudget({ budget, spend }), now);
|
||||
o.log?.(`${ss[0]!.taskKey}: budget reached (${over.join(", ")}), paused`);
|
||||
paused++;
|
||||
}
|
||||
return paused;
|
||||
}
|
||||
|
||||
async function pauseStory(db: Db, taskId: number, ss: SessionView[], over: string[], summary: string, now: number) {
|
||||
// Recorded first: a Stop hook firing right after the interrupt must already see the pause.
|
||||
await setBudgetState(db, taskId, { pausedAt: now, over: over as never, questionId: null });
|
||||
for (const s of ss) {
|
||||
// Escape interrupts the agent's turn; the process and the conversation stay for «extend».
|
||||
if (s.status === "running" || s.status === "starting" || s.status === "stalled") await tmux.sendKeys(s.tmuxName, "Escape").catch(() => {});
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date(now) });
|
||||
await logSessionEvent(db, s, "budget_paused", { over, summary });
|
||||
}
|
||||
const ref = await resolveTaskById(db, taskId);
|
||||
const names = over.map((k) => BUDGET_LABELS[k as keyof typeof BUDGET_LABELS] ?? k).join(", ");
|
||||
const q = await askPm(db, ref, {
|
||||
kind: "question",
|
||||
text: `💸 ${ref.key}: исчерпан бюджет (${names}). Агент на паузе — ход прерван, разговор сохранён.\n\n${summary}`,
|
||||
options: [BUDGET_EXTEND, BUDGET_UNLIMIT, BUDGET_STOP],
|
||||
});
|
||||
await setBudgetState(db, taskId, { pausedAt: now, over: over as never, questionId: q.id });
|
||||
}
|
||||
|
||||
/** Resumes paused live runners of the story with a message. */
|
||||
async function continueStory(db: Db, taskId: number, text: string) {
|
||||
for (const s of await listSessions(db, { active: true, taskId })) {
|
||||
if (!(await tmux.hasSession(s.tmuxName))) continue;
|
||||
await sendToSession(db, s.id, text).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** The PM's answer to a budget question (`onAnswer` registry). */
|
||||
export async function onBudgetAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
|
||||
if (!q.taskId) return false;
|
||||
const st = await getBudgetState(db, q.taskId);
|
||||
if (!st || st.questionId !== q.id) return false;
|
||||
const ref = await resolveTaskById(db, q.taskId);
|
||||
const text = answer.trim();
|
||||
await setBudgetState(db, q.taskId, null);
|
||||
if (text.startsWith(BUDGET_EXTEND) || /^продл/i.test(text)) {
|
||||
const { budget } = await effectiveBudget(db, ref.task);
|
||||
const next = extendBudget(budget, await taskSpend(db, ref.task.id));
|
||||
await setTaskBudget(db, ref.task.id, next);
|
||||
await continueStory(db, ref.task.id, `Бюджет ${ref.key} продлён PM (${describeBudget({ budget: next, spend: await taskSpend(db, ref.task.id) })}). Продолжай работу с того места, где остановился.`);
|
||||
return true;
|
||||
}
|
||||
if (text.startsWith(BUDGET_UNLIMIT) || /^сн(ять|яли|ими)/i.test(text)) {
|
||||
await setTaskBudget(db, ref.task.id, {});
|
||||
await continueStory(db, ref.task.id, `PM снял лимит бюджета ${ref.key}. Продолжай работу с того места, где остановился.`);
|
||||
return true;
|
||||
}
|
||||
for (const s of await listSessions(db, { active: true, taskId: ref.task.id })) await stopSession(db, s.id);
|
||||
return true;
|
||||
}
|
||||
onAnswer(onBudgetAnswer);
|
||||
|
||||
/**
|
||||
* The PM changed the story's budget in the card: a pause the new budget no longer
|
||||
* justifies is lifted (its question closed) and the runner continues.
|
||||
*/
|
||||
export async function budgetChanged(db: Db, taskId: number): Promise<void> {
|
||||
const st = await getBudgetState(db, taskId);
|
||||
if (!st) return;
|
||||
const ref = await resolveTaskById(db, taskId);
|
||||
const { budget } = await effectiveBudget(db, ref.task);
|
||||
if (budgetOver(budget, await taskSpend(db, taskId)).length) return;
|
||||
await setBudgetState(db, taskId, null);
|
||||
if (st.questionId) {
|
||||
await answerQuestion(db, st.questionId, "(бюджет изменён в карточке)", "system").catch(() => {});
|
||||
}
|
||||
await continueStory(db, taskId, `Бюджет ${ref.key} изменён PM. Продолжай работу с того места, где остановился.`);
|
||||
}
|
||||
@ -3,7 +3,7 @@ import { answerQuestion, dropQueuedTask, getQuestion, listSessions, PeppaError,
|
||||
import { tasks, projects, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { stopSession, type StartOptions } from "./sessions.ts";
|
||||
import { assertBudgetOpen, stopSession, type StartOptions } from "./sessions.ts";
|
||||
import { cleanupWorktree, releaseRunner, runnerFollowsQueue, startTaskOnRunner } from "./runners.ts";
|
||||
import { mergeTaskPr } from "./ci-feedback.ts";
|
||||
import { syncWorkspace } from "./workspace-sync.ts";
|
||||
@ -42,6 +42,7 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
|
||||
const from = columnOf(ref.task.status);
|
||||
let stopped = 0;
|
||||
if (to === "in_progress") {
|
||||
if ((await activeSessions(db, ref.task.id)).length === 0) await assertBudgetOpen(db, ref.task.id);
|
||||
if (from !== "in_progress") await updateTask(db, ref, { status: "in_progress" });
|
||||
// PEP-10: by the runner settings — a new runner, or a free/queued runner of the project.
|
||||
if ((await activeSessions(db, ref.task.id)).length === 0 && (await queuedItems(db, { taskId: ref.task.id })).length === 0) {
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { actorColumns } from "@peppa/core";
|
||||
// Gitea → Peppa (PEP-46): issues become stories, comments and "changes requested" reviews in
|
||||
// a story's PR go to its agent, a PR merged by hand in Gitea closes the story; a finished
|
||||
// story closes its issue. CI results are handled in ci-feedback.ts (PEP-57).
|
||||
@ -64,7 +65,7 @@ export async function giteaLoginHasAccess(db: Db, project: Project, login: strin
|
||||
}
|
||||
|
||||
async function logProjectEvent(db: Db, project: Project, type: string, payload: Record<string, unknown>, taskId?: number) {
|
||||
await db.insert(events).values({ projectId: project.id, taskId, type, payload });
|
||||
await db.insert(events).values({ projectId: project.id, taskId, type, payload, ...actorColumns() });
|
||||
}
|
||||
|
||||
export interface IssueImport {
|
||||
|
||||
@ -8,8 +8,16 @@ import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
describeStep,
|
||||
getAutonomy,
|
||||
recordStep,
|
||||
describeUsage,
|
||||
getAutonomy,
|
||||
getBudgetState,
|
||||
parseStatusLine,
|
||||
recordStatusLine,
|
||||
recordTranscriptUsage,
|
||||
setDefaultActor,
|
||||
transcriptUsage,
|
||||
usageTotals,
|
||||
getQuestion,
|
||||
getReviewSettings,
|
||||
latestReview,
|
||||
@ -185,6 +193,12 @@ const NUDGE = (key: string) =>
|
||||
*/
|
||||
async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise<unknown> {
|
||||
await logSessionEvent(db, s, "turn_end", { text });
|
||||
// PEP-43: the story's budget is spent — the PM was asked; don't push the agent further.
|
||||
if (s.taskId && (await getBudgetState(db, s.taskId))) {
|
||||
await logSessionEvent(db, s, "budget_hold", {});
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||||
return null;
|
||||
}
|
||||
// PEP-39: the subscription is near its limit — end the turn here (no nudge, no ping);
|
||||
// the watchdog moves the session to a free subscription at this boundary.
|
||||
if (s.rotateReason && (await pendingSessionQuestions(db, s.id)).length === 0) {
|
||||
@ -240,6 +254,41 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
|
||||
return null;
|
||||
}
|
||||
|
||||
/** PEP-5: token totals of the conversation, from its transcript. */
|
||||
function saveTranscriptUsage(db: Db, s: SessionView, input: HookInput) {
|
||||
const u = transcriptUsage(input.transcript_path);
|
||||
const conv = input.session_id ?? s.conversationId;
|
||||
if (u && conv) recordTranscriptUsage(db, s.id, conv, u);
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-5: Claude's statusLine command. Prints the status line (one line, must be quick) and
|
||||
* records cost / context / limit windows. Never throws: a broken status line is still a line.
|
||||
*/
|
||||
async function statusLine(input: Record<string, unknown>): Promise<void> {
|
||||
const sessionId = Number(process.env.PEPPA_SESSION_ID);
|
||||
const data = parseStatusLine(input);
|
||||
let line = "Пеппа";
|
||||
try {
|
||||
if (sessionId) {
|
||||
const db = createDb();
|
||||
const s = await getSession(db, sessionId);
|
||||
if (Number(process.env.PEPPA_GENERATION) === s.generation) {
|
||||
await recordStatusLine(db, s, data);
|
||||
line = `Пеппа ${s.taskKey ?? `#${s.id}`}`;
|
||||
const fresh = await getSession(db, sessionId);
|
||||
if (usageTotals(fresh.usage).hasData) line += ` · ${describeUsage(fresh.usage)}`;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log(`statusline session=${sessionId}: ${(e as Error).message}`);
|
||||
}
|
||||
const w = data.windows;
|
||||
if (w.fiveHour) line += ` · 5ч ${Math.round(w.fiveHour.pct)}%`;
|
||||
if (w.sevenDay) line += ` · 7д ${Math.round(w.sevenDay.pct)}%`;
|
||||
process.stdout.write(`${line}\n`);
|
||||
}
|
||||
|
||||
async function handle(event: string, input: HookInput): Promise<void> {
|
||||
const sessionId = Number(process.env.PEPPA_SESSION_ID);
|
||||
if (!sessionId) return; // manual `claude`, not started by Peppa
|
||||
@ -290,6 +339,7 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
break;
|
||||
|
||||
case "stop": {
|
||||
saveTranscriptUsage(db, s, input);
|
||||
const res = await turnEnd(db, s, input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path), true);
|
||||
if (res) output(res);
|
||||
break;
|
||||
@ -326,6 +376,7 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
}
|
||||
|
||||
case "session-end":
|
||||
saveTranscriptUsage(db, s, input);
|
||||
// /clear and /resume end a Claude session inside a live process, so this is not
|
||||
// the process exiting; the watchdog decides that from the tmux pane.
|
||||
await logSessionEvent(db, s, "claude_session_end", { reason: input.reason });
|
||||
@ -344,8 +395,11 @@ if (event !== "codex-notify") {
|
||||
raw = readFileSync(0, "utf8");
|
||||
} catch {}
|
||||
}
|
||||
// PEP-48: hooks act as the session's agent (answers typed into the terminal are a person's).
|
||||
setDefaultActor({ kind: "agent", channel: "hook" });
|
||||
try {
|
||||
await handle(event, raw ? (JSON.parse(raw) as HookInput) : {});
|
||||
if (event === "statusline") await statusLine(raw ? JSON.parse(raw) : {});
|
||||
else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {});
|
||||
} catch (e) {
|
||||
log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`);
|
||||
}
|
||||
|
||||
@ -29,3 +29,4 @@ export * from "./gitea-events.ts";
|
||||
export * from "./planner.ts";
|
||||
export * from "./runners.ts";
|
||||
export * from "./worktree.ts";
|
||||
export * from "./budgets.ts";
|
||||
|
||||
@ -35,6 +35,8 @@ export function writeRunSettings(sessionId: number, generation: number): string
|
||||
// PEP-33: steps of the agent; async — Claude doesn't wait for the hook process.
|
||||
const step = { ...hook("tool-use", 15), async: true };
|
||||
const settings = {
|
||||
// PEP-5: Claude reports cost, context and the 5h/7d limit windows to the status line command.
|
||||
statusLine: { type: "command", command: `${hookBin()} statusline`, padding: 0 },
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [hook("session-start")] }],
|
||||
UserPromptSubmit: [{ hooks: [hook("prompt")] }],
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { actorColumns } from "@peppa/core";
|
||||
// PEP-10/27/53: a runner (tmux session with an agent) as a long-lived thing — a queue of
|
||||
// stories, fresh context or one conversation between them, its own worktree, free runners.
|
||||
import { existsSync } from "node:fs";
|
||||
@ -140,7 +141,7 @@ export async function advanceRunner(db: Db, sessionId: number, log: (m: string)
|
||||
if (!sw.ok) {
|
||||
const told = await db.select().from(events).where(and(eq(events.sessionId, s.id), eq(events.type, "switch_blocked"), eq(events.taskId, ref.task.id)));
|
||||
if (!told.length) {
|
||||
await db.insert(events).values({ projectId: s.projectId, taskId: ref.task.id, sessionId: s.id, type: "switch_blocked", payload: { reason: sw.reason } });
|
||||
await db.insert(events).values({ projectId: s.projectId, taskId: ref.task.id, sessionId: s.id, type: "switch_blocked", payload: { reason: sw.reason }, ...actorColumns(s.id) });
|
||||
await raiseSessionQuestion(db, s, "attention", `Раннер #${s.id} не может перейти к ${ref.key}: ${sw.reason}. Закоммить или убери изменения — раннер возьмёт стори сам.`);
|
||||
}
|
||||
log(`#${s.id}: switch to ${ref.key} blocked — ${sw.reason}`);
|
||||
|
||||
@ -4,6 +4,7 @@ import {
|
||||
agentAutonomyNote,
|
||||
answerQuestion,
|
||||
getAutonomy,
|
||||
getBudgetState,
|
||||
getSubscription,
|
||||
pickSubscription,
|
||||
createSession,
|
||||
@ -51,6 +52,12 @@ export interface StartOptions {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/** PEP-43: a story paused by its budget is not started or resumed until the PM decides. */
|
||||
export async function assertBudgetOpen(db: Db, taskId: number | null | undefined): Promise<void> {
|
||||
if (taskId == null) return;
|
||||
if (await getBudgetState(db, taskId)) throw new PeppaError("Бюджет стори исчерпан — ответьте на вопрос о бюджете или поменяйте бюджет в карточке стори");
|
||||
}
|
||||
|
||||
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
/** Starts an interactive agent session (Claude Code or Codex) for a task in a detached tmux session. */
|
||||
@ -79,6 +86,8 @@ export async function startRunner(
|
||||
task: { id: number; key: string } | null,
|
||||
opts: StartOptions & { prompt: string },
|
||||
): Promise<SessionView> {
|
||||
// PEP-43: a story paused by its budget waits for the PM.
|
||||
await assertBudgetOpen(db, task?.id);
|
||||
const dir = project.workspacePath;
|
||||
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
|
||||
const rs = await resolveRunnerSettings(db, project.id, task?.id);
|
||||
@ -124,6 +133,7 @@ export async function runnerCwd(db: Db, s: SessionView): Promise<string> {
|
||||
*/
|
||||
export async function resumeSession(db: Db, sessionId: number, opts: StartOptions = {}): Promise<SessionView> {
|
||||
const s = await getSession(db, sessionId);
|
||||
await assertBudgetOpen(db, s.taskId);
|
||||
if (await tmux.hasSession(s.tmuxName)) {
|
||||
if (!(await tmux.paneState(s.tmuxName)).dead) throw new PeppaError(`Session #${s.id} is still running`);
|
||||
await tmux.killSession(s.tmuxName);
|
||||
|
||||
@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
|
||||
import {
|
||||
backupDb,
|
||||
digestTick,
|
||||
getBudgetState,
|
||||
runAsActor,
|
||||
expireSessionQuestions,
|
||||
listSessions,
|
||||
logSessionEvent,
|
||||
@ -24,6 +26,7 @@ import { incidentTick } from "./incidents.ts";
|
||||
import { pollChecks } from "./ci-feedback.ts";
|
||||
import { reviewTick } from "./reviewer.ts";
|
||||
import { autonomyTick } from "./autonomy.ts";
|
||||
import { budgetTick } from "./budgets.ts";
|
||||
|
||||
export interface WatchdogOptions {
|
||||
/** Current time (tests move it instead of waiting). */
|
||||
@ -48,6 +51,11 @@ const limitAlerted = new Set<string>();
|
||||
const thresholdSeen = new Set<string>();
|
||||
|
||||
export async function tick(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
// PEP-48: what the watchdog does is Peppa's own doing.
|
||||
return runAsActor({ kind: "system", channel: "watchdog" }, () => tickInner(db, opts));
|
||||
}
|
||||
|
||||
async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
const log = opts.log ?? (() => {});
|
||||
for (const s of await listSessions(db, { active: true })) {
|
||||
try {
|
||||
@ -58,6 +66,8 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
}
|
||||
// Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup.
|
||||
await runnerTick(db, { log }).catch((e) => log(`runners: ${(e as Error).message}`));
|
||||
// Story budgets (PEP-43): over the limit → pause and ask the PM.
|
||||
await budgetTick(db, { now: opts.now, log }).catch((e) => log(`budgets: ${(e as Error).message}`));
|
||||
// Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher.
|
||||
await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`));
|
||||
// Errors of running products (PEP-58): Bugsink poll + incident policies.
|
||||
@ -72,6 +82,8 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
|
||||
// Rate-limited runner: move it to a free subscription of its pool (PEP-39), else continue
|
||||
// it once its limit has reset (PEP-56), whether or not the agent process is still alive.
|
||||
if (s.status === "rate_limited" && s.resumeAt) {
|
||||
// PEP-43: a story paused by its budget waits for the PM, not for the limit reset.
|
||||
if (s.taskId && (await getBudgetState(db, s.taskId))) return;
|
||||
if (await rotateLimited(db, s, nowDate, log)) return;
|
||||
if (nowDate.getTime() >= s.resumeAt.getTime()) await resumeAfterLimit(db, s, nowDate, log);
|
||||
return;
|
||||
|
||||
@ -79,6 +79,8 @@ if (provider === "opencode" && process.env.OPENCODE_CONFIG && existsSync(process
|
||||
}
|
||||
const conversationId = args.resume ?? randomUUID();
|
||||
let lastMessage = "";
|
||||
// Claude keeps one transcript per conversation; resume appends to it.
|
||||
const transcriptPath = join(cwd, ".peppa", `mock-transcript-${conversationId}.jsonl`);
|
||||
|
||||
// ── hooks / notify ───────────────────────────────────────────────────────────────
|
||||
interface HookCmd {
|
||||
@ -99,7 +101,7 @@ function hookFor(event: string, matchQuery?: string): HookCmd | null {
|
||||
function fireHook(event: string, payload: Record<string, unknown>, matchQuery?: string): Promise<any> {
|
||||
const h = hookFor(event, matchQuery);
|
||||
if (!h) return Promise.resolve(null);
|
||||
const input = { session_id: conversationId, cwd, hook_event_name: event, ...payload };
|
||||
const input = { session_id: conversationId, transcript_path: transcriptPath, cwd, hook_event_name: event, ...payload };
|
||||
return new Promise((resolve) => {
|
||||
const p = spawn("sh", ["-c", h.command], { stdio: ["pipe", "pipe", "inherit"] });
|
||||
let stdout = "";
|
||||
@ -118,6 +120,24 @@ function fireHook(event: string, payload: Record<string, unknown>, matchQuery?:
|
||||
});
|
||||
}
|
||||
|
||||
/** Claude's statusLine: the command from settings, JSON on stdin, the first stdout line shown. */
|
||||
function fireStatusLine(payload: Record<string, unknown>): Promise<string | null> {
|
||||
if (!args.settings) return Promise.resolve(null);
|
||||
const cmd = JSON.parse(readFileSync(args.settings, "utf8")).statusLine?.command as string | undefined;
|
||||
if (!cmd) return Promise.resolve(null);
|
||||
return new Promise((resolve) => {
|
||||
const p = spawn("sh", ["-c", cmd], { stdio: ["pipe", "pipe", "inherit"] });
|
||||
let stdout = "";
|
||||
p.stdout.on("data", (d) => (stdout += d));
|
||||
p.on("close", () => {
|
||||
const line = stdout.split("\n")[0] ?? "";
|
||||
log("statusline", { line });
|
||||
resolve(line);
|
||||
});
|
||||
p.stdin.end(JSON.stringify({ hook_event_name: "Status", session_id: conversationId, transcript_path: transcriptPath, cwd, ...payload }));
|
||||
});
|
||||
}
|
||||
|
||||
function codexNotify(message: string): Promise<void> {
|
||||
if (!args.notify?.length) return Promise.resolve();
|
||||
const payload = { type: "agent-turn-complete", "thread-id": conversationId, "turn-id": randomUUID(), cwd, "last-assistant-message": message };
|
||||
@ -234,6 +254,25 @@ async function run(action: Action): Promise<boolean> {
|
||||
await sleep(100);
|
||||
}
|
||||
out("\n");
|
||||
} else if ("usage" in action) {
|
||||
const u = action.usage;
|
||||
const model = u.model ?? "claude-sonnet-4-5";
|
||||
appendFileSync(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({ type: "assistant", sessionId: conversationId, message: { id: `msg_${randomUUID()}`, model, role: "assistant", content: [{ type: "text", text: "…" }], usage: { input_tokens: u.input ?? 0, output_tokens: u.output ?? 0, cache_read_input_tokens: u.cacheRead ?? 0, cache_creation_input_tokens: u.cacheWrite ?? 0 } } })}\n`,
|
||||
);
|
||||
if (provider === "claude") {
|
||||
const resets = Math.floor(Date.now() / 1000) + (u.resetInSec ?? 3600);
|
||||
const rate_limits: Record<string, unknown> = {};
|
||||
if (u.fiveHour != null) rate_limits.five_hour = { used_percentage: u.fiveHour, resets_at: resets };
|
||||
if (u.sevenDay != null) rate_limits.seven_day = { used_percentage: u.sevenDay, resets_at: resets + 6 * 86400 };
|
||||
await fireStatusLine({
|
||||
model: { id: model, display_name: model },
|
||||
...(u.costUsd != null ? { cost: { total_cost_usd: u.costUsd, total_duration_ms: 1000 } } : {}),
|
||||
...(u.context ? { context_window: { context_window_size: u.context.size, current_usage: { input_tokens: u.context.used, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 } } } : {}),
|
||||
...(Object.keys(rate_limits).length ? { rate_limits } : {}),
|
||||
});
|
||||
}
|
||||
} else if ("sleep" in action) {
|
||||
await sleep(action.sleep);
|
||||
} else if ("mcp" in action) {
|
||||
|
||||
@ -12,6 +12,9 @@ export type Action =
|
||||
// usage limit: StopFailure (claude) / banner only (codex); resetInSec → "resets at HH:MM";
|
||||
// credential → only when the run's login (Claude token, Codex auth.json, OpenCode key) contains it
|
||||
| { limit: true | { resetInSec?: number; reset?: "unknown"; credential?: string } }
|
||||
// PEP-5: an assistant message with this token usage in the transcript, then (claude) the
|
||||
// statusLine command with cost / context / limit windows (pct, reset in N seconds)
|
||||
| { usage: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; model?: string; costUsd?: number; context?: { used: number; size: number }; fiveHour?: number; sevenDay?: number; resetInSec?: number } }
|
||||
| { warn: number } // usage warning banner: "You've used N% of your weekly limit"
|
||||
| { hang: true } // freeze: no output, no input handling
|
||||
| { crash: number } // exit with this code
|
||||
|
||||
108
packages/testkit/test/budgets.test.ts
Normal file
108
packages/testkit/test/budgets.test.ts
Normal file
@ -0,0 +1,108 @@
|
||||
// PEP-43: story budgets — spend, pause over the limit, the PM's decision.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
|
||||
const tmuxAlive = (name: string) => {
|
||||
try {
|
||||
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "has-session", "-t", `=${name}`], { stdio: "ignore" });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const budgetQuestion = (taskId: number) =>
|
||||
waitFor("budget question", async () => (await core.pendingQuestions(db)).find((q) => q.taskId === taskId && q.text.includes("исчерпан бюджет")));
|
||||
|
||||
/** A runner that spent 1 500 tokens in its first turn and is now idle. */
|
||||
async function spentRunner() {
|
||||
const p = await project({ turns: [[{ usage: { input: 1000, output: 500 } }, { say: "Сделал часть." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await waitFor("usage recorded", async () => core.usageTotals((await core.getSession(db, sid)).usage).total === 1500);
|
||||
return { p, sid, task: await p.task() };
|
||||
}
|
||||
|
||||
describe("Бюджет стори", () => {
|
||||
test("Бюджет по умолчанию", async () => {
|
||||
const p = await project({ turns: [] });
|
||||
const task = await p.task();
|
||||
await core.setProjectBudget(db, task.projectId, { tokens: 100_000 });
|
||||
const v = await core.taskBudgetView(db, task);
|
||||
assert.equal(v.source, "project");
|
||||
assert.equal(v.budget.tokens, 100_000);
|
||||
assert.match(core.describeBudget(v), /токены 0 из 100\s000/);
|
||||
// The story's own budget replaces the project's; {} = explicitly unlimited.
|
||||
await core.setTaskBudget(db, task.id, {});
|
||||
assert.equal((await core.effectiveBudget(db, task)).source, "task");
|
||||
assert.equal(core.hasLimits((await core.effectiveBudget(db, task)).budget), false);
|
||||
});
|
||||
|
||||
test("Без бюджета", async () => {
|
||||
const { p, sid } = await spentRunner();
|
||||
assert.equal(await runner.budgetTick(db), 0);
|
||||
assert.equal((await core.pendingQuestions(db)).some((q) => q.text.includes("исчерпан бюджет")), false);
|
||||
await runner.stopSession(db, sid);
|
||||
void p;
|
||||
});
|
||||
|
||||
test("Расход на карточке", () => {
|
||||
const t0 = new Date("2026-11-14T10:00:00");
|
||||
const min = (m: number) => new Date(t0.getTime() + m * 60_000);
|
||||
const s = core.spendOf([
|
||||
{ startedAt: t0, endedAt: min(10), generation: 1, usage: { convs: { a: { input: 1000, output: 500, cacheRead: 0, cacheWrite: 0 } } } },
|
||||
{ startedAt: min(20), endedAt: min(30), generation: 1, usage: { convs: { b: { input: 1000, output: 500, cacheRead: 0, cacheWrite: 0 } } } },
|
||||
]);
|
||||
assert.equal(s.minutes, 20);
|
||||
assert.equal(s.tokens, 3000);
|
||||
assert.equal(s.restarts, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Превышение бюджета ставит стори на паузу и спрашивает PM", () => {
|
||||
test("Превышение токенов → PM продлил бюджет", async () => {
|
||||
const { p, sid, task } = await spentRunner();
|
||||
await core.setTaskBudget(db, task.id, { tokens: 1000 });
|
||||
assert.equal(await runner.budgetTick(db), 1);
|
||||
const q = await budgetQuestion(task.id);
|
||||
assert.deepEqual(q.options, [runner.BUDGET_EXTEND, runner.BUDGET_UNLIMIT, runner.BUDGET_STOP]);
|
||||
const s = await core.getSession(db, sid);
|
||||
assert.ok(tmuxAlive(s.tmuxName), "the runner process is not killed");
|
||||
await assert.rejects(runner.startSession(db, p.taskKey), /Бюджет стори исчерпан/);
|
||||
assert.equal(await runner.budgetTick(db), 0, "asked once");
|
||||
const ev = (await core.listJournal(db, { taskId: task.id })).find((e) => e.type === "budget_paused");
|
||||
assert.ok(ev, "budget_paused event on the story");
|
||||
|
||||
// PM продлил бюджет
|
||||
await runner.answerAndDeliver(db, q.id, runner.BUDGET_EXTEND, "web");
|
||||
assert.equal((await core.getTaskBudget(db, task.id))?.tokens, 2250);
|
||||
assert.equal(await core.getBudgetState(db, task.id), null);
|
||||
await p.waitLog("continued", (e) => e.ev === "prompt" && String(e.prompt).includes("Бюджет") && String(e.prompt).includes("продлён"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("PM остановил", async () => {
|
||||
const { sid, task } = await spentRunner();
|
||||
await core.setTaskBudget(db, task.id, { tokens: 1000 });
|
||||
await runner.budgetTick(db);
|
||||
const q = await budgetQuestion(task.id);
|
||||
await runner.answerAndDeliver(db, q.id, runner.BUDGET_STOP, "telegram");
|
||||
assert.equal((await core.getSession(db, sid)).status, "done");
|
||||
});
|
||||
|
||||
test("Новый бюджет в карточке снимает паузу", async () => {
|
||||
const { p, sid, task } = await spentRunner();
|
||||
await core.setTaskBudget(db, task.id, { tokens: 1000 });
|
||||
await runner.budgetTick(db);
|
||||
const q = await budgetQuestion(task.id);
|
||||
await core.setTaskBudget(db, task.id, { tokens: 10_000 });
|
||||
await runner.budgetChanged(db, task.id);
|
||||
assert.equal(await core.getBudgetState(db, task.id), null);
|
||||
assert.equal((await core.getQuestion(db, q.id)).answeredVia, "system");
|
||||
await p.waitLog("continued", (e) => e.ev === "prompt" && String(e.prompt).includes("изменён"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
96
packages/testkit/test/journal.test.ts
Normal file
96
packages/testkit/test/journal.test.ts
Normal file
@ -0,0 +1,96 @@
|
||||
// PEP-48: every event records who did it; the journal lists them with filters.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { oauthClients } from "@peppa/db";
|
||||
import { core, db, runner, teardown } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
|
||||
let seq = 0;
|
||||
async function newTask() {
|
||||
const key = `J${String.fromCharCode(65 + seq++)}`;
|
||||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: `/tmp/${key}` });
|
||||
return core.createTask(db, { projectId: p.id, title: `story ${key}` });
|
||||
}
|
||||
const user = (login: string) => core.createLocalUser(db, { login, password: "correct-horse-battery" });
|
||||
const last = async (taskId: number, type: string) => (await core.listJournal(db, { taskId })).find((e) => e.type === type)!;
|
||||
|
||||
describe("Автор каждого события", () => {
|
||||
test("Карточку подвинул участник через веб", async () => {
|
||||
const anna = await user("anna");
|
||||
const ref = await newTask();
|
||||
await core.updateTask(db, ref, { status: "in_progress" });
|
||||
const fresh = await core.resolveTask(db, ref.key);
|
||||
await core.runAsActor({ kind: "user", userId: anna.id, channel: "web" }, () => runner.moveTask(db, fresh, "backlog"));
|
||||
const e = await last(ref.task.id, "task_updated");
|
||||
assert.deepEqual([e.actorKind, e.actorLogin, e.actorChannel], ["user", "anna", "web"]);
|
||||
assert.equal(core.actorLabel(e), "anna · веб");
|
||||
});
|
||||
|
||||
test("Ответ через удалённый MCP", async () => {
|
||||
const pm = await user("pm");
|
||||
await db.insert(oauthClients).values({ id: "client-chatgpt", name: "ChatGPT", redirectUris: ["https://chat.example/cb"] });
|
||||
const ref = await newTask();
|
||||
const q = await core.askPm(db, ref, { kind: "question", text: "Postgres или SQLite?" });
|
||||
await core.runAsActor({ kind: "user", userId: pm.id, channel: "mcp", clientId: "client-chatgpt" }, () => runner.answerAndDeliver(db, q.id, "SQLite", "web"));
|
||||
const e = await last(ref.task.id, "question_answered");
|
||||
assert.equal(core.actorLabel(e), "pm · MCP (ChatGPT)");
|
||||
assert.equal((e.payload as { answer: string }).answer, "SQLite");
|
||||
});
|
||||
|
||||
test("Ответ в терминале и закрытие самой Пеппой", async () => {
|
||||
const ref = await newTask();
|
||||
const q1 = await core.askPm(db, ref, { kind: "question", text: "a" });
|
||||
const q2 = await core.askPm(db, ref, { kind: "question", text: "b" });
|
||||
await core.answerQuestion(db, q1.id, "ok", "terminal");
|
||||
await core.answerQuestion(db, q2.id, "(неактуально)", "system");
|
||||
const answers = (await core.listJournal(db, { taskId: ref.task.id })).filter((e) => e.type === "question_answered");
|
||||
assert.equal(answers.length, 1, "system closings are not actions");
|
||||
assert.equal(core.actorLabel(answers[0]!), "человек · терминал");
|
||||
});
|
||||
|
||||
test("Действие агента", async () => {
|
||||
const ref = await newTask();
|
||||
const s = await core.createSession(db, { projectId: ref.project.id, taskId: ref.task.id });
|
||||
await core.reportProgress(db, ref, "сделал 1.1", s.id);
|
||||
const e = await last(ref.task.id, "progress");
|
||||
assert.equal(e.actorKind, "agent");
|
||||
assert.equal(core.actorLabel(e), `агент · раннер #${s.id}`);
|
||||
});
|
||||
|
||||
test("Без контекста и без сессии — Пеппа", async () => {
|
||||
const ref = await newTask();
|
||||
await core.updateTask(db, ref, { title: "renamed" });
|
||||
assert.equal(core.actorLabel(await last(ref.task.id, "task_updated")), "Пеппа");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Журнал действий", () => {
|
||||
test("Фильтр по проекту", async () => {
|
||||
const a = await newTask();
|
||||
const b = await newTask();
|
||||
await core.reportProgress(db, a, "A");
|
||||
await core.reportProgress(db, b, "B");
|
||||
const onlyB = await core.listJournal(db, { projectId: b.project.id });
|
||||
assert.ok(onlyB.length > 0);
|
||||
assert.ok(onlyB.every((e) => e.projectKey === b.project.key));
|
||||
assert.deepEqual(await core.listJournal(db, { projectIds: [] }), []);
|
||||
});
|
||||
|
||||
test("Фильтр по автору и каналу", async () => {
|
||||
const ref = await newTask();
|
||||
const u = await user("ops");
|
||||
await core.runAsActor({ kind: "user", userId: u.id, channel: "telegram" }, () => core.reportProgress(db, ref, "из телеграма"));
|
||||
await core.reportProgress(db, ref, "сам");
|
||||
const tg = await core.listJournal(db, { projectId: ref.project.id, channel: "telegram" });
|
||||
assert.deepEqual(tg.map((e) => (e.payload as { text: string }).text), ["из телеграма"]);
|
||||
const sys = await core.listJournal(db, { projectId: ref.project.id, actorKind: "system" });
|
||||
assert.ok(sys.some((e) => (e.payload as { text?: string }).text === "сам"));
|
||||
});
|
||||
|
||||
test("Не суперадмин", async () => {
|
||||
const u = await user("guest");
|
||||
await core.setPlatformAdmins(db, ["root"]);
|
||||
assert.equal(await core.isSuperadmin(db, u), false);
|
||||
});
|
||||
});
|
||||
98
packages/testkit/test/metrics.test.ts
Normal file
98
packages/testkit/test/metrics.test.ts
Normal file
@ -0,0 +1,98 @@
|
||||
// PEP-47: factory metrics from status history, questions, sessions and reviews.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { events, sessions, codeReviews } from "@peppa/db";
|
||||
import { core, db, teardown } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
|
||||
let seq = 0;
|
||||
async function newProject() {
|
||||
const key = `M${String.fromCharCode(65 + seq++)}`;
|
||||
return core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: `/tmp/${key}` });
|
||||
}
|
||||
const at = (s: string) => new Date(s);
|
||||
async function move(projectId: number, taskId: number, from: string, to: string, when: string) {
|
||||
await db.insert(events).values({ projectId, taskId, type: "task_updated", payload: { from: { status: from }, to: { status: to } }, createdAt: at(when) });
|
||||
}
|
||||
async function runner(projectId: number, taskId: number | null, provider: "claude" | "codex", start: string, hours: number) {
|
||||
await db.insert(sessions).values({ projectId, taskId, provider, tmuxName: `m-${Math.random()}`, status: "done", generation: 1, startedAt: at(start), endedAt: new Date(at(start).getTime() + hours * 3_600_000) });
|
||||
}
|
||||
|
||||
// Monday 2026-11-09 … Sunday 2026-11-15; "now" = Saturday 2026-11-14.
|
||||
const now = at("2026-11-14T12:00:00");
|
||||
|
||||
describe("Метрики проекта", () => {
|
||||
test("Время цикла и первый проход", async () => {
|
||||
const p = await newProject();
|
||||
const t1 = (await core.createTask(db, { projectId: p.id, title: "PEP-1" })).task;
|
||||
const t2 = (await core.createTask(db, { projectId: p.id, title: "PEP-2" })).task;
|
||||
await move(p.id, t1.id, "backlog", "in_progress", "2026-11-09T10:00:00");
|
||||
await move(p.id, t1.id, "in_progress", "review", "2026-11-09T18:00:00");
|
||||
await move(p.id, t1.id, "review", "done", "2026-11-10T10:00:00");
|
||||
await move(p.id, t2.id, "backlog", "in_progress", "2026-11-09T10:00:00");
|
||||
await move(p.id, t2.id, "in_progress", "review", "2026-11-10T10:00:00");
|
||||
await move(p.id, t2.id, "review", "in_progress", "2026-11-10T12:00:00");
|
||||
await move(p.id, t2.id, "in_progress", "review", "2026-11-11T10:00:00");
|
||||
await move(p.id, t2.id, "review", "done", "2026-11-12T10:00:00");
|
||||
const m = await core.projectMetrics(db, p.id, { weeks: 4, now });
|
||||
assert.equal(m.summary.done, 2);
|
||||
assert.equal(m.summary.firstPassRate, 0.5);
|
||||
assert.equal(m.summary.reviewReturnRate, 0.5);
|
||||
assert.equal(m.summary.cycleHoursMedian, (24 + 72) / 2, "PEP-1: 24 h, PEP-2: 72 h");
|
||||
assert.equal(m.weekly.length, 4);
|
||||
assert.equal(m.weekly.at(-1)!.done, 2, "both in this week");
|
||||
assert.equal(m.weekly[0]!.done, 0);
|
||||
});
|
||||
|
||||
test("Замечания ревьюера — не первый проход", async () => {
|
||||
const p = await newProject();
|
||||
const t = (await core.createTask(db, { projectId: p.id, title: "x" })).task;
|
||||
await move(p.id, t.id, "backlog", "in_progress", "2026-11-09T10:00:00");
|
||||
await move(p.id, t.id, "in_progress", "done", "2026-11-09T12:00:00");
|
||||
await db.insert(codeReviews).values({ projectId: p.id, taskId: t.id, prNumber: 1, sha: "abc", state: "done", verdict: "changes" });
|
||||
assert.equal((await core.projectMetrics(db, p.id, { weeks: 1, now })).summary.firstPassRate, 0);
|
||||
});
|
||||
|
||||
test("Пустой проект", async () => {
|
||||
const p = await newProject();
|
||||
const m = await core.projectMetrics(db, p.id, { now });
|
||||
assert.equal(m.summary.done, 0);
|
||||
assert.equal(m.summary.cycleHoursMedian, null);
|
||||
assert.equal(core.fmtPct(m.summary.firstPassRate), "—");
|
||||
assert.equal(core.fmtHours(m.summary.cycleHoursMedian), "—");
|
||||
});
|
||||
|
||||
test("Вопросы на стори и ожидание PM", async () => {
|
||||
const p = await newProject();
|
||||
const t = (await core.createTask(db, { projectId: p.id, title: "q" })).task;
|
||||
await runner(p.id, t.id, "claude", "2026-11-13T09:00:00", 1);
|
||||
const [s] = await db.select().from(sessions).where((await import("drizzle-orm")).eq(sessions.taskId, t.id));
|
||||
const { questions } = await import("@peppa/db");
|
||||
await db.insert(questions).values([
|
||||
{ projectId: p.id, taskId: t.id, sessionId: s!.id, kind: "question", text: "?", answer: "да", answeredVia: "web", createdAt: at("2026-11-13T09:10:00"), answeredAt: at("2026-11-13T09:40:00") },
|
||||
{ projectId: p.id, taskId: t.id, sessionId: s!.id, kind: "attention", text: "ждёт", createdAt: at("2026-11-13T09:50:00") },
|
||||
]);
|
||||
const m = await core.projectMetrics(db, p.id, { weeks: 1, now });
|
||||
assert.equal(m.summary.questions, 1, "notices are not questions");
|
||||
assert.equal(m.summary.questionsPerStory, 1);
|
||||
assert.equal(m.summary.pmWaitHours, 0.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Тренд по неделям, агентам и эпикам", () => {
|
||||
test("Разбивка по агентам", async () => {
|
||||
const p = await newProject();
|
||||
const epic = await core.createGoal(db, p.id, "Платежи");
|
||||
const t = (await core.createTask(db, { projectId: p.id, title: "a", goalId: epic.id })).task;
|
||||
await runner(p.id, t.id, "claude", "2026-11-12T10:00:00", 2);
|
||||
await runner(p.id, t.id, "codex", "2026-11-13T10:00:00", 1);
|
||||
const m = await core.projectMetrics(db, p.id, { weeks: 2, now });
|
||||
const by = Object.fromEntries(m.byProvider.map((x) => [x.provider, x.hours]));
|
||||
assert.deepEqual(by, { claude: 2, codex: 1 });
|
||||
assert.equal(m.summary.runnerHours, 3);
|
||||
const e = m.byEpic.find((x) => x.goalId === epic.id)!;
|
||||
assert.equal(e.title, "Платежи");
|
||||
assert.equal(e.spend.minutes, 180);
|
||||
});
|
||||
});
|
||||
@ -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", "apply_plan", "archive_task", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]);
|
||||
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "apply_plan", "archive_task", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_metrics", "get_project_settings", "get_task", "get_usage", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]);
|
||||
assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true);
|
||||
assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false);
|
||||
|
||||
|
||||
95
packages/testkit/test/usage.test.ts
Normal file
95
packages/testkit/test/usage.test.ts
Normal file
@ -0,0 +1,95 @@
|
||||
// PEP-5: usage of sessions (statusLine + transcript) and subscription limit windows.
|
||||
import assert from "node:assert/strict";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, project, teardown } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
|
||||
describe("Разбор данных Claude", () => {
|
||||
test("statusLine: стоимость, контекст, окна (секунды и ISO, доля 0..1)", () => {
|
||||
const d = core.parseStatusLine({
|
||||
cost: { total_cost_usd: 0.42 },
|
||||
context_window: { context_window_size: 200000, current_usage: { input_tokens: 40000, cache_read_input_tokens: 10000 } },
|
||||
rate_limits: { five_hour: { used_percentage: 42, resets_at: 1_900_000_000 }, seven_day: { utilization: 0.18, resets_at: "2030-01-01T00:00:00Z" } },
|
||||
model: { id: "claude-opus-4-6" },
|
||||
});
|
||||
assert.equal(d.costUsd, 0.42);
|
||||
assert.deepEqual(d.context, { used: 50000, size: 200000, pct: 25 });
|
||||
assert.deepEqual(d.windows.fiveHour, { pct: 42, resetsAt: 1_900_000_000_000 });
|
||||
assert.equal(d.windows.sevenDay?.pct, 18);
|
||||
assert.equal(d.windows.sevenDay?.resetsAt, Date.parse("2030-01-01T00:00:00Z"));
|
||||
assert.equal(d.model, "claude-opus-4-6");
|
||||
});
|
||||
|
||||
test("transcript: сумма по ответам без потоковых дублей", () => {
|
||||
const path = join(process.env.PEPPA_HOME!, "t.jsonl");
|
||||
const line = (id: string, input: number, output: number) => JSON.stringify({ type: "assistant", message: { id, model: "claude-sonnet-4-5", usage: { input_tokens: input, output_tokens: output, cache_read_input_tokens: 10 } } });
|
||||
writeFileSync(path, [line("a", 100, 5), line("a", 100, 20), line("b", 50, 30), JSON.stringify({ type: "user", message: { content: "hi" } })].join("\n"));
|
||||
const u = core.transcriptUsage(path)!;
|
||||
assert.deepEqual(u.tokens, { input: 150, output: 50, cacheRead: 20, cacheWrite: 0 });
|
||||
assert.equal(u.model, "claude-sonnet-4-5");
|
||||
assert.equal(core.transcriptUsage(join(process.env.PEPPA_HOME!, "missing.jsonl")), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Окна лимитов аккаунта", () => {
|
||||
test("Данных нет — «нет данных»", async () => {
|
||||
const accounts = await core.listAccountUsage(db);
|
||||
assert.equal(accounts.length, 1);
|
||||
assert.equal(accounts[0]!.fiveHour, null);
|
||||
assert.match(core.describeAccount(accounts[0]!), /нет данных/);
|
||||
});
|
||||
|
||||
test("Сброс прошёл — «сброшено», без процента", () => {
|
||||
const now = Date.parse("2026-11-14T14:31:00");
|
||||
const v = core.windowView({ pct: 90, resetsAt: Date.parse("2026-11-14T14:30:00") }, now)!;
|
||||
assert.equal(v.reset, true);
|
||||
assert.equal(v.pct, null);
|
||||
assert.equal(core.windowView({ pct: 90, resetsAt: now + 60_000 }, now)!.pct, 90);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Расход сессии из statusLine и transcript", () => {
|
||||
test("Сессия сообщила расход", async () => {
|
||||
const p = await project({ turns: [[{ usage: { input: 1200, output: 300, costUsd: 0.42, context: { used: 50000, size: 200000 }, fiveHour: 42, sevenDay: 18 } }, { say: "Готово." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("statusline", (e) => e.ev === "statusline");
|
||||
await p.waitQuestion(sid, "attention");
|
||||
const s = await core.getSession(db, sid);
|
||||
const t = core.usageTotals(s.usage);
|
||||
assert.equal(t.total, 1500);
|
||||
assert.equal(t.costUsd, 0.42);
|
||||
assert.equal(t.estimated, false);
|
||||
assert.equal(t.context?.pct, 25);
|
||||
// The status line shown in Claude names the story and the windows.
|
||||
const line = String(p.log().find((e) => e.ev === "statusline")!.line);
|
||||
assert.match(line, new RegExp(`Пеппа ${p.taskKey}.*5ч 42%.*7д 18%`));
|
||||
// Окна обновились — on this machine's login (no subscription).
|
||||
const acc = (await core.listAccountUsage(db)).find((a) => a.subscriptionId === null)!;
|
||||
assert.equal(acc.fiveHour?.pct, 42);
|
||||
assert.equal(acc.sevenDay?.pct, 18);
|
||||
assert.ok(acc.fiveHour?.resetsAt && acc.fiveHour.resetsAt.getTime() > Date.now());
|
||||
assert.match(core.describeAccount(acc), /5 ч 42% \(сброс \d\d:\d\d\) · 7 д 18%/);
|
||||
});
|
||||
|
||||
test("Стоимость неизвестна — оценка по прайсу с «≈»", async () => {
|
||||
const p = await project({ turns: [] });
|
||||
const s = await core.createSession(db, { projectId: (await p.task()).projectId, taskId: (await p.task()).id });
|
||||
core.recordTranscriptUsage(db, s.id, "conv-1", { tokens: { input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 0 }, model: "claude-sonnet-4-5" });
|
||||
const t = core.usageTotals((await core.getSession(db, s.id)).usage);
|
||||
assert.equal(t.estimated, true);
|
||||
assert.equal(t.costUsd!.toFixed(2), "3.00");
|
||||
assert.equal(core.fmtCost(t), "≈ $3.00");
|
||||
// A resumed conversation replaces its own total, another conversation adds up.
|
||||
core.recordTranscriptUsage(db, s.id, "conv-1", { tokens: { input: 1_000_000, output: 100, cacheRead: 0, cacheWrite: 0 } });
|
||||
core.recordTranscriptUsage(db, s.id, "conv-2", { tokens: { input: 10, output: 0, cacheRead: 0, cacheWrite: 0 } });
|
||||
assert.equal(core.usageTotals((await core.getSession(db, s.id)).usage).total, 1_000_110);
|
||||
});
|
||||
|
||||
test("Codex расход не сообщает — «нет данных»", () => {
|
||||
assert.equal(core.describeUsage(null), "нет данных");
|
||||
assert.equal(core.usageTotals({}).hasData, false);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user