From 6e54fc69a6e9086d510bd024727dc865d5421088 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 12:39:46 +0500 Subject: [PATCH 001/394] =?UTF-8?q?PEP-91:=20Peppa=20reports=20its=20own?= =?UTF-8?q?=20errors=20to=20Bugsink=20=E2=80=94=20backend=20to=20PEP-api,?= =?UTF-8?q?=20browser=20to=20PEP-web?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/bot/src/bot.ts | 2 + apps/bot/src/index.ts | 3 + apps/web/app/api/client-errors/route.ts | 42 ++++ apps/web/app/layout.tsx | 6 +- apps/web/components/ErrorReporter.tsx | 39 ++++ apps/web/instrumentation.ts | 18 +- .../pep-91-platform-errors/proposal.md | 32 +++ .../specs/error-tracking/spec.md | 22 ++ .../changes/pep-91-platform-errors/tasks.md | 15 ++ packages/cli/src/index.ts | 17 +- packages/core/src/error-report.ts | 211 ++++++++++++++++++ packages/core/src/index.ts | 1 + packages/runner/src/incidents.ts | 5 + packages/runner/src/watchdog.ts | 52 +++-- packages/testkit/src/mock-bugsink.ts | 26 +++ packages/testkit/test/platform-errors.test.ts | 108 +++++++++ 17 files changed, 575 insertions(+), 25 deletions(-) create mode 100644 apps/web/app/api/client-errors/route.ts create mode 100644 apps/web/components/ErrorReporter.tsx create mode 100644 openspec/changes/pep-91-platform-errors/proposal.md create mode 100644 openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md create mode 100644 openspec/changes/pep-91-platform-errors/tasks.md create mode 100644 packages/core/src/error-report.ts create mode 100644 packages/testkit/test/platform-errors.test.ts diff --git a/AGENTS.md b/AGENTS.md index 6600b08f..eeb48970 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,6 +46,7 @@ - **Перенос репозитория проекта (PEP-4)**: `peppa project transfer ` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo---`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно - **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` +- **Свои ошибки Пеппы (PEP-91)**: проект `PEP` подключён к Bugsink как любой (`peppa project errors ` = `connectErrorTrackingFromEnv`), бэк → `PEP-api`, фронт → `PEP-web`. Отправитель без SDK — `core/error-report.ts` (`reportPlatformError`: envelope `POST /api//envelope/`, DSN источников проекта `PEPPA_PLATFORM_KEY` из БД (кэш 5 мин) или `PEPPA_ERRORS_DSN_API`/`_WEB`, `release` = `peppaCommit()`, `environment` = `PEPPA_ENVIRONMENT` (live), теги `service`/`where`; не бросает, 3 с, одна ошибка раз в минуту, ≤30/мин, `PEPPA_ERRORS=off`). Кто шлёт: `onRequestError` в `instrumentation.ts`, вачдог (`failed(db, log, часть)` вместо голого `log`), бот (`handleUpdate`), падения процессов (`installCrashReporting`: отправить и `exit 1`); браузер — `components/ErrorReporter.tsx` → `POST /api/client-errors` (без входа, ≤16 КБ, 20/мин на IP). Мок — envelope в `mock-bugsink` (`ingested`), тест `platform-errors.test.ts` - **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ``, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` - **Вход только eGov (PEP-71)**: Gitea-вход и пароль убраны из веба (маршрутов `/auth/start|callback|password` нет). Неизвестный ИИН → `registerEgovUser` (core/egov.ts): учётка `gitea_id < 0` без пароля, логин `egovLoginBase` из имени сертификата («ИВАНОВА АЙГЕРИМ» → `aigerim.ivanova`, дубль `-2`, без имени `user-<4 цифры>`). Самозарегистрированный владелец (без Gitea и пароля, не админ/allowlist) без пула не получает вход машины для агентов — `mayUseMachineLogin` (core/access.ts) в `startSession`. Старым учёткам ИИН — «Настройки» (пока залогинен) или `peppa user egov`; аварийный вход — `peppa web login-link` - **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из stdin или сгенерированный) diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 419df6e8..0da94323 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -2,6 +2,7 @@ // alerts) to the paired chat and turns button presses / replies into answers delivered // 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 { reportPlatformError } from "@peppa/core"; import { accountUsageForUser, describeUsage, @@ -701,6 +702,7 @@ export function createBot(o: BotOptions) { await finishUpdate(db, u.update_id, r, botUserId); } catch (e) { log(`update ${u.update_id}: ${(e as Error).stack ?? e}`); + void reportPlatformError(db, e, { service: "bot", where: u.message ? "message" : u.callback_query ? `button ${u.callback_query.data ?? ""}`.slice(0, 60) : "update" }); await finishUpdate(db, u.update_id, "failed", botUserId); } } diff --git a/apps/bot/src/index.ts b/apps/bot/src/index.ts index 594f6e49..64ef3cd4 100644 --- a/apps/bot/src/index.ts +++ b/apps/bot/src/index.ts @@ -2,6 +2,7 @@ import { createDb } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { setRunnerClient } from "@peppa/runner"; +import { installCrashReporting } from "@peppa/core"; import { createBot } from "./bot.ts"; import { TelegramApi } from "./telegram.ts"; @@ -13,6 +14,8 @@ if (!env.TELEGRAM_BOT_TOKEN) { const db = createDb(env.PEPPA_DB); // PEP-21: the bot only enqueues runner commands; the runner service (watchdog) runs them. setRunnerClient(true, db); +// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it. +installCrashReporting(db, "bot"); const bot = createBot({ db, api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL), diff --git a/apps/web/app/api/client-errors/route.ts b/apps/web/app/api/client-errors/route.ts new file mode 100644 index 00000000..8d929f49 --- /dev/null +++ b/apps/web/app/api/client-errors/route.ts @@ -0,0 +1,42 @@ +// PEP-91: errors from the browser (ErrorReporter) → Bugsink, source `web` of the platform project. +// No login needed (the login page breaks too): size cap and a per-IP limit instead. +import { reportPlatformError } from "@peppa/core"; +import { db } from "@/lib/db"; + +const MAX_BYTES = 16 * 1024; +const PER_IP_PER_MIN = 20; +const hits = new Map(); + +function limited(ip: string, now = Date.now()): boolean { + const h = hits.get(ip); + if (!h || now - h.at >= 60_000) { + if (hits.size > 5000) hits.clear(); + hits.set(ip, { at: now, n: 1 }); + return false; + } + return ++h.n > PER_IP_PER_MIN; +} + +const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max) : undefined); + +export async function POST(req: Request) { + const ip = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local"; + if (limited(ip)) return new Response(null, { status: 429 }); + const raw = await req.text(); + if (raw.length > MAX_BYTES) return new Response(null, { status: 413 }); + let b: Record; + try { + b = JSON.parse(raw) as Record; + } catch { + return new Response(null, { status: 400 }); + } + const message = str(b.message, 2000); + if (!message) return new Response(null, { status: 400 }); + const path = str(b.url, 500); + const sent = await reportPlatformError( + db, + { name: str(b.type, 100) || "Error", message, stack: str(b.stack, 8000) }, + { service: "browser", kind: "web", platform: "javascript", where: path?.split("?")[0], request: { url: path, method: "GET", userAgent: req.headers.get("user-agent") ?? undefined } }, + ); + return Response.json({ sent }); +} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 5259483f..71f6ad47 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -4,6 +4,7 @@ import { GeistSans } from "geist/font/sans"; import { GeistMono } from "geist/font/mono"; import { cn } from "@/lib/utils"; import { THEME_COOKIE } from "@/lib/theme"; +import { ErrorReporter } from "@/components/ErrorReporter"; import "./app.css"; export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты", icons: { icon: "/icon.svg" } }; @@ -13,7 +14,10 @@ export default async function RootLayout({ children }: { children: ReactNode }) const light = (await cookies()).get(THEME_COOKIE)?.value === "light"; return ( - {children} + + + {children} + ); } diff --git a/apps/web/components/ErrorReporter.tsx b/apps/web/components/ErrorReporter.tsx new file mode 100644 index 00000000..56d3d123 --- /dev/null +++ b/apps/web/components/ErrorReporter.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { useEffect } from "react"; + +const MAX_PER_PAGE = 10; + +/** PEP-91: browser errors of Peppa's own pages → /api/client-errors → Bugsink (PEP-web). */ +export function ErrorReporter() { + useEffect(() => { + let sent = 0; + const seen = new Set(); + const send = (type: string, message: string, stack?: string) => { + const key = `${type}|${message}`; + if (sent >= MAX_PER_PAGE || seen.has(key) || !message) return; + seen.add(key); + sent++; + const body = JSON.stringify({ type, message: message.slice(0, 2000), stack: stack?.slice(0, 8000), url: location.pathname + location.search }); + void fetch("/api/client-errors", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).catch(() => {}); + }; + const onError = (ev: ErrorEvent) => { + const e = ev.error as Error | undefined; + // "Script error." comes from cross-origin scripts without details: nothing to act on. + if (!e && (!ev.message || ev.message === "Script error.")) return; + send(e?.name ?? "Error", e?.message ?? ev.message, e?.stack ?? (ev.filename ? ` at ${ev.filename}:${ev.lineno}:${ev.colno}` : undefined)); + }; + const onRejection = (ev: PromiseRejectionEvent) => { + const r = ev.reason as Error | string | undefined; + if (r instanceof Error) send(r.name, r.message, r.stack); + else send("UnhandledRejection", typeof r === "string" ? r : JSON.stringify(r) ?? ""); + }; + window.addEventListener("error", onError); + window.addEventListener("unhandledrejection", onRejection); + return () => { + window.removeEventListener("error", onError); + window.removeEventListener("unhandledrejection", onRejection); + }; + }, []); + return null; +} diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts index 98b8e31e..79c32d4e 100644 --- a/apps/web/instrumentation.ts +++ b/apps/web/instrumentation.ts @@ -2,8 +2,10 @@ // and the runner-client mode (PEP-21): the web enqueues runner commands, the watchdog runs them. export async function register() { if (process.env.NEXT_RUNTIME !== "nodejs") return; - const { beat } = await import("@peppa/core"); + const { beat, installCrashReporting } = await import("@peppa/core"); const { db } = await import("@/lib/db"); + // PEP-91: a crash of the web goes to Bugsink before launchd restarts it. + installCrashReporting(db, "web"); const { setRunnerClient } = await import("@peppa/runner"); setRunnerClient(true, db); const version = process.env.NEXT_PUBLIC_PEPPA_VERSION; @@ -11,3 +13,17 @@ export async function register() { void tick(); setInterval(tick, 60_000).unref(); } + +/** PEP-91: an error while rendering or handling a request → Bugsink (PEP-api). */ +export async function onRequestError(err: unknown, request: { path: string; method: string; headers: Record }, context: { routerKind: string; routePath: string; routeType: string }) { + if (process.env.NEXT_RUNTIME !== "nodejs") return; + const { reportPlatformError } = await import("@peppa/core"); + const { db } = await import("@/lib/db"); + const ua = request.headers["user-agent"]; + await reportPlatformError(db, err, { + service: "web", + where: `${request.method} ${context.routePath}`, + request: { url: request.path, method: request.method, userAgent: typeof ua === "string" ? ua : undefined }, + tags: { route_type: context.routeType }, + }); +} diff --git a/openspec/changes/pep-91-platform-errors/proposal.md b/openspec/changes/pep-91-platform-errors/proposal.md new file mode 100644 index 00000000..b1442f63 --- /dev/null +++ b/openspec/changes/pep-91-platform-errors/proposal.md @@ -0,0 +1,32 @@ +# Proposal: PEP-91 — Пеппа ловит свои ошибки + +Задача Пеппы: **PEP-91**. + +## Why + +15.11 живой сайт отдавал 500 всем вошедшим (`no such column: "google_sub"`: схема из рабочей +копии опередила миграцию). Узнали об этом от PM. Bugsink (PEP-58) уже ловит ошибки проектов +на фабрике, но сама Пеппа к нему не подключена: её ошибки остаются в логах launchd. + +## What Changes + +- Проект `PEP` подключается к Bugsink как любой проект: источники `PEP-web` и `PEP-api`, + вебхук, цель «Стабильность», политика `backlog`. Новая команда CLI + `peppa project errors ` делает то же, что кнопка «Подключить отслеживание ошибок». +- Свой лёгкий отправитель по протоколу Sentry (`core/error-report.ts`, без внешнего SDK): + envelope `POST /api//envelope/`, `X-Sentry-Auth`, стек V8 → frames, `release` = коммит + процесса, `environment` = `PEPPA_ENVIRONMENT` (по умолчанию `live`), теги `service`, `where`. + DSN — источники платформенного проекта (`PEPPA_PLATFORM_KEY`) из БД (кэш 5 мин) или + `PEPPA_ERRORS_DSN_API`/`_WEB`; адрес приёма — `BUGSINK_URL` (внутренний), иначе хост DSN. + Никогда не бросает, тайм-аут 3 с, одна и та же ошибка не чаще раза в минуту на процесс, + не больше 30 в минуту. `PEPPA_ERRORS=off` выключает. +- Кто отправляет (`api`): сервер веба (`onRequestError` в `instrumentation.ts`), вачдог + (ошибки частей тика и сессий), бот (обработка обновлений), падения процессов веб/бот/вачдог + (`uncaughtException`/`unhandledRejection`: отправить и упасть, как раньше). +- Браузер (`web`): `ErrorReporter` в корневом layout ловит `error`/`unhandledrejection` и шлёт + в `POST /api/client-errors` (≤16 КБ, 20 в минуту на IP, не больше 10 со страницы); веб + пересылает в `PEP-web`. DSN в браузер не попадает. + +## Вне scope + +Source maps, трейсинг, ошибки агентов в tmux. diff --git a/openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md b/openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md new file mode 100644 index 00000000..fc9bf97c --- /dev/null +++ b/openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: Ошибки самой Пеппы уходят в Bugsink +Пеппа SHALL отправлять свои ошибки (сервер веба, браузер, бот, вачдог, падения процессов) в +источники Bugsink платформенного проекта по протоколу Sentry, без внешнего SDK и не ломая работу +при недоступном Bugsink. + +#### Scenario: Ошибка сервера веба +- **WHEN** запрос к вебу падает с исключением, а у проекта `PEP` есть источник `api` +- **THEN** в Bugsink уходит envelope с типом и текстом ошибки, стеком, `release` = коммит, тегом `service=web` и адресом запроса + +#### Scenario: Ошибка в браузере +- **WHEN** на странице Пеппы случается необработанная ошибка JS +- **THEN** браузер шлёт её в `/api/client-errors`, веб пересылает в источник `web`; DSN браузеру не выдаётся + +#### Scenario: Шум и недоступность +- **WHEN** одна и та же ошибка повторяется много раз в минуту или Bugsink не отвечает +- **THEN** отправляется не больше одной такой ошибки в минуту, а вызывающий код не получает исключения и не ждёт дольше 3 секунд + +#### Scenario: Не подключено +- **WHEN** у платформенного проекта нет источников и env DSN не задан, или `PEPPA_ERRORS=off` +- **THEN** ничего не отправляется diff --git a/openspec/changes/pep-91-platform-errors/tasks.md b/openspec/changes/pep-91-platform-errors/tasks.md new file mode 100644 index 00000000..efe6ff73 --- /dev/null +++ b/openspec/changes/pep-91-platform-errors/tasks.md @@ -0,0 +1,15 @@ +## 1. Отправитель +- [x] 1.1 `core/error-report.ts`: `parseDsn`, `errorEvent` (стек V8 → frames), `bugsinkEnvelope`, `reportPlatformError` (DSN из env/БД, троттлинг, тайм-аут, выключатель) +- [x] 1.2 `installCrashReporting(db, service)` — падение процесса: отправить и выйти с кодом 1 + +## 2. Кто отправляет +- [x] 2.1 Веб: `onRequestError` в `instrumentation.ts`, `installCrashReporting` в `register` +- [x] 2.2 Браузер: `components/ErrorReporter.tsx` + `POST /api/client-errors` (лимиты) +- [x] 2.3 Вачдог: ошибки частей тика и сессий; `installCrashReporting` в `peppa watchdog` +- [x] 2.4 Бот: ошибки обработки обновлений; `installCrashReporting` + +## 3. Подключение +- [x] 3.1 CLI `peppa project errors ` (= `connectErrorTracking`) +- [x] 3.2 `mock-bugsink`: приём envelope (`events`), e2e `platform-errors.test.ts` +- [x] 3.3 AGENTS.md +- [ ] 3.4 На живой системе: `peppa project errors PEP` (координатор после мержа) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index badc4571..e9ab527d 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -74,6 +74,8 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core"; import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core"; import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core"; +import { connectErrorTrackingFromEnv } from "@peppa/runner"; +import { installCrashReporting } from "@peppa/core"; import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; @@ -88,6 +90,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project agent [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit) peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) peppa project transfer (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook) + peppa project errors (PEP-58/91: connect to Bugsink — -web and -api, webhook, goal «Стабильность») peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back) peppa project list peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) @@ -293,6 +296,14 @@ async function main(): Promise { console.log(`${p.key} owner → ${u?.login ?? "none"}`); break; } + case "project errors": { + if (!args[0]) throw new PeppaError("usage: peppa project errors "); + const p = await getProject(db, args[0]); + const r = await connectErrorTrackingFromEnv(db, p); + for (const s of r.sources) console.log(`${s.kind}: Bugsink project #${s.bugsinkProjectId}`); + console.log(`webhook: ${r.settings.webhookAuto ? "set automatically" : `add a Custom webhook in Bugsink → ${r.webhookUrl}`}`); + break; + } case "project import-issues": { if (!args[0]) throw new PeppaError("usage: peppa project import-issues "); const p = await getProject(db, args[0]); @@ -832,7 +843,11 @@ async function main(): Promise { log: (m: string) => console.log(`${new Date().toISOString()} ${m}`), }; if (opts.once) await tick(db, wopts); - else await runWatchdog(db, wopts); + else { + // PEP-91: a crash of the watchdog goes to Bugsink before launchd restarts it. + installCrashReporting(db, "watchdog"); + await runWatchdog(db, wopts); + } break; } default: diff --git a/packages/core/src/error-report.ts b/packages/core/src/error-report.ts new file mode 100644 index 00000000..7186e847 --- /dev/null +++ b/packages/core/src/error-report.ts @@ -0,0 +1,211 @@ +// PEP-91: Peppa reports its own errors to Bugsink — the Sentry envelope protocol without an SDK. +// DSNs are the error sources of the platform project (PEPPA_PLATFORM_KEY, connected like any +// project, PEP-58) or PEPPA_ERRORS_DSN_API / _WEB. Never throws, never waits longer than 3 s. +import { randomBytes } from "node:crypto"; +import { hostname } from "node:os"; +import { and, eq } from "drizzle-orm"; +import { errorSources, projects, type Db } from "@peppa/db"; +import { peppaCommit, peppaVersion } from "./monitor.ts"; + +export type ErrorSourceKind = "api" | "web"; + +export interface ParsedDsn { + key: string; + origin: string; + projectId: string; +} + +/** `https://@host/` → parts; null for anything else. */ +export function parseDsn(dsn: string): ParsedDsn | null { + try { + const u = new URL(dsn); + const projectId = u.pathname.replace(/^\/+|\/+$/g, ""); + if (!u.username || !/^\d+$/.test(projectId)) return null; + return { key: decodeURIComponent(u.username), origin: u.origin, projectId }; + } catch { + return null; + } +} + +export interface StackFrame { + function?: string; + filename: string; + lineno?: number; + colno?: number; + in_app: boolean; +} + +const FRAME_RE = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/; + +/** V8 stack (`at fn (file:1:2)`) → Sentry frames, outermost first. */ +export function stackFrames(stack: string | undefined): StackFrame[] { + const frames: StackFrame[] = []; + for (const line of (stack ?? "").split("\n")) { + const m = FRAME_RE.exec(line); + if (!m) continue; + const filename = m[2]!.replace(/^file:\/\//, ""); + frames.push({ + function: m[1] || undefined, + filename, + lineno: Number(m[3]), + colno: Number(m[4]), + in_app: !/node_modules|^node:|^internal\//.test(filename), + }); + } + return frames.reverse().slice(-50); +} + +export interface ErrorContext { + service: string; + /** Which part failed: "tick: autonomy", "session #12", "GET /p/PEP"… */ + where?: string; + kind?: ErrorSourceKind; + platform?: "node" | "javascript"; + request?: { url?: string; method?: string; userAgent?: string }; + tags?: Record; + /** Overrides for tests. */ + release?: string | null; + environment?: string; +} + +export interface ErrorLike { + name?: string; + message?: string; + stack?: string; +} + +function asError(e: unknown): ErrorLike { + if (e instanceof Error) return e; + if (e && typeof e === "object" && "message" in e) return e as ErrorLike; + return { name: "Error", message: typeof e === "string" ? e : JSON.stringify(e) ?? String(e) }; +} + +/** A Sentry event for an error. */ +export function errorEvent(e: unknown, ctx: ErrorContext, at = new Date()) { + const err = asError(e); + const frames = stackFrames(err.stack); + const tags: Record = { service: ctx.service, ...(ctx.where ? { where: ctx.where.slice(0, 200) } : {}), ...ctx.tags }; + return { + event_id: randomBytes(16).toString("hex"), + timestamp: at.getTime() / 1000, + platform: ctx.platform ?? "node", + level: "error", + logger: ctx.service, + server_name: hostname(), + release: (ctx.release !== undefined ? ctx.release : peppaCommit()) ?? `peppa@${peppaVersion()}`, + environment: ctx.environment ?? process.env.PEPPA_ENVIRONMENT ?? "live", + tags, + ...(ctx.request ? { request: { url: ctx.request.url, method: ctx.request.method, headers: ctx.request.userAgent ? { "User-Agent": ctx.request.userAgent } : undefined } } : {}), + exception: { + values: [{ type: err.name || "Error", value: (err.message ?? "").slice(0, 2000), ...(frames.length ? { stacktrace: { frames } } : {}) }], + }, + }; +} +export type ErrorEvent = ReturnType; + +/** The envelope body for one event. */ +export function bugsinkEnvelope(dsn: string, event: ErrorEvent): string { + return [JSON.stringify({ event_id: event.event_id, dsn, sent_at: new Date().toISOString() }), JSON.stringify({ type: "event" }), JSON.stringify(event)].join("\n") + "\n"; +} + +/** POST one event; `ingestBase` (BUGSINK_URL on the same host) beats the DSN's public host. */ +export async function sendEvent(dsn: string, event: ErrorEvent, o: { ingestBase?: string; timeoutMs?: number } = {}): Promise { + const d = parseDsn(dsn); + if (!d) return false; + const base = (o.ingestBase || d.origin).replace(/\/$/, ""); + try { + const res = await fetch(`${base}/api/${d.projectId}/envelope/`, { + method: "POST", + headers: { "Content-Type": "application/x-sentry-envelope", "X-Sentry-Auth": `Sentry sentry_version=7, sentry_key=${d.key}, sentry_client=peppa/${peppaVersion()}` }, + body: bugsinkEnvelope(dsn, event), + signal: AbortSignal.timeout(o.timeoutMs ?? 3000), + }); + return res.ok; + } catch { + return false; + } +} + +const DSN_TTL = 5 * 60_000; +const dsnCache = new Map(); + +/** DSN of the platform project's source: env first, then the DB (cached 5 min). */ +export async function platformDsn(db: Db, kind: ErrorSourceKind, now = Date.now()): Promise { + const env = process.env[kind === "web" ? "PEPPA_ERRORS_DSN_WEB" : "PEPPA_ERRORS_DSN_API"]; + if (env) return env; + const hit = dsnCache.get(kind); + if (hit && now - hit.at < DSN_TTL) return hit.dsn; + const key = process.env.PEPPA_PLATFORM_KEY || "PEP"; + const [row] = await db + .select({ dsn: errorSources.dsn }) + .from(errorSources) + .innerJoin(projects, eq(projects.id, errorSources.projectId)) + .where(and(eq(projects.key, key), eq(errorSources.kind, kind))); + const dsn = row?.dsn ?? null; + dsnCache.set(kind, { dsn, at: now }); + return dsn; +} + +const SAME_ERROR_MS = 60_000; +const MAX_PER_MINUTE = 30; +const seen = new Map(); +let windowStart = 0; +let windowCount = 0; + +/** Throttle: one per fingerprint per minute, 30 a minute overall. Exported for tests. */ +export function shouldSend(fingerprint: string, now = Date.now()): boolean { + if (now - windowStart >= 60_000) { + windowStart = now; + windowCount = 0; + for (const [k, t] of seen) if (now - t >= SAME_ERROR_MS) seen.delete(k); + } + const last = seen.get(fingerprint); + if (last !== undefined && now - last < SAME_ERROR_MS) return false; + if (windowCount >= MAX_PER_MINUTE) return false; + seen.set(fingerprint, now); + windowCount++; + return true; +} + +export function resetErrorReporting() { + seen.clear(); + dsnCache.clear(); + windowStart = 0; + windowCount = 0; +} + +/** + * Report one of Peppa's own errors. Never throws; resolves to whether Bugsink took it + * (false when not connected, throttled, switched off or unreachable). + */ +export async function reportPlatformError(db: Db, e: unknown, ctx: ErrorContext): Promise { + try { + if (process.env.PEPPA_ERRORS === "off") return false; + const kind = ctx.kind ?? "api"; + const event = errorEvent(e, ctx); + const ex = event.exception.values[0]!; + const top = ex.stacktrace?.frames.at(-1); + if (!shouldSend(`${kind}|${ctx.service}|${ex.type}|${ex.value.slice(0, 200)}|${top?.filename ?? ""}:${top?.lineno ?? ""}`)) return false; + const dsn = await platformDsn(db, kind); + if (!dsn) return false; + return await sendEvent(dsn, event, { ingestBase: process.env.BUGSINK_URL }); + } catch { + return false; + } +} + +let crashInstalled = false; + +/** A process crash (uncaught exception / unhandled rejection) goes to Bugsink, then exit 1 as before. */ +export function installCrashReporting(db: Db, service: string, log: (m: string) => void = (m) => console.error(m)): void { + if (crashInstalled) return; + crashInstalled = true; + const crash = (kind: string) => (e: unknown) => { + log(`${service} ${kind}: ${(e as Error)?.stack ?? String(e)}`); + const done = () => process.exit(1); + setTimeout(done, 3500).unref(); + void reportPlatformError(db, e, { service, where: kind }).finally(done); + }; + process.on("uncaughtException", crash("uncaughtException")); + process.on("unhandledRejection", crash("unhandledRejection")); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e8663891..74d495ea 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,6 +15,7 @@ export * from "./users.ts"; export * from "./oauth.ts"; export * from "./access.ts"; export * from "./monitor.ts"; +export * from "./error-report.ts"; export * from "./backup.ts"; export * from "./repo-info.ts"; export * from "./incidents.ts"; diff --git a/packages/runner/src/incidents.ts b/packages/runner/src/incidents.ts index d47e965d..1cb8c269 100644 --- a/packages/runner/src/incidents.ts +++ b/packages/runner/src/incidents.ts @@ -292,6 +292,11 @@ export async function connectErrorTracking(db: Db, project: Project, client: Bug return { settings, sources: await listErrorSources(db, project.id), webhookUrl }; } +/** `peppa project errors ` (PEP-91): connect with the Bugsink configured in env. */ +export function connectErrorTrackingFromEnv(db: Db, project: Project): Promise { + return connectErrorTracking(db, project, bugsinkFromEnv(), bugsinkWebhookBase()); +} + /** Where Bugsink (in docker) reaches Peppa's web; PEPPA_WEB_URL by default. */ export function bugsinkWebhookBase(): string { return process.env.BUGSINK_WEBHOOK_BASE ?? process.env.PEPPA_WEB_URL ?? "http://localhost:3100"; diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 2d820d20..0eb62c77 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -24,7 +24,7 @@ import * as tmux from "./tmux.ts"; import { recordLimit } from "./limits.ts"; import { killRunner, resumeSession } from "./sessions.ts"; import { hostTick } from "./hosts.ts"; -import { getSubscription, isUsable } from "@peppa/core"; +import { getSubscription, isUsable, reportPlatformError } from "@peppa/core"; import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts"; import { monitorTick } from "./monitor.ts"; import { platformBuildTick } from "./platform-build.ts"; @@ -70,42 +70,50 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { try { await checkSession(db, s, opts, cfg, log); } catch (e) { - log(`session #${s.id}: ${(e as Error).message}`); + failed(db, log, `session #${s.id}`)(e); } } // PEP-28: planned automatic restarts, reminders/escalation, runners waiting for nobody. - await restartTick(db, { now, cfg, log }).catch((e) => log(`restarts: ${(e as Error).message}`)); - await remindTick(db, { now, cfg, log }).catch((e) => log(`reminders: ${(e as Error).message}`)); - await idleStopTick(db, { now, cfg, log }).catch((e) => log(`idle: ${(e as Error).message}`)); + await restartTick(db, { now, cfg, log }).catch(failed(db, log, "restarts")); + await remindTick(db, { now, cfg, log }).catch(failed(db, log, "reminders")); + await idleStopTick(db, { now, cfg, log }).catch(failed(db, log, "idle")); // 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}`)); + await runnerTick(db, { log }).catch(failed(db, log, "runners")); // PEP-40: runner hosts — online/offline, load, versions (once a minute each). - await hostTick(db, { now: opts.now, log }).catch((e) => log(`hosts: ${(e as Error).message}`)); + await hostTick(db, { now: opts.now, log }).catch(failed(db, log, "hosts")); // 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}`)); + await budgetTick(db, { now: opts.now, log }).catch(failed(db, log, "budgets")); // Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher. // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them. - await intakeTick(db, { now: opts.now, log }).catch((e) => log(`intake: ${(e as Error).message}`)); - await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`)); + await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake")); + await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy")); // Errors of running products (PEP-58): Bugsink poll + incident policies. - await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`)); + await incidentTick(db, { now: opts.now, log }).catch(failed(db, log, "incidents")); // Daily digest at each user's time (PEP-29); a no-op outside their window. - await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`)); + await digestTick(db, { now: opts.now, log }).catch(failed(db, log, "digest")); // PEP-60: platform channel — re-check a channel that isn't working yet, new builds, the // platform digest at its time. - await recheckPlatformChannel(db, { now: opts.now, log }).catch((e) => log(`platform channel: ${(e as Error).message}`)); - await platformBuildTick(db, { now: opts.now, log }).catch((e) => log(`platform build: ${(e as Error).message}`)); - await platformDigestTick(db, { now: opts.now, log }).catch((e) => log(`platform digest: ${(e as Error).message}`)); + await recheckPlatformChannel(db, { now: opts.now, log }).catch(failed(db, log, "platform channel")); + await platformBuildTick(db, { now: opts.now, log }).catch(failed(db, log, "platform build")); + await platformDigestTick(db, { now: opts.now, log }).catch(failed(db, log, "platform digest")); // PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour. - await syncChats(db, { now: opts.now }).catch((e) => log(`chats: ${(e as Error).message}`)); + await syncChats(db, { now: opts.now }).catch(failed(db, log, "chats")); const nowMs = (opts.now ?? new Date()).getTime(); if (nowMs - lastChatPrune >= 3600_000) { lastChatPrune = nowMs; - await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch((e) => log(`chats prune: ${(e as Error).message}`)); + await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch(failed(db, log, "chats prune")); } } let lastChatPrune = 0; +/** A part of the watchdog failed: log it and send it to Bugsink (PEP-91). */ +function failed(db: Db, log: (m: string) => void, where: string) { + return (e: unknown) => { + log(`${where}: ${(e as Error)?.message ?? e}`); + void reportPlatformError(db, e, { service: "watchdog", where }); + }; +} + async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) { if (s.tmuxName.startsWith("pending-")) return; const nowDate = opts.now ?? new Date(); @@ -219,18 +227,18 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS }); } while (!signal?.aborted) { - await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); + await tick(db, opts).catch(failed(db, log, "tick failed")); // Heartbeat and the check on the bot and the web (PEP-20). - await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`)); + await monitorTick(db, { log }).catch(failed(db, log, "monitor failed")); // CI results lost on the way (PEP-57): poll commit statuses about once a minute. if (Date.now() - lastCiPoll >= 60_000) { lastCiPoll = Date.now(); - await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`)); + await pollChecks(db).catch(failed(db, log, "ci poll failed")); // Reviews whose MCP process died before running them (PEP-26). - await reviewTick(db, log).catch((e) => log(`review tick failed: ${(e as Error).message}`)); + await reviewTick(db, log).catch(failed(db, log, "review tick failed")); } // Daily copy of the SQLite database (PEP-36); a no-op until a day has passed. - await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`)); + await backupDb(db, { log }).catch(failed(db, log, "backup failed")); await new Promise((r) => setTimeout(r, opts.intervalMs)); } await service?.stop(); diff --git a/packages/testkit/src/mock-bugsink.ts b/packages/testkit/src/mock-bugsink.ts index 9319f448..c1335d7b 100644 --- a/packages/testkit/src/mock-bugsink.ts +++ b/packages/testkit/src/mock-bugsink.ts @@ -69,6 +69,14 @@ export class MockBugsink { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { + const ingest = /^\/api\/(\d+)\/envelope\/$/.exec(req.url!.split("?")[0]!); + if (req.method === "POST" && ingest) { + void this.ingestEnvelope(Number(ingest[1]), String(req.headers["x-sentry-auth"] ?? ""), body).then((r) => { + res.writeHead(r.status, { "Content-Type": "application/json" }); + res.end(JSON.stringify(r.body)); + }); + return; + } const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {}); res.writeHead(r.status, { "Content-Type": "application/json" }); res.end(JSON.stringify(r.body ?? {})); @@ -157,6 +165,24 @@ export class MockBugsink { return issue.id; } + /** Envelopes taken by the ingest endpoint (PEP-91): the raw event as the SDK sent it. */ + readonly ingested: Array<{ projectId: number; event: Record }> = []; + + /** `POST /api//envelope/` like Bugsink's ingest: sentry_key must match the project's DSN. */ + async ingestEnvelope(projectId: number, auth: string, body: string): Promise<{ status: number; body: unknown }> { + const p = this.projects.get(projectId); + const key = /sentry_key=([^,\s]+)/.exec(auth)?.[1]; + if (!p || key !== p.key) return { status: 403, body: { error: "invalid sentry_key" } }; + const lines = body.split("\n").filter(Boolean); + const item = lines.findIndex((l, n) => n > 0 && (JSON.parse(l) as { type?: string }).type === "event"); + if (item < 0 || !lines[item + 1]) return { status: 400, body: { error: "no event item" } }; + const event = JSON.parse(lines[item + 1]!) as Record; + this.ingested.push({ projectId, event }); + const ex = event.exception?.values?.[0] ?? { type: "Error", value: String(event.message ?? "") }; + await this.capture(projectId, { type: ex.type, value: ex.value, frames: ex.stacktrace?.frames, environment: event.environment, release: event.release, level: event.level }); + return { status: 200, body: { id: event.event_id } }; + } + private async alert(i: Issue, reason: string) { const p = this.projects.get(i.project)!; if (!p.webhook) return; diff --git a/packages/testkit/test/platform-errors.test.ts b/packages/testkit/test/platform-errors.test.ts new file mode 100644 index 00000000..caa6c887 --- /dev/null +++ b/packages/testkit/test/platform-errors.test.ts @@ -0,0 +1,108 @@ +// PEP-91: Peppa's own errors → Bugsink (envelope protocol, no SDK): the platform project is +// connected like any project; server errors go to -api, browser errors to -web, +// the watchdog's failing parts too; throttled, never throwing, silent when not connected. +import assert from "node:assert/strict"; +import { after, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); + +const bugsink = await new MockBugsink().start(); +const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); +// Ingest goes to BUGSINK_URL (same host), not to the DSN's public host. +process.env.BUGSINK_URL = bugsink.url; + +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-91: Peppa reports its own errors to Bugsink", () => { + test("not connected → nothing is sent and nothing throws", async () => { + process.env.PEPPA_PLATFORM_KEY = "NOPE"; + core.resetErrorReporting(); + assert.equal(await core.reportPlatformError(db, new Error("boom"), { service: "web" }), false); + assert.equal(bugsink.ingested.length, 0); + }); + + test("parseDsn and V8 stack → frames (outermost first)", () => { + assert.deepEqual(core.parseDsn("https://abc123@bugsink.telecom.quest/4"), { key: "abc123", origin: "https://bugsink.telecom.quest", projectId: "4" }); + assert.equal(core.parseDsn("not a dsn"), null); + const frames = core.stackFrames("Error: x\n at inner (/app/packages/core/src/users.ts:43:17)\n at async outer (/app/node_modules/next/x.js:1:2)\n at node:internal/process:3:4"); + assert.equal(frames.length, 3); + assert.equal(frames.at(-1)!.function, "inner"); + assert.equal(frames.at(-1)!.in_app, true); + assert.equal(frames[1]!.in_app, false); + }); + + test("connected platform project: server error → -api with release, service and request", async () => { + const p = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = p.key; + core.resetErrorReporting(); + const r = await runner.connectErrorTracking(db, await core.getProject(db, p.key), client, "http://peppa.test"); + const api = r.sources.find((s) => s.kind === "api")!.bugsinkProjectId; + const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId; + + const err = new Error('no such column: "google_sub"'); + const ok = await core.reportPlatformError(db, err, { service: "web", where: "GET /", request: { url: "/", method: "GET" }, release: "abc1234", environment: "live" }); + assert.equal(ok, true); + const got = bugsink.ingested.at(-1)!; + assert.equal(got.projectId, api); + const ev = got.event as ReturnType; + assert.equal(ev.release, "abc1234"); + assert.equal(ev.environment, "live"); + assert.equal(ev.tags.service, "web"); + assert.equal(ev.tags.where, "GET /"); + assert.equal(ev.request?.url, "/"); + assert.equal(ev.exception.values[0]!.value, 'no such column: "google_sub"'); + assert.ok(ev.exception.values[0]!.stacktrace!.frames.length > 0); + // Bugsink grouped it into an issue — Peppa's own poll turns it into an incident of the project. + const issues = await client.listIssues(api); + assert.equal(issues.length, 1); + assert.equal(await runner.pollBugsink(db, client), 1); + const incidents = await core.listIncidents(db, (await core.getProject(db, p.key)).id); + assert.equal(incidents.length, 1); + + // Same error again within a minute: throttled, not sent. + assert.equal(await core.reportPlatformError(db, err, { service: "web", where: "GET /", release: "abc1234" }), false); + assert.equal(bugsink.ingested.filter((i) => i.projectId === api).length, 1); + + // Browser errors go to -web. + assert.equal(await core.reportPlatformError(db, { name: "TypeError", message: "x is undefined", stack: "TypeError: x\n at f (https://peppa.test/_next/static/a.js:1:2)" }, { service: "browser", kind: "web", platform: "javascript" }), true); + assert.equal(bugsink.ingested.at(-1)!.projectId, web); + }); + + test("a failing watchdog part is reported (service=watchdog, where=)", async () => { + core.resetErrorReporting(); + const before = bugsink.ingested.length; + // A part of the tick blows up: hide the incidents table for one tick. + db.run(sql`ALTER TABLE incidents RENAME TO incidents_x`); + try { + await runner.tick(db, { intervalMs: 1000, stallMs: 60_000 }); + } finally { + db.run(sql`ALTER TABLE incidents_x RENAME TO incidents`); + } + // Sent in the background: the tick doesn't wait for Bugsink. + const tags = () => bugsink.ingested.slice(before).map((i) => (i.event as ReturnType).tags); + await waitFor("watchdog error in Bugsink", async () => tags().some((t) => t.service === "watchdog" && t.where === "incidents"), 5000); + }); + + test("Bugsink down → false within the timeout, no exception", async () => { + core.resetErrorReporting(); + process.env.BUGSINK_URL = "http://127.0.0.1:9"; + const t0 = Date.now(); + assert.equal(await core.reportPlatformError(db, new Error("unreachable"), { service: "bot" }), false); + assert.ok(Date.now() - t0 < 3500); + process.env.BUGSINK_URL = bugsink.url; + }); + + test("PEPPA_ERRORS=off switches it off", async () => { + core.resetErrorReporting(); + process.env.PEPPA_ERRORS = "off"; + assert.equal(await core.reportPlatformError(db, new Error("quiet"), { service: "web" }), false); + delete process.env.PEPPA_ERRORS; + }); +}); -- 2.45.2 From 02b045700d7be54303eaa912e2e3af3ccdb53e2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 13:01:41 +0500 Subject: [PATCH 002/394] PEP-92: welcome page /welcome, opens once for new users Co-Authored-By: Claude Sonnet 5.5 --- apps/web/app/(app)/page.tsx | 4 +- apps/web/app/(app)/welcome/page.tsx | 81 +++++++++++++++++++ apps/web/components/Sidebar.tsx | 3 +- .../2026-11-15-pep-92-welcome-page/design.md | 1 + .../proposal.md | 6 ++ .../specs/onboarding/spec.md | 14 ++++ .../2026-11-15-pep-92-welcome-page/tasks.md | 3 + openspec/specs/onboarding/spec.md | 13 +++ packages/core/src/onboarding.ts | 9 +++ packages/testkit/test/agent-smarts.test.ts | 9 +++ 10 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 apps/web/app/(app)/welcome/page.tsx create mode 100644 openspec/changes/archive/2026-11-15-pep-92-welcome-page/design.md create mode 100644 openspec/changes/archive/2026-11-15-pep-92-welcome-page/proposal.md create mode 100644 openspec/changes/archive/2026-11-15-pep-92-welcome-page/specs/onboarding/spec.md create mode 100644 openspec/changes/archive/2026-11-15-pep-92-welcome-page/tasks.md diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 30387c78..d20b35bc 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -1,4 +1,5 @@ -import { listUserProjects, onboardingChecklist, progressOverview } from "@peppa/core"; +import { redirect } from "next/navigation"; +import { claimWelcome, listUserProjects, onboardingChecklist, progressOverview } from "@peppa/core"; import { ProgressOverview } from "@/components/ProgressOverview"; import { OnboardingChecklist } from "@/components/Onboarding"; import { PugBanner } from "@/components/PugMascot"; @@ -14,6 +15,7 @@ import { activeSessions, inbox } from "@/lib/queries"; export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); const { error } = await searchParams; + if (await claimWelcome(db, user.id)) redirect("/welcome"); const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]); return ( }> diff --git a/apps/web/app/(app)/welcome/page.tsx b/apps/web/app/(app)/welcome/page.tsx new file mode 100644 index 00000000..fbb445fd --- /dev/null +++ b/apps/web/app/(app)/welcome/page.tsx @@ -0,0 +1,81 @@ +// PEP-92: the welcome page for everyone who signs in — why Peppa, how work goes, where to click. +import Link from "next/link"; +import { ArrowRight, Check } from "lucide-react"; +import { Workspace } from "@/components/Workspace"; +import { PageHeader, Section } from "@/components/common"; +import { PugMascot } from "@/components/PugMascot"; +import { requireUser } from "@/lib/auth"; + +const WHY = [ + { title: "Программировать не нужно", text: "Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты." }, + { title: "Всё на виду", text: "Доска показывает, что в работе, что готово и какой агент чем занят." }, + { title: "Последнее слово за вами", text: "Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять»." }, +]; + +const FLOW = [ + { title: "Стори", text: "Одна понятная история: «Страница каталога: фото, цена, кнопка „Купить“». Пишите, зачем это нужно и как понять, что готово.", href: "/projects", cta: "К проектам" }, + { title: "Бэклог → В работе", text: "Когда стори переходит «В работе», её берёт агент: придумывает план, пишет код, проверяет себя и открывает изменение.", href: null, cta: "" }, + { title: "Вопросы агентов", text: "Агент спрашивает только о важном: решения, деньги, доступы. Ответ — на Главной, в Telegram или через MCP.", href: "/", cta: "На Главную" }, + { title: "Ревью → Готово", text: "Придёт «готово к ревью» со ссылкой на стенд. Посмотрите и нажмите «Принять» — или напишите, что поправить, агент доделает.", href: null, cta: "" }, +]; + +const WORDS: Array<[string, string]> = [ + ["Проект", "ваш продукт: у него свой репозиторий, доска и агенты"], + ["Эпик", "метка, которая группирует стори одной большой цели"], + ["Стори", "одна задача для агента; одна стори — одно законченное изменение"], + ["Агент", "ИИ-разработчик со своим именем; работает на вашей подписке Claude или ChatGPT"], + ["Ревью", "момент, когда агент закончил, а вы решаете: принять или вернуть"], +]; + +export default async function Welcome() { + await requireUser(); + return ( + + Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат. +
+ +
+

Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.

+ + Начать с первых шагов + +
+
+
+
    + {WHY.map((w) => ( +
  • + {w.title} + {w.text} +
  • + ))} +
+
+
+
    + {FLOW.map((s, i) => ( +
  1. + {i + 1} +
    + {s.title} + {s.text} + {s.href && {s.cta} →} +
    +
  2. + ))} +
+
+
+
+ {WORDS.map(([t, d]) => ( +
+
{t}
+
{d}
+
+ ))} +
+

Что-то непонятно? Загляните в Помощь — там и подключение через MCP, и горячие клавиши.

+
+
+ ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index f2387bcc..c8125ae7 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react"; +import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react"; import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; @@ -26,6 +26,7 @@ const ITEMS: Item[] = [ { href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, { href: "/runners", label: "Работа агентов", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, + { href: "/welcome", label: "О Пеппе", icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true }, { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, { href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, { href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, diff --git a/openspec/changes/archive/2026-11-15-pep-92-welcome-page/design.md b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/design.md new file mode 100644 index 00000000..2dbf1f44 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/design.md @@ -0,0 +1 @@ +Без миграций и новых зависимостей. «Показано» — настройка `welcome.shown:`; `claimWelcome` (core/onboarding.ts) ставит её при первом заходе и возвращает true только если у пользователя нет проектов — владельцы с проектами редиректа не получают. Контент статический, в самой странице. diff --git a/openspec/changes/archive/2026-11-15-pep-92-welcome-page/proposal.md b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/proposal.md new file mode 100644 index 00000000..2f2a84ad --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/proposal.md @@ -0,0 +1,6 @@ +## Why +Войдя, человек видит рабочую Главную, но не понимает, зачем Пеппа и как тут работать (PEP-92). + +## What Changes +- Страница `/welcome` («О Пеппе»): зачем, как идёт работа (стори → агент → вопросы → ревью), словарь. +- Новый пользователь без проектов попадает на неё один раз при первом открытии Главной; дальше — пункт меню. diff --git a/openspec/changes/archive/2026-11-15-pep-92-welcome-page/specs/onboarding/spec.md b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/specs/onboarding/spec.md new file mode 100644 index 00000000..80710592 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/specs/onboarding/spec.md @@ -0,0 +1,14 @@ +## ADDED Requirements + +### Requirement: Велком-страница +Платформа SHALL иметь страницу `/welcome`, объясняющую, зачем Пеппа и как в ней работать, и открывать её сама один раз новому пользователю без проектов. + +#### Scenario: Первый вход +- **GIVEN** пользователь без проектов, не видевший велком-страницу +- **WHEN** он открывает Главную +- **THEN** его перенаправляют на `/welcome` + +#### Scenario: Повторный заход +- **GIVEN** пользователь уже один раз был перенаправлен на `/welcome` +- **WHEN** он снова открывает Главную +- **THEN** видна Главная, а страница доступна из меню «О Пеппе» diff --git a/openspec/changes/archive/2026-11-15-pep-92-welcome-page/tasks.md b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/tasks.md new file mode 100644 index 00000000..57278b85 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-92-welcome-page/tasks.md @@ -0,0 +1,3 @@ +- [x] 1. `claimWelcome` в core, редирект с Главной +- [x] 2. Страница `/welcome` и пункт меню «О Пеппе» +- [x] 3. Тест в agent-smarts diff --git a/openspec/specs/onboarding/spec.md b/openspec/specs/onboarding/spec.md index 807ea738..502dd26c 100644 --- a/openspec/specs/onboarding/spec.md +++ b/openspec/specs/onboarding/spec.md @@ -53,3 +53,16 @@ ChatGPT). На телефоне заголовок SHALL идти перед б - **GIVEN** пользователь прошёл пять шагов - **WHEN** он принимает первую стори - **THEN** блок шагов больше не показывается + +### Requirement: Велком-страница +Платформа SHALL иметь страницу `/welcome`, объясняющую, зачем Пеппа и как в ней работать, и открывать её сама один раз новому пользователю без проектов. + +#### Scenario: Первый вход +- **GIVEN** пользователь без проектов, не видевший велком-страницу +- **WHEN** он открывает Главную +- **THEN** его перенаправляют на `/welcome` + +#### Scenario: Повторный заход +- **GIVEN** пользователь уже один раз был перенаправлен на `/welcome` +- **WHEN** он снова открывает Главную +- **THEN** видна Главная, а страница доступна из меню «О Пеппе» diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts index c63929c4..653ea1ab 100644 --- a/packages/core/src/onboarding.ts +++ b/packages/core/src/onboarding.ts @@ -38,6 +38,15 @@ export async function dismissOnboarding(db: Db, userId: number): Promise { await setSetting(db, dismissedKey(userId), { at: new Date().toISOString() }); } +const welcomeKey = (userId: number) => `welcome.shown:${userId}`; + +/** PEP-92: the welcome page opens by itself once — for a user with no projects who has not seen it yet. */ +export async function claimWelcome(db: Db, userId: number): Promise { + if (await getSetting(db, welcomeKey(userId))) return false; + await setSetting(db, welcomeKey(userId), { at: new Date().toISOString() }); + return (await userProjectIds(db, userId)).length === 0; +} + export async function onboardingChecklist(db: Db, user: Pick): Promise { 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); diff --git a/packages/testkit/test/agent-smarts.test.ts b/packages/testkit/test/agent-smarts.test.ts index 2edb0669..dde88b73 100644 --- a/packages/testkit/test/agent-smarts.test.ts +++ b/packages/testkit/test/agent-smarts.test.ts @@ -169,6 +169,15 @@ describe("PEP-41: модель и провайдер стори", () => { }); }); +describe("PEP-92: велком-страница", () => { + test("Открывается сама один раз и только тому, у кого нет проектов", async () => { + const fresh = await core.upsertUserFromGitea(db, { id: 9201, login: "mock-welcome-9201" }, { access_token: "x" }); + assert.equal(await core.claimWelcome(db, fresh.id), true, "первый заход нового пользователя"); + assert.equal(await core.claimWelcome(db, fresh.id), false, "повторно не навязываем"); + assert.equal(await core.claimWelcome(db, pm.id), false, "у владельца проектов своя Главная"); + }); +}); + describe("PEP-31: чек-лист первого запуска", () => { test("Шаги отмечаются по данным, чек-лист скрывается после выполнения или по кнопке", async () => { const u = await core.upsertUserFromGitea(db, { id: 3131, login: "mock-new-3131" }, { access_token: "x" }); -- 2.45.2 From 20031adc08e6d05fa18c935e8567207eddd62517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 13:33:41 +0500 Subject: [PATCH 003/394] PEP-93: Accept closes a PR whose commits are already in main instead of failing with 405 Co-Authored-By: Claude Opus 5.5 --- .../pep-93-empty-pr-accept/proposal.md | 13 ++++++++++++ .../specs/delivery-pipeline/spec.md | 8 +++++++ .../changes/pep-93-empty-pr-accept/tasks.md | 3 +++ packages/core/src/gitea.ts | 10 +++++++++ packages/runner/src/ci-feedback.ts | 21 ++++++++++++++++--- packages/testkit/src/mock-gitea.ts | 15 +++++++++++++ packages/testkit/test/ci-feedback.test.ts | 17 ++++++++++++++- 7 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 openspec/changes/pep-93-empty-pr-accept/proposal.md create mode 100644 openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md create mode 100644 openspec/changes/pep-93-empty-pr-accept/tasks.md diff --git a/openspec/changes/pep-93-empty-pr-accept/proposal.md b/openspec/changes/pep-93-empty-pr-accept/proposal.md new file mode 100644 index 00000000..34e0149c --- /dev/null +++ b/openspec/changes/pep-93-empty-pr-accept/proposal.md @@ -0,0 +1,13 @@ +# Proposal: PEP-93 — «Принять» на пустом PR + +## Why +FRTVL-1: ветка FRTVL-2 выросла из ветки FRTVL-1, PR №2 смержили первым — он унёс в `main` все +коммиты FRTVL-1. PR №1 остался открытым и пустым; Gitea на merge отвечает +`405 Please try again later`, и «Принять» показывал PM эту ошибку, стори застревала в ревью. + +## What Changes +- `GiteaClient.commitsAhead` (compare base...head) и `closePullRequest`. +- `mergeOrCloseEmpty` (runner/ci-feedback.ts) в «Принять» (`mergeTaskPr`) и автомерже + (`autoMergeTask`): если в PR нечего мержить — комментарий «уже в main» и закрытие PR, + стори принимается; иначе обычный мерж. +- `mock-gitea`: compare, PATCH PR, 405 на пустой мерж (как настоящая Gitea). diff --git a/openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md b/openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..19ea1a47 --- /dev/null +++ b/openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: Приёмка PR, уже вошедшего в основную ветку +«Принять» и автомерж SHALL принимать стори, чьи коммиты уже в основной ветке (вошли с другим PR), закрывая её пустой PR с пояснением вместо мержа. + +#### Scenario: Ветка следующей стори унесла коммиты +- **WHEN** PM жмёт «Принять» у стори, в PR которой нет коммитов сверх основной ветки +- **THEN** PR закрывается с комментарием «уже в main», стори переходит в «Готово», ошибки Gitea PM не видит diff --git a/openspec/changes/pep-93-empty-pr-accept/tasks.md b/openspec/changes/pep-93-empty-pr-accept/tasks.md new file mode 100644 index 00000000..d7ec0457 --- /dev/null +++ b/openspec/changes/pep-93-empty-pr-accept/tasks.md @@ -0,0 +1,3 @@ +- [x] 1.1 `commitsAhead`, `closePullRequest` в GiteaClient +- [x] 1.2 `mergeOrCloseEmpty` в `mergeTaskPr` и `autoMergeTask` +- [x] 1.3 mock-gitea: compare, PATCH, 405 на пустой PR; тест в ci-feedback.test.ts diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index a362dff5..6afff4b7 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -264,6 +264,16 @@ export class GiteaClient { return this.request("POST", `${this.repoPath(owner, repo)}/pulls/${n}/merge`, { Do: "merge", head_commit_id: sha, delete_branch_after_merge: true }); } + /** Commits `head` has that `base` hasn't (0: nothing to merge — already in base). */ + async commitsAhead(owner: string, repo: string, base: string, head: string): Promise { + const r = await this.request<{ total_commits?: number; commits?: unknown[] }>("GET", `${this.repoPath(owner, repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`); + return r.total_commits ?? r.commits?.length ?? 0; + } + + closePullRequest(owner: string, repo: string, n: number) { + return this.request("PATCH", `${this.repoPath(owner, repo)}/pulls/${n}`, { state: "closed" }); + } + combinedStatus(owner: string, repo: string, ref: string) { return this.request("GET", `${this.repoPath(owner, repo)}/commits/${encodeURIComponent(ref)}/status`); } diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 1a02cb45..6abdff00 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -229,8 +229,23 @@ export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<" if (!gate.pull) return "no_pr"; if (gate.pull.merged) return "already"; if (!gate.ok) throw new PeppaError(`Мерж не выполнен: ${gate.reason}`); - await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); - return "merged"; + return (await mergeOrCloseEmpty(ref, gate.pull, gitea)) ? "merged" : "already"; +} + +/** + * PEP-93: a PR whose commits are all in the base already (a later story's branch grew from this + * one and was merged first) can't be merged — Gitea answers 405 «Please try again later». Then + * the work is in main: close the PR with a note instead. True when merged, false when closed. + */ +export async function mergeOrCloseEmpty(ref: TaskRef, pull: { number: number; head: { sha: string }; base: { ref: string } }, gitea: GiteaClient): Promise { + const { giteaOwner: owner, giteaRepo: repo } = ref.project; + if ((await gitea.commitsAhead(owner, repo, pull.base.ref, pull.head.sha)) === 0) { + await gitea.commentIssue(owner, repo, pull.number, `Все коммиты этого PR уже в \`${pull.base.ref}\` (вошли с другим PR) — закрываю без мержа. ${ref.key} принята.`).catch(() => {}); + await gitea.closePullRequest(owner, repo, pull.number); + return false; + } + await gitea.mergePullRequest(owner, repo, pull.number, pull.head.sha); + return true; } /** @@ -251,6 +266,6 @@ export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = g }); return { merged: false, reason: "изменение конвейера требует ревью PM" }; } - await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); + await mergeOrCloseEmpty(ref, gate.pull, gitea); return { merged: true }; } diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 50f5a427..5127db9a 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -257,6 +257,10 @@ export class MockGitea { return { state, sha, statuses }; } + private ahead(r: MockRepo, base: string, head: string): number { + return Number(execFileSync("git", ["--git-dir", r.path, "rev-list", "--count", `${base}..${head}`], { encoding: "utf8" }).trim()); + } + private merge(r: MockRepo, p: MockPull) { const g = (...a: string[]) => execFileSync("git", ["--git-dir", r.path, ...a], { encoding: "utf8" }).trim(); const head = g("rev-parse", p.head); @@ -436,6 +440,11 @@ export class MockGitea { const p = r.pulls.find((x) => x.number === Number(m![1])); if (!p) return { status: 404, body: { message: "pull not found" } }; if (method === "GET" && !m[2]) return { status: 200, body: this.pullJson(r, p) }; + if (method === "PATCH" && !m[2]) { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + if (body.state === "closed" || body.state === "open") p.state = body.state; + return { status: 201, body: this.pullJson(r, p) }; + } if (method === "GET" && m[2] === "/files") { const out = execFileSync("git", ["--git-dir", r.path, "diff", "--name-only", `${p.base}...${p.head}`], { encoding: "utf8" }).trim(); return { status: 200, body: out ? out.split("\n").map((filename) => ({ filename })) : [] }; @@ -445,6 +454,8 @@ export class MockGitea { if (p.merged) return { status: 405, body: { message: "already merged" } }; if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } }; if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } }; + // Like Gitea: a PR with nothing to merge (head already in base) is refused. + if (this.ahead(r, p.base, p.head) === 0) return { status: 405, body: { message: "Please try again later" } }; this.merge(r, p); return { status: 200 }; } @@ -454,6 +465,10 @@ export class MockGitea { this.setStatus(r.owner, r.name, m[1]!, String(body.context), String(body.state), { target_url: body.target_url as string, description: body.description as string }); return { status: 201, body: {} }; } + if (method === "GET" && (m = sub.match(/^compare\/(.+)\.\.\.(.+)$/))) { + const n = this.ahead(r, decodeURIComponent(m[1]!), decodeURIComponent(m[2]!)); + return { status: 200, body: { total_commits: n, commits: [], files: [] } }; + } if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) }; if (method === "GET" && sub === "branches") { const out = execFileSync("git", ["--git-dir", r.path, "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(authorname)%09%(committerdate:iso-strict)%09%(contents:subject)", "refs/heads"], { encoding: "utf8" }).trim(); diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts index 398e189f..2163d923 100644 --- a/packages/testkit/test/ci-feedback.test.ts +++ b/packages/testkit/test/ci-feedback.test.ts @@ -2,7 +2,7 @@ // агенту», «Гейт ревью и мержа», «Изменение конвейера требует ревью» — one test per scenario, // against mock Gitea (commit statuses, PRs, webhooks) and mock-claude runners. import assert from "node:assert/strict"; -import { execFile } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { createHmac } from "node:crypto"; import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; @@ -222,6 +222,21 @@ describe("Гейт ревью и мержа", () => { assert.equal((await t.ref()).task.status, "done"); }); + test("PEP-93: PR already in main (a later story's branch grew from it and was merged) — closed with a note, story done", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success"); + const q = await toReview(t); + // The next story's PR carried this branch's commits into main first. + const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo); + execFileSync("git", ["--git-dir", r.path, "update-ref", "refs/heads/main", sha]); + await runner.acceptTask(db, q.id, "web"); + const pr = r.pulls[0]!; + assert.equal(pr.merged, false); + assert.equal(pr.state, "closed"); + assert.equal((await t.ref()).task.status, "done"); + }); + test("review gate: the agent can't move a task to review with red or running checks", async () => { const t = await ciTask({ checks: CHECKS }); const sha = t.push(); -- 2.45.2 From 664054c217011d23cf3238700393cc08810e53ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 13:56:25 +0500 Subject: [PATCH 004/394] =?UTF-8?q?PEP-94:=20the=20PM=20is=20a=20product?= =?UTF-8?q?=20person=20=E2=80=94=20no=20technical=20questions,=20no=20wait?= =?UTF-8?q?ing=20for=20approval;=20Proposal=20is=20=C2=AB=D0=9F=D0=BB?= =?UTF-8?q?=D0=B0=D0=BD=C2=BB=20in=20the=20UI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/web/app/(app)/help/page.tsx | 8 +-- apps/web/app/(app)/t/[key]/tabs.tsx | 21 +++--- apps/web/components/Autonomy.tsx | 6 +- apps/web/components/Board.tsx | 2 +- apps/web/components/cards.tsx | 2 +- apps/web/lib/status.ts | 2 +- .../pep-94-no-tech-questions/proposal.md | 18 +++++ .../specs/project-autonomy/spec.md | 16 +++++ .../changes/pep-94-no-tech-questions/tasks.md | 7 ++ packages/core/src/autonomy.ts | 8 ++- packages/core/src/chats.ts | 2 +- packages/core/src/intake.ts | 4 +- packages/core/src/palette.ts | 2 +- packages/mcp/src/agent.ts | 14 ++-- packages/mcp/src/format.ts | 4 +- packages/runner/src/intake.ts | 11 +-- packages/testkit/test/bot.test.ts | 4 ++ packages/testkit/test/cjm.test.ts | 4 ++ packages/testkit/test/intake.test.ts | 72 +++++++------------ packages/testkit/test/subscriptions.test.ts | 6 +- template/RULES.md | 47 ++++++------ 22 files changed, 151 insertions(+), 110 deletions(-) create mode 100644 openspec/changes/pep-94-no-tech-questions/proposal.md create mode 100644 openspec/changes/pep-94-no-tech-questions/specs/project-autonomy/spec.md create mode 100644 openspec/changes/pep-94-no-tech-questions/tasks.md diff --git a/AGENTS.md b/AGENTS.md index b3c2855f..7d4f9aea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ - **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts` - **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx` - **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning` +- **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние) - **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`) - **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула - **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:` {enabled, waitMin, since}, состояние `intake.task:`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`) diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 28a9e66c..2e9bd509 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -24,7 +24,7 @@ const TOOLS: Array<[string, string]> = [ ["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"], ["get_usage", "лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали"], ["get_metrics", "метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"], - ["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)"], + ["get_project_settings / update_project_settings", "автономность проекта: уровень manual / assisted / self / auto (новые проекты — auto) и отдельные настройки — кто берёт стори, одобрение плана, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)"], ["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"], ]; @@ -34,7 +34,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [ { title: "Создать стори в эпике", say: "В этом эпике создай стори «Форма оплаты» с условиями готовности: …", how: "create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент" }, { title: "Поправить стори", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" }, { title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" }, - { title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит стори в Ревью" }, + { title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент составляет план, реализует, открывает PR и переводит стори в Ревью" }, { title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" }, { title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" }, { title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" }, @@ -68,7 +68,7 @@ export default async function Help() {
  • Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же).
  • Зависимости и планировщик — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой.
  • Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ?).
  • -
  • Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
  • +
  • Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: составляет план стори (OpenSpec), реализует, открывает PR и отдаёт стори на ревью.
  • Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
  • Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
  • Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
  • @@ -130,7 +130,7 @@ export default async function Help() { С подсказками: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками «Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. Автомат: Пеппа сама берёт следующую стори из бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент - сам делает rebase. Настройки можно комбинировать: одобрять каждый proposal, мержить сам, но закрывать вручную или «само через N + сам делает rebase. Настройки можно комбинировать: одобрять план каждой стори, мержить сам, но закрывать вручную или «само через N часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main.

    diff --git a/apps/web/app/(app)/t/[key]/tabs.tsx b/apps/web/app/(app)/t/[key]/tabs.tsx index 54758365..81690034 100644 --- a/apps/web/app/(app)/t/[key]/tabs.tsx +++ b/apps/web/app/(app)/t/[key]/tabs.tsx @@ -15,23 +15,24 @@ import { cn } from "@/lib/utils"; import { acceptStoryAction, commentStoryAction } from "../../actions"; export const STORY_TABS = [ - { id: "proposal", label: "Proposal" }, - { id: "design", label: "Design" }, - { id: "specs", label: "Specs" }, - { id: "tasks", label: "Tasks" }, - { id: "comments", label: "Comments" }, - { id: "tests", label: "Tests" }, - { id: "merge", label: "Merge request" }, - { id: "activity", label: "Activity" }, + // PEP-94: names a product manager understands (ids stay — links keep working). + { id: "proposal", label: "План" }, + { id: "design", label: "Как устроено" }, + { id: "specs", label: "Требования" }, + { id: "tasks", label: "Шаги" }, + { id: "comments", label: "Обсуждение" }, + { id: "tests", label: "Проверки" }, + { id: "merge", label: "Результат" }, + { id: "activity", label: "История" }, ] as const; export type StoryTab = (typeof STORY_TABS)[number]["id"]; -const noChange = (change: string | null) => {change ? `Change ${change} не найден в рабочей копии.` : "Change ещё не создан — агент заведёт его на этапе proposal."}; +const noChange = (change: string | null) => {change ? `Change ${change} не найден в рабочей копии.` : "План ещё не написан — агент составит его, когда возьмёт стори."}; export function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) { if (!change) return noChange(changeId); const text = change[file]; - if (!text) return {file === "design" ? "design.md в этом change нет — значит, решений сверх proposal не понадобилось." : "proposal.md ещё не написан."}; + if (!text) return {file === "design" ? "Отдельных решений об устройстве не понадобилось — всё есть в плане." : "План ещё не написан."}; return (
    diff --git a/apps/web/components/Autonomy.tsx b/apps/web/components/Autonomy.tsx index f154da80..acf823ce 100644 --- a/apps/web/components/Autonomy.tsx +++ b/apps/web/components/Autonomy.tsx @@ -42,10 +42,10 @@ export function AutonomyPanel({ projectId, settings, back }: { projectId: number