peppa/packages/core/src/onboarding.ts
Асель 53ac7efdcc PEP-30/41/31: project memory, agent model per story with escalation, first-run checklist
- PEP-30: .peppa/memory.md in the project repo (core/memory.ts), agent MCP get_memory/remember
  (dedupe, 12k size limit, replace to compact), runner appends memory + last finished stories
  to the launch rules, RULES.md rule, memory on the project «Спеки» tab.
- PEP-41: agent settings platform → project → story (provider, model, effort, escalation model
  after N failures, fallback provider); Claude --effort / Codex model_reasoning_effort;
  sticky escalation relaunches a live runner on the stronger model (sendWithEscalation from
  CI feedback and the reviewer); fallback provider when the main one has no working
  subscription; web panels, MCP PM `agent`, CLI `peppa project agent`.
- PEP-31: first-run checklist on the home page (core/onboarding.ts), hide button,
  «Агенты не запустятся» warning on the project page when its pool has no working subscription.

No migrations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:44:24 +05:00

88 lines
5.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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

// PEP-31: first-run checklist on the home page and the "agents won't start" project warning.
import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
import { isSuperadmin } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { isUsable, poolSubscriptions } from "./subscriptions.ts";
import { userProjectIds, type User } from "./users.ts";
export type OnboardingStepId = "subscription" | "telegram" | "egov" | "project" | "story" | "started";
export interface OnboardingStep {
id: OnboardingStepId;
title: string;
hint: string;
href: string;
done: boolean;
optional: boolean;
}
export interface Onboarding {
steps: OnboardingStep[];
/** Required steps done / total. */
done: number;
total: number;
/** All required steps done. */
complete: boolean;
dismissed: boolean;
/** Shown on the home page. */
visible: boolean;
}
const dismissedKey = (userId: number) => `onboarding.dismissed:${userId}`;
export async function dismissOnboarding(db: Db, userId: number): Promise<void> {
await setSetting(db, dismissedKey(userId), { at: new Date().toISOString() });
}
export async function onboardingChecklist(db: Db, user: Pick<User, "id" | "login">): Promise<Onboarding> {
const [me] = await db.select({ chat: users.telegramChatId, iin: users.egovIin }).from(users).where(eq(users.id, user.id));
const admin = await isSuperadmin(db, user);
const ids = await userProjectIds(db, user.id);
const n = async (q: Promise<Array<{ n: number }>>) => (await q)[0]?.n ?? 0;
const storyCount = ids.length ? await n(db.select({ n: count() }).from(tasks).where(inArray(tasks.projectId, ids))) : 0;
const started = ids.length ? await n(db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), isNotNull(sessions.taskId)))) : 0;
const firstKey = ids.length ? (await db.select({ key: projects.key }).from(projects).where(inArray(projects.id, ids)).limit(1))[0]?.key : undefined;
const steps: OnboardingStep[] = [];
if (admin) {
const subs = await db.select({ status: subscriptions.status, limitedUntil: subscriptions.limitedUntil }).from(subscriptions);
steps.push({
id: "subscription",
title: "Подключить подписку агента",
hint: "Claude, Codex или OpenCode — на ней работают агенты; добавь её в пул проекта.",
href: "/subscriptions",
done: subs.some((s) => s.status === "active" || s.status === "limited"),
optional: false,
});
}
steps.push(
{ id: "telegram", title: "Привязать Telegram", hint: "Вопросы агентов и «готово к ревью» придут в бот, отвечать можно кнопками.", href: "/settings#telegram", done: me?.chat != null, optional: false },
{ id: "egov", title: "Привязать eGov", hint: "Вход по QR из eGov Mobile без пароля.", href: "/settings#egov", done: !!me?.iin, optional: true },
{ id: "project", title: "Создать проект", hint: "Пеппа заведёт репозиторий в Gitea с шаблоном и CI.", href: "/projects/new", done: ids.length > 0, optional: false },
{ id: "story", title: "Завести стори", hint: "Опиши, что нужно сделать, — одна стори = одно изменение.", href: firstKey ? `/p/${firstKey}` : "/projects", done: storyCount > 0, optional: false },
{ id: "started", title: "Двинуть стори в работу", hint: "Перетащи карточку в «В работе» — агент запустится сам.", href: firstKey ? `/p/${firstKey}` : "/projects", done: started > 0, optional: false },
);
const required = steps.filter((s) => !s.optional);
const done = required.filter((s) => s.done).length;
const complete = done === required.length;
const dismissed = !!(await getSetting(db, dismissedKey(user.id)));
return { steps, done, total: required.length, complete, dismissed, visible: !complete && !dismissed };
}
const STATUS_RU: Record<string, string> = { pending: "не подключена", limited: "в лимите", auth_error: "ошибка входа", active: "активна" };
/**
* Why agents of the project won't start, or null: the project's pool has no working
* subscription. Without a pool the runner uses this machine's login (not checked here).
*/
export async function projectAgentWarning(db: Db, projectId: number, now = new Date()): Promise<string | null> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
if (p?.poolId == null) return null;
const subs = await poolSubscriptions(db, p.poolId);
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
if (subs.some((s) => isUsable(s, now))) return null;
const why = subs.map((s) => `«${s.name}» — ${STATUS_RU[s.status] ?? s.status}${s.status === "limited" && s.limitedUntil ? ` до ${s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}` : ""}`);
return `нет рабочей подписки в пуле проекта: ${why.join(", ")}`;
}