peppa/apps/web/scripts/mock-ui-seed.ts
Асель 8dc82859c7 PEP-36 stage 1: run Peppa with Node 26 type stripping instead of tsx
- tsconfig: erasableSyntaxOnly + verbatimModuleSyntax; parameter properties
  rewritten (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError,
  TelegramApi, MockGitea)
- bin wrappers (peppa, peppa-mcp, peppa-hook, peppa-bot, testkit mocks,
  peppa-dev): `node --import scripts/lib/require-node.mjs` (clear error on
  Node < 26, PEPPA_NODE overrides the binary); package scripts and tests on
  `node` / `node --test`; tsx removed
- install-launchd.sh pins PEPPA_NODE (checked absolute path) in the plists
- fix a race the faster hooks exposed: the prompt hook answered every pending
  question, including a PM question raised after Peppa itself pasted text
  into the terminal; sendToSession now logs `input_sent` and the hook only
  answers questions older than that input
- change pep-36-lightweight-stack: stage 1 done, hook start numbers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:51:22 +05:00

132 lines
8.5 KiB
TypeScript
Raw Permalink 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.

// Demo data for checking the web UI by eye (PEP-38): a user, two projects, goals, tasks on every board
// column, runners in every status (one hit the usage limit and resumes later), open questions, releases.
// Only for a throwaway database — refuses the production one:
// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui node apps/web/scripts/mock-ui-seed.ts [login]
import { mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { checkRuns, createDb, errorSources, events, goals, incidents, incidentSettings, projects, questions, releases, sessions, tasks, users } from "@peppa/db";
import { eq } from "drizzle-orm";
const url = process.env.DATABASE_URL ?? "";
if (!url || /\/peppa$/.test(url)) throw new Error("mock-ui-seed: point DATABASE_URL at a throwaway database, not the production one");
const login = process.argv[2] ?? "mock-pm";
const db = createDb(url);
const ago = (min: number) => new Date(Date.now() - min * 60_000);
const ws = join(tmpdir(), "peppa-mock-ui");
// Negative Gitea id = local account: allowed in without the allowlist.
const [user] = await db.insert(users).values({ giteaId: -900001, login }).onConflictDoUpdate({ target: users.login, set: { login } }).returning();
async function project(key: string, name: string, slug: string) {
mkdirSync(join(ws, slug, ".peppa"), { recursive: true });
const checks = { typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" };
writeFileSync(join(ws, slug, ".peppa", "project.json"), JSON.stringify({ key, slug, checks }));
const [p] = await db
.insert(projects)
.values({ key, name, slug, giteaOwner: login, giteaRepo: slug, workspacePath: join(ws, slug), ownerId: user!.id })
.returning();
return p!;
}
const pay = await project("PAY", "Платёжный сервис", "mock-payments");
const shop = await project("SHOP", "Витрина магазина", "mock-shop");
const [g1, g2] = await db
.insert(goals)
.values([
{ projectId: pay.id, title: "Оплата картой", description: "Карты РФ и СБП" },
{ projectId: pay.id, title: "Стабильность", description: "Ошибки из прода" },
])
.returning();
type T = { title: string; status: (typeof tasks.$inferInsert)["status"]; goalId?: number; description?: string; prUrl?: string };
async function addTasks(projectId: number, list: T[]) {
const rows = await db
.insert(tasks)
.values(list.map((t, i) => ({ projectId, number: i + 1, ...t })))
.returning();
await db.update(projects).set({ nextTaskNumber: list.length + 1 }).where(eq(projects.id, projectId));
return rows;
}
const pt = await addTasks(pay.id, [
{ title: "Оплата картой через ЮKassa", status: "in_progress", goalId: g1!.id, description: "Подключить ЮKassa, вебхуки статуса платежа." },
{ title: "Возвраты платежей", status: "awaiting_approval", goalId: g1!.id },
{ title: "Оплата по СБП", status: "in_progress", goalId: g1!.id },
{ title: "Чеки по 54-ФЗ", status: "review", goalId: g1!.id, prUrl: "https://git.telecom.quest/mock/mock-payments/pulls/4" },
{ title: "TypeError в форме оплаты", status: "backlog", goalId: g2!.id },
{ title: "Логи платежей в Bugsink", status: "done", goalId: g2!.id },
{ title: "Рефакторинг конфигурации", status: "proposing" },
]);
const st = await addTasks(shop.id, [
{ title: "Каталог с фильтрами", status: "in_progress" },
{ title: "Корзина и промокоды", status: "blocked" },
{ title: "Поиск по товарам", status: "backlog" },
]);
type S = { task: (typeof pt)[number]; status: (typeof sessions.$inferInsert)["status"]; min: number; provider?: "claude" | "codex"; resumeAt?: Date; gen?: number };
const runners: S[] = [
{ task: pt[1]!, status: "waiting_input", min: 3 },
{ task: pt[0]!, status: "running", min: 1 },
{ task: pt[2]!, status: "rate_limited", min: 42, resumeAt: new Date(Date.now() + 95 * 60_000), gen: 2 },
{ task: pt[3]!, status: "idle", min: 18 },
{ task: st[0]!, status: "running", min: 0, provider: "codex" },
{ task: st[1]!, status: "stalled", min: 27 },
{ task: pt[5]!, status: "done", min: 600 },
{ task: pt[4]!, status: "failed", min: 1500 },
];
const made = [];
for (const [i, r] of runners.entries()) {
const key = r.task.projectId === pay.id ? "pay" : "shop";
const [s] = await db
.insert(sessions)
.values({
projectId: r.task.projectId,
taskId: r.task.id,
tmuxName: `peppa-${key}-${r.task.number}-s${100 + i}`,
provider: r.provider ?? "claude",
status: r.status,
generation: r.gen ?? 1,
lastActivityAt: ago(r.min),
resumeAt: r.resumeAt ?? null,
limitResumes: r.resumeAt ? 1 : 0,
startedAt: ago(r.min + 30),
endedAt: r.status === "done" || r.status === "failed" ? ago(r.min) : null,
})
.returning();
made.push(s!);
}
await db.insert(questions).values([
{ projectId: pay.id, taskId: pt[1]!.id, sessionId: made[0]!.id, kind: "approval", text: "Proposal pep-2-refunds: частичные возвраты через API ЮKassa, новая таблица refunds. Одобрить?" },
{ projectId: pay.id, taskId: pt[0]!.id, sessionId: made[1]!.id, kind: "permission", text: "Bash: pnpm add @yookassa/sdk@3.1.0" },
{ projectId: pay.id, taskId: pt[3]!.id, sessionId: made[3]!.id, kind: "attention", text: "PAY-4 готово к ревью: чеки уходят в АТОЛ, PR #4, проверки зелёные." },
{ projectId: shop.id, taskId: st[1]!.id, kind: "question", text: "Промокоды суммируются со скидкой на товар?", options: ["Да", "Нет, берём большую"] },
]);
await db.insert(events).values([
{ projectId: pay.id, taskId: pt[0]!.id, sessionId: made[1]!.id, type: "progress", payload: { text: "Вебхук статуса платежа готов, пишу тесты" } },
{ projectId: pay.id, taskId: pt[0]!.id, type: "task_updated", payload: { to: { status: "in_progress" } } },
]);
await db.insert(releases).values([
{ projectId: pay.id, env: "staging", sha: "a1b2c3d4e5f6", status: "healthy", host: "mock-payments-staging.telecom.quest", tasks: ["PAY-6"], deployedBy: "ci" },
{ projectId: pay.id, env: "prod", sha: "9f8e7d6c5b4a", status: "healthy", host: "mock-payments-prod.telecom.quest", tasks: ["PAY-5"], deployedBy: login },
]);
// CI of PAY-1 (one red check with a log tail) and PAY-4 (green), PEP-57.
await db.insert(checkRuns).values([
...["typecheck", "build"].map((check) => ({ projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check, state: "success" as const })),
{ projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check: "test", state: "failure" as const, logTail: "FAIL src/webhook.test.ts\n ✕ marks the payment paid (12 ms)\n expected 'paid', got 'pending'" },
...["typecheck", "test", "build"].map((check) => ({ projectId: pay.id, taskId: pt[3]!.id, sha: "beef5678", check, state: "success" as const })),
]);
// Error tracking (PEP-58): settings, DSNs, an open incident, one with a task, one ignored.
await db.insert(incidentSettings).values({ projectId: pay.id, hookSecret: "mock-hook-secret", policy: "ask", webhookAuto: false });
await db.insert(errorSources).values([
{ projectId: pay.id, kind: "web", bugsinkProjectId: 9001, dsn: "https://mock-key@bugsink.example/9001" },
{ projectId: pay.id, kind: "api", bugsinkProjectId: 9002, dsn: "https://mock-key@bugsink.example/9002" },
]);
await db.insert(incidents).values([
{ projectId: pay.id, source: "web", bugsinkIssueId: "mock-1", title: "TypeError: Cannot read properties of undefined (reading 'amount')", culprit: "PaymentForm.tsx in submit", environment: "prod", lastRelease: "9f8e7d6", events: 14, firstSeen: ago(300), lastSeen: ago(6), status: "pending", decidedBy: "triage", decisionReason: "Падает оплата у части пользователей — нужен PM" },
{ projectId: pay.id, source: "api", bugsinkIssueId: "mock-2", title: "TimeoutError: YooKassa did not answer in 10s", environment: "prod", events: 3, firstSeen: ago(900), lastSeen: ago(90), status: "task", taskId: pt[4]!.id },
{ projectId: pay.id, source: "web", bugsinkIssueId: "mock-3", title: "ResizeObserver loop limit exceeded", environment: "prod", events: 120, firstSeen: ago(5000), lastSeen: ago(30), status: "ignored" },
]);
console.log(`seeded: user ${login}, projects PAY and SHOP, ${made.length} runners`);
process.exit(0);