From 3159e888d2129b10bea9d68965b004db00a32c35 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:33:27 +0500 Subject: [PATCH 001/394] PEP-90: sign in and register with Google (OAuth code + PKCE), link with eGov in Settings Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 4 + .peppa/memory.md | 1 + AGENTS.md | 1 + apps/web/app/(app)/actions.ts | 8 + apps/web/app/(app)/help/page.tsx | 2 +- apps/web/app/(app)/settings/page.tsx | 39 +- apps/web/app/(app)/users/page.tsx | 4 +- apps/web/app/auth/google/callback/route.ts | 32 + apps/web/app/auth/google/start/route.ts | 25 + apps/web/app/login/page.tsx | 7 +- apps/web/components/GoogleSignIn.tsx | 20 + apps/web/lib/auth.ts | 4 + .../2026-11-15-pep-90-google-login/design.md | 8 + .../proposal.md | 14 + .../specs/web-auth/spec.md | 43 + .../2026-11-15-pep-90-google-login/tasks.md | 11 + openspec/specs/web-auth/spec.md | 40 + packages/core/src/google.ts | 173 + packages/core/src/index.ts | 1 + .../db/migrations/0017_lowly_ghost_rider.sql | 4 + .../db/migrations/meta/0017_snapshot.json | 4148 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 4 + packages/shared/src/env.ts | 5 + packages/testkit/bin/mock-google | 3 + packages/testkit/src/mock-google.ts | 89 + packages/testkit/test/google.test.ts | 139 + 27 files changed, 4826 insertions(+), 10 deletions(-) create mode 100644 apps/web/app/auth/google/callback/route.ts create mode 100644 apps/web/app/auth/google/start/route.ts create mode 100644 apps/web/components/GoogleSignIn.tsx create mode 100644 openspec/changes/archive/2026-11-15-pep-90-google-login/design.md create mode 100644 openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md create mode 100644 openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md create mode 100644 openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md create mode 100644 packages/core/src/google.ts create mode 100644 packages/db/migrations/0017_lowly_ghost_rider.sql create mode 100644 packages/db/migrations/meta/0017_snapshot.json create mode 100755 packages/testkit/bin/mock-google create mode 100644 packages/testkit/src/mock-google.ts create mode 100644 packages/testkit/test/google.test.ts diff --git a/.env.example b/.env.example index 18bb27b2..4c9ecfaf 100644 --- a/.env.example +++ b/.env.example @@ -28,3 +28,7 @@ PEPPA_ROOT=/Users/telecom/Dev/Peppa # Gitea OAuth2 app for web login (scripts/create-oauth-app.sh) GITEA_OAUTH_CLIENT_ID= GITEA_OAUTH_CLIENT_SECRET= + +# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI /auth/google/callback +# GOOGLE_CLIENT_ID= +# GOOGLE_CLIENT_SECRET= diff --git a/.peppa/memory.md b/.peppa/memory.md index 4c94ef16..0d84414d 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -12,3 +12,4 @@ - Репозитории платформы — в организации Gitea `peppa` (PEP-4): `peppa/peppa`, `peppa/template`; старые адреса `peppa-bot/…` живут редиректом — не создавать `peppa-bot/peppa|template` заново. Проект переносит `peppa project transfer `. - Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents. - tmux-сервер по умолчанию: newSession чистит его глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69; при PEPPA_TMUX_SOCKET не трогает); агенту нужное — только через new-session -e. +- Вход через Google (PEP-90): идентичность — google_sub, по почте учётки не склеиваем; без GOOGLE_CLIENT_ID/SECRET кнопки нет; в тестах эндпоинты подменяет GOOGLE_OAUTH_BASE (mock-google). `pnpm typecheck` в apps/web может падать на устаревших .next/types (auth/callback, auth/start) — не от правок. diff --git a/AGENTS.md b/AGENTS.md index 6600b08f..14003a0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,7 @@ - **Ошибки из прода (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` - **Вход через 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` +- **Вход через Google (PEP-90)**: `core/google.ts` — OAuth code + PKCE; идентичность `users.google_sub` (+ `google_email`, миграция 0017), по почте учётки не склеиваются; поток `settings` `google.flow:` (10 мин, одноразовый) + cookie `peppa_google` (state, привязка к браузеру; путь `/auth/google`); регистрация как у eGov (`gitea_id < 0`, логин из почты); `/auth/google/start` (POST-форма, `purpose=login|link`) и `/auth/google/callback`; включено при `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` (`googleEnabled`), `GOOGLE_OAUTH_BASE` подменяет эндпоинты моком `mock-google`; «Настройки → Google» (привязать/отвязать, отвязка единственного способа входа запрещена). Нужно от PM: OAuth-клиент Google Cloud, redirect URI `/auth/google/callback` - **Локальные пользователи (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 или сгенерированный) - **Секреты (PEP-54/19)**: секреты проекта — таблица `project_secrets` (имя env, `value_enc` = `encrypt`, кто менял, `last_used_at`), `core/secrets.ts` (`setProjectSecret`/`deleteProjectSecret` через `projectForUser`, имена `^[A-Z][A-Z0-9_]*$` без зарезервированных `PATH`/`PEPPA_*`/`CLAUDE_*`…, `projectSecretEnv`, `projectSecretMasker`); веб «⋯ Настройки проекта → Секреты» (значение только на запись). Раннер (`launch` в runner/sessions.ts) пишет `secrets.env` (0600) в каталог поколения, `launch.sh` его читает и сразу удаляет — значений нет в argv tmux; событие `secrets_issued {names}`. Маскировка `••••` — `TerminalFeed` (`mask`, из `terminalSse`) и `recordStep`. MCP `list_secrets` (агент — проект своей сессии; PM — доступный проект), только имена. Ревизия (core/secrets-audit.ts `secretsAudit`): секреты платформы `PLATFORM_SECRETS` (задан ли, возраст от `settings` `secrets.rotated:`, кто использует, шаги ротации), шифрование по колонкам, MCP-токены по клиентам, подписки, секреты проектов — `/secrets` (суперадмин) и `peppa secrets audit|new-key|reencrypt|rotated|revoke-client|check-gitea|list`. Ротация `PEPPA_SECRET` двумя ключами: `PEPPA_SECRET_PREVIOUS` принимается для `decrypt`/`verify`/хэшей OAuth (`hashTokenCandidates`)/подписей вебхуков, пишется только текущим; `reencryptAll` переводит все `*_enc`. Новые зашифрованные колонки — добавлять в `encryptedColumns` (secrets-audit.ts), иначе ротация их потеряет - **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. **Ротация (PEP-39)**: лимит (StopFailure/баннер) помечает подписку «лимит до …» (`markSubscriptionLimited`), `recordLimit` при свободной подписке того же провайдера в пуле (`rotationCandidate`: пул проекта, иначе пулы текущей подписки; наименее занятая) ставит `sessions.rotate_reason=limit` вместо пинга PM, вачдог (runner/rotation.ts `tryRotate`/`rotateSession`) убивает tmux и `resumeSession` на новой подписке — Claude/OpenCode тот же разговор, Codex заново (`conversation_id` сбрасывается, история в `CODEX_HOME` аккаунта не переносится); событие `subscription_switched` + сообщение в Telegram (`sendProjectMessage`). Порог: баннер «N% of your … limit» (≥ `PEPPA_ROTATE_THRESHOLD_PCT`, 85) → `rotate_reason=threshold`, Stop-хук не подталкивает, после хода — на подписку без сессий. Свободных нет — ждёт сброса (PEP-56); освободилась раньше — переключит. Предел `PEPPA_ROTATE_MAX_PER_HOUR` (3), выключение `PEPPA_ROTATE=off`. Справедливость: проект с ≥ `PEPPA_POOL_PROJECT_MAX` (2) подписками пула не получает свободную, пока сессия другого проекта ждёт сброса на этом пуле (`poolRestricted`). Мок: `limit.credential` в сценарии — лимит только на входе с этой подстрокой, `{warn: N}` — баннер порога. Провайдер OpenCode (`providers.ts`): `opencode --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — » и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode` diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 29671a88..65e9ed3b 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -10,6 +10,7 @@ import { getQuestion, getSession, PeppaError, + unlinkGoogle, projectForUser, resolveTask, revokeApp, @@ -428,6 +429,13 @@ export async function pairTelegram(f: FormData) { }); } +export async function unlinkGoogleAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + await unlinkGoogle(db, user.id); + }); +} + export async function unpairTelegramAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index fd64b22f..28a9e66c 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -75,7 +75,7 @@ export default async function Help() {
  • Telegram — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда /newbot), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.
  • Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.
  • Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
  • -
  • Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot.
  • +
  • Вход — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал GOOGLE_CLIENT_ID/SECRET); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, aigerim.ivanova). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot.
  • Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
  • Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.
  • Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.
  • diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index f57ba0ce..70d86853 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,15 +1,16 @@ -import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core"; +import { googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core"; import { Hidden } from "@/components/cards"; import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { Input, Label } from "@/components/ui/input"; +import { GoogleSignIn } from "@/components/GoogleSignIn"; import { EgovSign } from "@/components/EgovSign"; import { OwnBotSteps } from "@/components/OwnBotSteps"; import { Workspace } from "@/components/Workspace"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions"; +import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions"; import { PushNotifications } from "@/components/PushNotifications"; import { TimezoneField } from "@/components/TimezoneField"; @@ -28,9 +29,9 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?: ); } -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string; bot?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) { const user = await requireUser(); - const { error, egov, notify, bot } = await searchParams; + const { error, egov, google, notify, bot } = await searchParams; const hasBot = !!user.telegramBotUsername; const local = isLocalUser(user); const superadmin = await isSuperadmin(db, user); @@ -50,13 +51,13 @@ export default async function Settings({ searchParams }: { searchParams: Promise

    Логин {user.login} - {user.name ? <> · {user.name} : null}. Вход в Пеппу — только через eGov QR + {user.name ? <> · {user.name} : null}. Вход в Пеппу — через eGov QR или Google {user.egovIin ? ( <> , ИИН {maskIin(user.egovIin)}. ) : ( - <>. ИИН ещё не привязан — привяжите его ниже, иначе после выхода вы не сможете войти. + <>. ИИН ещё не привязан{user.googleSub ? "." : " — привяжите его ниже или Google, иначе после выхода вы не сможете войти."} )}

    {local && ( @@ -113,6 +114,32 @@ export default async function Settings({ searchParams }: { searchParams: Promise )} {user.egovIin && egov === "linked" && eGov привязан — теперь можно входить по QR} + {(googleEnabled() || user.googleSub) && ( +
    + {google === "linked" && Google привязан — теперь можно входить через него} + {user.googleSub ? ( + + + + + } + > + {user.googleEmail}. Войти через Google можно в ту же учётку. + + ) : ( + +

    Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.

    +
    + +
    +
    + )} +
    + )} +
    {bot === "connected" && Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.} {user.telegramChatId ? ( diff --git a/apps/web/app/(app)/users/page.tsx b/apps/web/app/(app)/users/page.tsx index 93041a8a..73f40400 100644 --- a/apps/web/app/(app)/users/page.tsx +++ b/apps/web/app/(app)/users/page.tsx @@ -39,7 +39,9 @@ export default async function Users({ searchParams }: { searchParams: Promise<{ {!local && Gitea} {admins.has(u.login.toLowerCase()) && суперадмин} {u.disabledAt && отключён} - {u.egovIin ? eGov {maskIin(u.egovIin)} : без eGov — не войдёт} + {u.egovIin && eGov {maskIin(u.egovIin)}} + {u.googleSub && Google {u.googleEmail}} + {!u.egovIin && !u.googleSub && !u.passwordHash && без eGov и Google — не войдёт} {u.lastLoginAt ? `вход ${ago(u.lastLoginAt)}` : "ещё не входил"}
    diff --git a/apps/web/app/auth/google/callback/route.ts b/apps/web/app/auth/google/callback/route.ts new file mode 100644 index 00000000..7c090202 --- /dev/null +++ b/apps/web/app/auth/google/callback/route.ts @@ -0,0 +1,32 @@ +import { completeGoogleFlow, isUserAllowed, PeppaError } from "@peppa/core"; +import { cookies } from "next/headers"; +import { NextResponse, type NextRequest } from "next/server"; +import { GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext, sessionCookie } from "@/lib/auth"; +import { db } from "@/lib/db"; + +/** Google redirects here (PEP-90): checks state against the browser's cookie, then logs in, registers or links. */ +export async function GET(req: NextRequest) { + const origin = await publicOrigin(); + const jar = await cookies(); + const cookieState = jar.get(GOOGLE_COOKIE)?.value ?? ""; + const next = safeNext(jar.get(`${GOOGLE_COOKIE}_next`)?.value); + const q = req.nextUrl.searchParams; + const done = (path: string, error?: string) => { + const res = NextResponse.redirect(`${origin}${path}${error ? `${path.includes("?") ? "&" : "?"}error=${encodeURIComponent(error)}` : ""}`, 303); + res.cookies.set(GOOGLE_COOKIE, "", googleCookieOptions(0)); + res.cookies.set(`${GOOGLE_COOKIE}_next`, "", googleCookieOptions(0)); + return res; + }; + if (q.get("error")) return done("/login", q.get("error") === "access_denied" ? "Вход через Google отменён" : "Google отказал во входе"); + try { + const r = await completeGoogleFlow(db, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState }); + if (r.purpose === "link") return done("/settings?google=linked"); + if (!(await isUserAllowed(db, r.user))) return done("/login", "Учётка отключена — обратитесь к администратору"); + const res = done(next); + const c = sessionCookie(r.user.id); + res.cookies.set(c.name, c.value, c.options); + return res; + } catch (e) { + return done("/login", e instanceof PeppaError ? e.message : "Не удалось войти через Google"); + } +} diff --git a/apps/web/app/auth/google/start/route.ts b/apps/web/app/auth/google/start/route.ts new file mode 100644 index 00000000..934db849 --- /dev/null +++ b/apps/web/app/auth/google/start/route.ts @@ -0,0 +1,25 @@ +import { PeppaError, startGoogleFlow } from "@peppa/core"; +import { NextResponse, type NextRequest } from "next/server"; +import { currentUser, GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext } from "@/lib/auth"; +import { db } from "@/lib/db"; + +/** Starts a Google login (PEP-90) or, from Settings (`purpose=link`, needs a session), linking. POST form → 303 to Google. */ +export async function POST(req: NextRequest) { + const origin = await publicOrigin(); + const form = await req.formData().catch(() => null); + const purpose = form?.get("purpose") === "link" ? "link" : "login"; + const next = safeNext(String(form?.get("next") ?? "")); + const fail = (msg: string) => NextResponse.redirect(`${origin}${purpose === "link" ? "/settings" : "/login"}?error=${encodeURIComponent(msg)}`, 303); + try { + const user = purpose === "link" ? await currentUser() : null; + if (purpose === "link" && !user) return fail("Войдите, чтобы привязать Google"); + const flow = await startGoogleFlow(db, purpose, `${origin}/auth/google/callback`, user?.id ?? null); + const res = NextResponse.redirect(flow.url, 303); + res.cookies.set(GOOGLE_COOKIE, flow.state, googleCookieOptions(600)); + // Where to go after login: a separate cookie value would leak into the URL, so keep it beside the state. + res.cookies.set(`${GOOGLE_COOKIE}_next`, next, googleCookieOptions(600)); + return res; + } catch (e) { + return fail(e instanceof PeppaError ? e.message : "Не удалось начать вход через Google"); + } +} diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 9020612e..a904a1c7 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -1,7 +1,9 @@ import { redirect } from "next/navigation"; import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react"; +import { googleEnabled } from "@peppa/core"; import { currentUser, safeNext } from "@/lib/auth"; import { Brand } from "@/components/Brand"; +import { GoogleSignIn } from "@/components/GoogleSignIn"; import { Flash } from "@/components/common"; import { EgovSign } from "@/components/EgovSign"; import { Footer } from "@/components/Footer"; @@ -16,7 +18,7 @@ const WHY = [ ]; const STEPS = [ - { title: "Войдите с ноутбука", text: "Через eGov QR — учётка создаётся сама, пароль не нужен." }, + { title: "Войдите с ноутбука", text: "Через eGov QR или Google — учётка создаётся сама, пароль не нужен." }, { title: "Привяжите Telegram-бота", text: "Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова." }, { title: "Создайте проект и подключите подписку", text: "Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута." }, { title: "Опишите задачу словами", text: "«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам." }, @@ -48,9 +50,10 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ diff --git a/apps/web/components/GoogleSignIn.tsx b/apps/web/components/GoogleSignIn.tsx new file mode 100644 index 00000000..0418446c --- /dev/null +++ b/apps/web/components/GoogleSignIn.tsx @@ -0,0 +1,20 @@ +import { Button } from "@/components/ui/button"; + +/** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */ +export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) { + return ( +
    + + {next && } + +
    + ); +} diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index 0dfe4e3b..b28265da 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -54,6 +54,10 @@ export function sessionCookie(uid: number) { export const egovCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/egov", maxAge: maxAgeSec }); +/** Google OAuth state (PEP-90): binds the callback to the browser that started the flow. */ +export const GOOGLE_COOKIE = "peppa_google"; +export const googleCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/google", maxAge: maxAgeSec }); + const isHttps = () => loadEnv().PEPPA_WEB_URL.startsWith("https://"); /** diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/design.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/design.md new file mode 100644 index 00000000..af7055df --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/design.md @@ -0,0 +1,8 @@ +# Design: PEP-90 + +- Новые колонки `users.google_sub` (unique), `users.google_email`, `users.google_linked_at` (миграция 0017). Идентичность — только `sub`; почта показывается и даёт логин, но по ней учётки **не склеиваются** (иначе чужая почта угоняет учётку). +- `core/google.ts`: `startGoogleFlow` (state и PKCE verifier, поток в `settings` `google.flow:`, 10 мин; state ещё и в httpOnly cookie `peppa_google` — привязка к браузеру), `completeGoogleFlow` (поток удаляется до обмена: одноразовый; сверка cookie-state; обмен code на токены; профиль через `userinfo`; требуем `email_verified`). Токены не храним. +- Эндпоинты Google берутся из `GOOGLE_OAUTH_BASE` (по умолчанию настоящие `accounts.google.com`/`oauth2.googleapis.com`), чтобы подменять моком. Включено, только если заданы `GOOGLE_CLIENT_ID` и `GOOGLE_CLIENT_SECRET` (`googleEnabled`). +- Регистрация: логин из локальной части почты (латиница/цифры, дубль `-2`), `gitea_id < 0`, без пароля; подписки и `mayUseMachineLogin` работают как у eGov (по `gitea_id < 0`). +- Привязка (`purpose: link`) — только вошедшим; Google-аккаунт, занятый другой учёткой, отклоняется. Отвязать нельзя, если это единственный способ входа. +- Маршруты: `/auth/google/start` (редирект на Google), `/auth/google/callback`. diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md new file mode 100644 index 00000000..954d699e --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md @@ -0,0 +1,14 @@ +# PEP-90: Вход и регистрация через Google-почту + +## Зачем +Сейчас в Пеппу входят только через eGov QR (PEP-71). Нужен и обычный вход «через Google»: не у всех под рукой eGov Mobile. + +## Что меняется +- На странице входа рядом с eGov — кнопка «Войти через Google» (OAuth 2.0 authorization code + PKCE). +- Первый вход создаёт учётку как у eGov: без Gitea и пароля, логин из адреса почты; следующий находит её по Google-аккаунту (`sub`). +- В «Настройках» можно привязать Google к учётке eGov, а eGov — к учётке Google (оба способа ведут в одну учётку). +- Отключённый пользователь войти не может; state/code одноразовые и привязаны к браузеру. +- Мок Google OAuth (`mock-google`) для тестов и работы до выдачи OAuth-клиента. + +## Нужно от PM +OAuth-клиент в Google Cloud (Web application): redirect URI `https://peppa.telecom.quest/auth/google/callback`, `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` в `.env`. Без них кнопки Google нет. diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md new file mode 100644 index 00000000..e84f640e --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md @@ -0,0 +1,43 @@ +# Spec Delta: web-auth + +## ADDED Requirements + +### Requirement: Вход через Google +Страница входа SHALL предлагать «Войти через Google», если на платформе настроен OAuth-клиент Google. Первый вход SHALL создавать учётку без Gitea и пароля, последующие — находить её по идентификатору Google-аккаунта. Отключённый пользователь SHALL не входить. Ответ Google SHALL приниматься только один раз и только в браузере, начавшем вход. + +#### Scenario: Первый вход через Google +- **GIVEN** Google подтвердил почту «anna.petrova@example.com» аккаунта с идентификатором «g-1001», учётки с ним нет +- **WHEN** пользователь возвращается с Google с верными state и code +- **THEN** создаётся учётка с логином «anna.petrova» без пароля и Gitea +- **AND** открывается сессия веба + +#### Scenario: Повторный вход +- **GIVEN** учётка «anna.petrova» создана входом через Google «g-1001» +- **WHEN** тот же Google-аккаунт входит снова +- **THEN** открывается сессия той же учётки, новая не создаётся + +#### Scenario: Отключённый пользователь +- **GIVEN** учётка «anna.petrova» отключена администратором +- **WHEN** она входит через Google +- **THEN** вход отклонён и сессия не открывается + +#### Scenario: Подделанный или повторный ответ +- **WHEN** в callback приходит чужой или повторно использованный state, либо state без cookie начавшего браузера +- **THEN** вход отклонён без обращения к Google и без создания учётки + +#### Scenario: Непотверждённая почта +- **WHEN** Google отвечает `email_verified: false` +- **THEN** вход отклонён + +### Requirement: Связка eGov и Google +Вошедший пользователь SHALL привязывать Google к учётке eGov и eGov к учётке Google в «Настройках»; один Google-аккаунт — одна учётка. + +#### Scenario: Привязка Google к учётке eGov +- **GIVEN** пользователь вошёл через eGov +- **WHEN** он привязывает Google-аккаунт «g-2002» в «Настройках» +- **THEN** вход через Google ведёт в ту же учётку + +#### Scenario: Google-аккаунт занят +- **GIVEN** Google-аккаунт «g-1001» привязан к учётке «anna.petrova» +- **WHEN** другой пользователь пытается привязать «g-1001» +- **THEN** привязка отклонена с сообщением, что аккаунт уже привязан diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md new file mode 100644 index 00000000..2c4fc289 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md @@ -0,0 +1,11 @@ +# Tasks: PEP-90 + +## 1. Данные и ядро +- [x] 1.1 Колонки `users.google_*`, миграция 0017, env `GOOGLE_CLIENT_ID/SECRET/OAUTH_BASE` +- [x] 1.2 `core/google.ts`: start/complete/link/unlink, регистрация, `googleEnabled` +- [x] 1.3 `mock-google` в testkit +## 2. Веб +- [x] 2.1 Маршруты `/auth/google/start|callback` +- [x] 2.2 Кнопка на странице входа; «Настройки» (привязать/отвязать Google, привязать eGov учётке Google); `/users` +## 3. Проверка +- [x] 3.1 e2e `google.test.ts`, typecheck, документация (`/help`, AGENTS.md) diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md index a81a41df..da673c6e 100644 --- a/openspec/specs/web-auth/spec.md +++ b/openspec/specs/web-auth/spec.md @@ -193,3 +193,43 @@ nonce, созданные сервером для этого потока; по #### Scenario: Посторонний - **WHEN** пользователь, не владелец и не суперадмин, пытается добавить участника в «PAY» - **THEN** действие отклонено + +### Requirement: Вход через Google +Страница входа SHALL предлагать «Войти через Google», если на платформе настроен OAuth-клиент Google. Первый вход SHALL создавать учётку без Gitea и пароля, последующие — находить её по идентификатору Google-аккаунта. Отключённый пользователь SHALL не входить. Ответ Google SHALL приниматься только один раз и только в браузере, начавшем вход. + +#### Scenario: Первый вход через Google +- **GIVEN** Google подтвердил почту «anna.petrova@example.com» аккаунта с идентификатором «g-1001», учётки с ним нет +- **WHEN** пользователь возвращается с Google с верными state и code +- **THEN** создаётся учётка с логином «anna.petrova» без пароля и Gitea +- **AND** открывается сессия веба + +#### Scenario: Повторный вход +- **GIVEN** учётка «anna.petrova» создана входом через Google «g-1001» +- **WHEN** тот же Google-аккаунт входит снова +- **THEN** открывается сессия той же учётки, новая не создаётся + +#### Scenario: Отключённый пользователь +- **GIVEN** учётка «anna.petrova» отключена администратором +- **WHEN** она входит через Google +- **THEN** вход отклонён и сессия не открывается + +#### Scenario: Подделанный или повторный ответ +- **WHEN** в callback приходит чужой или повторно использованный state, либо state без cookie начавшего браузера +- **THEN** вход отклонён без обращения к Google и без создания учётки + +#### Scenario: Непотверждённая почта +- **WHEN** Google отвечает `email_verified: false` +- **THEN** вход отклонён + +### Requirement: Связка eGov и Google +Вошедший пользователь SHALL привязывать Google к учётке eGov и eGov к учётке Google в «Настройках»; один Google-аккаунт — одна учётка. + +#### Scenario: Привязка Google к учётке eGov +- **GIVEN** пользователь вошёл через eGov +- **WHEN** он привязывает Google-аккаунт «g-2002» в «Настройках» +- **THEN** вход через Google ведёт в ту же учётку + +#### Scenario: Google-аккаунт занят +- **GIVEN** Google-аккаунт «g-1001» привязан к учётке «anna.petrova» +- **WHEN** другой пользователь пытается привязать «g-1001» +- **THEN** привязка отклонена с сообщением, что аккаунт уже привязан diff --git a/packages/core/src/google.ts b/packages/core/src/google.ts new file mode 100644 index 00000000..962aa1af --- /dev/null +++ b/packages/core/src/google.ts @@ -0,0 +1,173 @@ +// Google login (PEP-90): OAuth 2.0 authorization code + PKCE. Identity is the Google account's +// stable `sub`; the e-mail (must be verified) only names a new account and is shown in Settings — +// accounts are never merged by e-mail. State lives in `settings` (one-shot, 10 min) and in an +// httpOnly cookie of the starting browser, so a forged or replayed callback is refused before +// Google is contacted. Tokens are not stored. +import { createHash, randomBytes, randomInt } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { users, type Db } from "@peppa/db"; +import { loadEnv } from "@peppa/shared"; +import { hashToken } from "./crypto.ts"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; +import { getUser, type User } from "./users.ts"; + +export const GOOGLE_FLOW_TTL_MS = 10 * 60_000; +export type GooglePurpose = "login" | "link"; + +interface Flow { + purpose: GooglePurpose; + userId: number | null; + verifier: string; + redirectUri: string; + expiresAt: number; +} + +export interface GoogleIdentity { + sub: string; + email: string; + name: string | null; +} + +export type GoogleResult = + | { purpose: "login"; user: User; identity: GoogleIdentity; created: boolean } + | { purpose: "link"; user: User; identity: GoogleIdentity }; + +const flowKey = (state: string) => `google.flow:${hashToken(state)}`; + +export function googleEnabled(env = loadEnv()): boolean { + return !!env.GOOGLE_CLIENT_ID && !!env.GOOGLE_CLIENT_SECRET; +} + +function endpoints() { + const b = loadEnv().GOOGLE_OAUTH_BASE?.replace(/\/$/, ""); + return b + ? { auth: `${b}/auth`, token: `${b}/token`, userinfo: `${b}/userinfo` } + : { + auth: "https://accounts.google.com/o/oauth2/v2/auth", + token: "https://oauth2.googleapis.com/token", + userinfo: "https://openidconnect.googleapis.com/v1/userinfo", + }; +} + +export interface GoogleStart { + /** Where to send the browser. */ + url: string; + /** Kept by the browser in an httpOnly cookie; the callback must bring the same value back. */ + state: string; +} + +export async function startGoogleFlow(db: Db, purpose: GooglePurpose, redirectUri: string, userId: number | null = null): Promise { + const env = loadEnv(); + if (!googleEnabled(env)) throw new PeppaError("Вход через Google не настроен"); + if (purpose === "link" && !userId) throw new PeppaError("Привязать Google можно только после входа"); + const state = randomBytes(24).toString("base64url"); + const verifier = randomBytes(32).toString("base64url"); + await setSetting(db, flowKey(state), { purpose, userId, verifier, redirectUri, expiresAt: Date.now() + GOOGLE_FLOW_TTL_MS } satisfies Flow); + const q = new URLSearchParams({ + client_id: env.GOOGLE_CLIENT_ID!, + redirect_uri: redirectUri, + response_type: "code", + scope: "openid email profile", + state, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + prompt: "select_account", + }); + return { url: `${endpoints().auth}?${q}`, state }; +} + +async function post(url: string, body: URLSearchParams): Promise { + const res = await fetch(url, { method: "POST", body, headers: { "Content-Type": "application/x-www-form-urlencoded" }, signal: AbortSignal.timeout(15_000) }); + const json = (await res.json().catch(() => ({}))) as T & { error?: string }; + if (!res.ok) throw new PeppaError(`Google: ${json.error ?? `HTTP ${res.status}`}`); + return json; +} + +/** + * Finishes the flow (one-shot: removed before anything else, whatever happens). `cookieState` is the + * state the starting browser kept; it must equal the callback's `state`. + */ +export async function completeGoogleFlow(db: Db, input: { state: string; code: string; cookieState: string }): Promise { + const { state, code, cookieState } = input; + if (!state || !code || state !== cookieState) throw new PeppaError("Вход не удался — начните заново"); + const flow = await getSetting(db, flowKey(state)); + await deleteSetting(db, flowKey(state)); + if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError("Вход устарел — начните заново"); + const env = loadEnv(); + const ep = endpoints(); + const tok = await post<{ access_token?: string }>( + ep.token, + new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: flow.redirectUri, + client_id: env.GOOGLE_CLIENT_ID ?? "", + client_secret: env.GOOGLE_CLIENT_SECRET ?? "", + code_verifier: flow.verifier, + }), + ); + if (!tok.access_token) throw new PeppaError("Google не выдал токен"); + const res = await fetch(ep.userinfo, { headers: { Authorization: `Bearer ${tok.access_token}` }, signal: AbortSignal.timeout(15_000) }); + const p = (await res.json().catch(() => ({}))) as { sub?: string; email?: string; email_verified?: boolean; name?: string }; + if (!res.ok || !p.sub || !p.email) throw new PeppaError("Google не вернул профиль"); + if (p.email_verified !== true) throw new PeppaError("Почта в Google не подтверждена"); + const identity: GoogleIdentity = { sub: p.sub, email: p.email.toLowerCase(), name: p.name?.trim() || null }; + + if (flow.purpose === "link") { + const user = await linkGoogle(db, flow.userId!, identity); + return { purpose: "link", user, identity }; + } + const [found] = await db.select().from(users).where(eq(users.googleSub, identity.sub)); + const account = found ?? (await registerGoogleUser(db, identity)); + await db.update(users).set({ googleEmail: identity.email, lastLoginAt: new Date() }).where(eq(users.id, account.id)); + return { purpose: "login", user: (await getUser(db, account.id))!, identity, created: !found }; +} + +/** "Anna.Petrova+work@x.com" → "anna.petrova"; nothing usable → "user-". */ +export function googleLoginBase(identity: GoogleIdentity): string { + const local = identity.email.split("@")[0]!.split("+")[0]!.toLowerCase().replace(/[^a-z0-9._-]/g, ""); + const login = local.slice(0, 39).replace(/^[._-]+/, ""); + return /^[a-z0-9][a-z0-9._-]{1,38}$/.test(login) ? login : `user-${identity.sub.slice(-4)}`; +} + +/** First Google login: a Peppa account without Gitea and password (negative gitea_id), like eGov's. */ +export async function registerGoogleUser(db: Db, identity: GoogleIdentity): Promise { + const base = googleLoginBase(identity); + for (let n = 1; n < 1000; n++) { + const suffix = n === 1 ? "" : `-${n}`; + const login = base.slice(0, 39 - suffix.length).replace(/[._-]+$/, "") + suffix; + const [taken] = await db.select({ id: users.id }).from(users).where(sql`lower(${users.login}) = ${login}`); + if (taken) continue; + for (let i = 0; i < 5; i++) { + const [row] = await db + .insert(users) + .values({ giteaId: -1 - randomInt(2 ** 47), login, name: identity.name, googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() }) + .onConflictDoNothing() + .returning(); + if (row) return row; + const [same] = await db.select().from(users).where(eq(users.googleSub, identity.sub)); + if (same) return same; + } + } + throw new PeppaError("Не удалось создать пользователя"); +} + +/** Links a Google account to `userId`. One Google account — one Peppa account. */ +export async function linkGoogle(db: Db, userId: number, identity: GoogleIdentity): Promise { + const [other] = await db.select().from(users).where(eq(users.googleSub, identity.sub)); + if (other && other.id !== userId) throw new PeppaError("Этот Google-аккаунт уже привязан к другой учётке"); + await db.update(users).set({ googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() }).where(eq(users.id, userId)); + const user = await getUser(db, userId); + if (!user) throw new PeppaError("Пользователь не найден"); + return user; +} + +/** Unlinks Google, unless it is the account's only way in. */ +export async function unlinkGoogle(db: Db, userId: number): Promise { + const user = await getUser(db, userId); + if (!user) throw new PeppaError("Пользователь не найден"); + if (!user.egovIin && !user.passwordHash) throw new PeppaError("Это единственный способ входа — сначала привяжите eGov"); + await db.update(users).set({ googleSub: null, googleEmail: null, googleLinkedAt: null }).where(eq(users.id, userId)); + return (await getUser(db, userId))!; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e8663891..9e25b48d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -20,6 +20,7 @@ export * from "./repo-info.ts"; export * from "./incidents.ts"; export * from "./ci.ts"; export * from "./egov.ts"; +export * from "./google.ts"; export * from "./team.ts"; export * from "./progress.ts"; export * from "./intake.ts"; diff --git a/packages/db/migrations/0017_lowly_ghost_rider.sql b/packages/db/migrations/0017_lowly_ghost_rider.sql new file mode 100644 index 00000000..f5219444 --- /dev/null +++ b/packages/db/migrations/0017_lowly_ghost_rider.sql @@ -0,0 +1,4 @@ +ALTER TABLE `users` ADD `google_sub` text;--> statement-breakpoint +ALTER TABLE `users` ADD `google_email` text;--> statement-breakpoint +ALTER TABLE `users` ADD `google_linked_at` integer;--> statement-breakpoint +CREATE UNIQUE INDEX `users_google_sub_unique` ON `users` (`google_sub`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0017_snapshot.json b/packages/db/migrations/meta/0017_snapshot.json new file mode 100644 index 00000000..7e0fee99 --- /dev/null +++ b/packages/db/migrations/meta/0017_snapshot.json @@ -0,0 +1,4148 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "be145d37-3842-4e43-b7b7-8435001d71eb", + "prevId": "adc91e4e-2273-4fb3-aaa1-fd9d3dc11061", + "tables": { + "agents": { + "name": "agents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "character": { + "name": "character", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "agents_name_unique": { + "name": "agents_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_messages": { + "name": "chat_messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "chat_id": { + "name": "chat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "thread_key": { + "name": "thread_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thread_title": { + "name": "thread_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "important": { + "name": "important", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "author_kind": { + "name": "author_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'system'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_message_id": { + "name": "tg_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chat_messages_dedupe_key_unique": { + "name": "chat_messages_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "chat_messages_chat": { + "name": "chat_messages_chat", + "columns": [ + "chat_id", + "id" + ], + "isUnique": false + }, + "chat_messages_created_at": { + "name": "chat_messages_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "chat_messages_tg": { + "name": "chat_messages_tg", + "columns": [ + "tg_chat_id", + "tg_message_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "chat_messages_chat_id_chats_id_fk": { + "name": "chat_messages_chat_id_chats_id_fk", + "tableFrom": "chat_messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_messages_author_user_id_users_id_fk": { + "name": "chat_messages_author_user_id_users_id_fk", + "tableFrom": "chat_messages", + "tableTo": "users", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_question_id_questions_id_fk": { + "name": "chat_messages_question_id_questions_id_fk", + "tableFrom": "chat_messages", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_task_id_tasks_id_fk": { + "name": "chat_messages_task_id_tasks_id_fk", + "tableFrom": "chat_messages", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_title": { + "name": "tg_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_at": { + "name": "tg_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_by": { + "name": "tg_linked_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chats_user_id_unique": { + "name": "chats_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + }, + "chats_project_id_unique": { + "name": "chats_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + }, + "chats_tg_chat_id_unique": { + "name": "chats_tg_chat_id_unique", + "columns": [ + "tg_chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chats_user_id_users_id_fk": { + "name": "chats_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_project_id_projects_id_fk": { + "name": "chats_project_id_projects_id_fk", + "tableFrom": "chats", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_tg_linked_by_users_id_fk": { + "name": "chats_tg_linked_by_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_linked_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_agent_id_agents_id_fk": { + "name": "sessions_agent_id_agents_id_fk", + "tableFrom": "sessions", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "telegram_outbox_chat_message_id_chat_messages_id_fk": { + "name": "telegram_outbox_chat_message_id_chat_messages_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_token_enc": { + "name": "telegram_bot_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_username": { + "name": "telegram_bot_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_sub": { + "name": "google_sub", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_email": { + "name": "google_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_linked_at": { + "name": "google_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + }, + "users_google_sub_unique": { + "name": "users_google_sub_unique", + "columns": [ + "google_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index d91b73ba..3f6e63e3 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -120,6 +120,13 @@ "when": 1794678698233, "tag": "0016_user_telegram_bot", "breakpoints": true + }, + { + "idx": 17, + "version": "6", + "when": 1794727874686, + "tag": "0017_lowly_ghost_rider", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 6521db13..467f6084 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -38,6 +38,10 @@ export const users = sqliteTable("users", { // eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN. egovIin: text("egov_iin").unique(), egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }), + // Google login (PEP-90): the Google account's stable `sub` (identity) and its verified e-mail (display only). + googleSub: text("google_sub").unique(), + googleEmail: text("google_email"), + googleLinkedAt: integer("google_linked_at", { mode: "timestamp_ms" }), // Local login (PEP-68): scrypt hash "scrypt$N$r$p$salt$hash" (core/local-users.ts). passwordHash: text("password_hash"), passwordSetAt: integer("password_set_at", { mode: "timestamp_ms" }), diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index 0091752e..23f29b4b 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -26,6 +26,11 @@ const schema = z.object({ // eGov QR login (PEP-65) through the KazEDS relay, already trusted by eGov Mobile. KAZEDS_RELAY_BASE: z.string().url().default("https://sign.aitu.uz/relay/v1"), EGOV_ORGANISATION_NAME: z.string().default("Peppa"), + // Google login (PEP-90): OAuth client from Google Cloud; without both the button is hidden. + GOOGLE_CLIENT_ID: z.string().optional(), + GOOGLE_CLIENT_SECRET: z.string().optional(), + // Test override of accounts.google.com / oauth2.googleapis.com (mock-google). + GOOGLE_OAUTH_BASE: z.string().url().optional(), EGOV_ORGANISATION_BIN: z.string().regex(/^\d{12}$/).default("241140100000"), }); diff --git a/packages/testkit/bin/mock-google b/packages/testkit/bin/mock-google new file mode 100755 index 00000000..cc2608e9 --- /dev/null +++ b/packages/testkit/bin/mock-google @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-google.ts" "$@" diff --git a/packages/testkit/src/mock-google.ts b/packages/testkit/src/mock-google.ts new file mode 100644 index 00000000..1949aa7b --- /dev/null +++ b/packages/testkit/src/mock-google.ts @@ -0,0 +1,89 @@ +// Mock Google OAuth (PEP-90) for tests and checks without a Google Cloud client: GET /auth (the +// "user" consents at once and is redirected back with code+state), POST /token (checks client, +// redirect_uri, PKCE S256 and that the code is used once), GET /userinfo (OIDC profile). +// Standalone: `mock-google [port]` → GOOGLE_OAUTH_BASE=. +import { createHash, randomUUID } from "node:crypto"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +export interface MockGoogleAccount { + sub: string; + email: string; + email_verified?: boolean; + name?: string; +} + +interface Grant { + account: MockGoogleAccount; + redirectUri: string; + challenge: string; +} + +export class MockGoogle { + /** Who consents on the next /auth. */ + account: MockGoogleAccount = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" }; + readonly codes = new Map(); + readonly tokens = new Map(); + /** What the platform sent to /auth and /token — for assertions. */ + readonly seen: { auth: URLSearchParams[]; token: URLSearchParams[] } = { auth: [], token: [] }; + clientId = "mock-google-client"; + clientSecret = "mock-google-secret"; + private server: Server | null = null; + + async start(port = 0): Promise { + this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res)); + await new Promise((r) => this.server!.listen(port, "127.0.0.1", r)); + return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; + } + + async stop(): Promise { + await new Promise((r) => (this.server ? this.server.close(() => r()) : r())); + } + + private async handle(method: string, url: string, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) { + const u = new URL(url, "http://mock"); + const send = (code: number, body: unknown) => { + res.writeHead(code, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); + }; + if (method === "GET" && u.pathname === "/auth") { + const q = u.searchParams; + this.seen.auth.push(q); + if (q.get("client_id") !== this.clientId || q.get("response_type") !== "code" || q.get("code_challenge_method") !== "S256" || !q.get("redirect_uri") || !q.get("state")) { + return send(400, { error: "invalid_request" }); + } + const code = randomUUID(); + this.codes.set(code, { account: { ...this.account }, redirectUri: q.get("redirect_uri")!, challenge: q.get("code_challenge") ?? "" }); + const back = new URL(q.get("redirect_uri")!); + back.searchParams.set("code", code); + back.searchParams.set("state", q.get("state")!); + res.writeHead(302, { Location: back.toString() }); + return res.end(); + } + if (method === "POST" && u.pathname === "/token") { + let raw = ""; + for await (const chunk of req) raw += chunk; + const f = new URLSearchParams(raw); + this.seen.token.push(f); + const grant = this.codes.get(f.get("code") ?? ""); + this.codes.delete(f.get("code") ?? ""); // one use + if (f.get("client_id") !== this.clientId || f.get("client_secret") !== this.clientSecret) return send(401, { error: "invalid_client" }); + if (!grant || f.get("grant_type") !== "authorization_code" || f.get("redirect_uri") !== grant.redirectUri) return send(400, { error: "invalid_grant" }); + if (createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") !== grant.challenge) return send(400, { error: "invalid_grant" }); + const token = randomUUID(); + this.tokens.set(token, grant.account); + return send(200, { access_token: token, token_type: "Bearer", expires_in: 3600 }); + } + if (method === "GET" && u.pathname === "/userinfo") { + const account = this.tokens.get((req.headers.authorization ?? "").replace(/^Bearer /, "")); + return account ? send(200, account) : send(401, { error: "invalid_token" }); + } + send(404, { error: "not_found" }); + } +} + +if (import.meta.main) { + const g = new MockGoogle(); + const url = await g.start(Number(process.argv[2] ?? process.env.MOCK_PORT ?? 3104)); + console.log(`mock-google (TEST ONLY): GOOGLE_OAUTH_BASE=${url} GOOGLE_CLIENT_ID=${g.clientId} GOOGLE_CLIENT_SECRET=${g.clientSecret}`); +} diff --git a/packages/testkit/test/google.test.ts b/packages/testkit/test/google.test.ts new file mode 100644 index 00000000..023bdc8c --- /dev/null +++ b/packages/testkit/test/google.test.ts @@ -0,0 +1,139 @@ +// PEP-90: Google login against mock-google: first login registers, repeat finds the account, +// disabled user refused, forged/replayed/foreign-browser state refused, unverified e-mail, link/unlink. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { core, db, teardown } from "./helpers.ts"; +import { MockGoogle } from "../src/mock-google.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const google = new MockGoogle(); +const REDIRECT = "https://peppa.test/auth/google/callback"; + +before(async () => { + process.env.GOOGLE_OAUTH_BASE = await google.start(); + process.env.GOOGLE_CLIENT_ID = google.clientId; + process.env.GOOGLE_CLIENT_SECRET = google.clientSecret; +}); +after(async () => { + await google.stop(); + await teardown(); +}); + +/** The "browser": opens Google's authorize URL, which consents and redirects back with code+state. */ +async function consent(url: string) { + const res = await fetch(url, { redirect: "manual" }); + assert.equal(res.status, 302); + const back = new URL(res.headers.get("location")!); + return { code: back.searchParams.get("code")!, state: back.searchParams.get("state")! }; +} +async function login(purpose: "login" | "link" = "login", userId: number | null = null) { + const f = await core.startGoogleFlow(db, purpose, REDIRECT, userId); + const { code, state } = await consent(f.url); + return { f, code, state }; +} + +describe("Google login", () => { + test("disabled without a client", async () => { + delete process.env.GOOGLE_CLIENT_SECRET; + assert.equal(core.googleEnabled(), false); + await assert.rejects(core.startGoogleFlow(db, "login", REDIRECT), /не настроен/); + process.env.GOOGLE_CLIENT_SECRET = google.clientSecret; + assert.equal(core.googleEnabled(), true); + }); + + test("first login registers, the next one finds the same account", async () => { + const a = await login(); + const r = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }); + assert.ok(r.purpose === "login" && r.created); + assert.equal(r.user.login, "anna.petrova"); + assert.equal(r.user.name, "Anna Petrova"); + assert.equal(r.user.googleSub, "g-1001"); + assert.ok(r.user.giteaId < 0 && !r.user.passwordHash, "no Gitea, no password"); + assert.ok(core.isLocalUser(r.user)); + assert.equal(await core.mayUseMachineLogin(db, r.user.id), false, "no pool → no machine login, like eGov"); + assert.ok(google.seen.auth[0]!.get("code_challenge"), "PKCE"); + + const b = await login(); + const r2 = await core.completeGoogleFlow(db, { state: b.state, code: b.code, cookieState: b.f.state }); + assert.ok(r2.purpose === "login" && !r2.created); + assert.equal(r2.user.id, r.user.id); + }); + + test("same e-mail local part, other Google account → suffixed login, no merge by e-mail", async () => { + google.account = { sub: "g-1002", email: "anna.petrova@other.org", email_verified: true, name: "Another Anna" }; + const a = await login(); + const r = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }); + assert.equal(r.user.login, "anna.petrova-2"); + google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" }; + }); + + test("replayed callback is refused", async () => { + const a = await login(); + await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }); + await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }), /устарел/); + }); + + test("forged state and a state from another browser are refused, without calling Google", async () => { + const calls = google.seen.token.length; + const a = await login(); + await assert.rejects(core.completeGoogleFlow(db, { state: "forged", code: a.code, cookieState: "forged" }), /устарел/); + await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: "" }), /заново/); + await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: "other-browser" }), /заново/); + assert.equal(google.seen.token.length, calls, "no token exchange"); + // The failed attempts did not spend the flow: the real browser still completes. + const ok = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }); + assert.equal(ok.user.googleSub, "g-1001"); + }); + + test("a stolen code without the PKCE verifier is useless", async () => { + const a = await login(); + const res = await fetch(`${process.env.GOOGLE_OAUTH_BASE}/token`, { + method: "POST", + body: new URLSearchParams({ grant_type: "authorization_code", code: a.code, redirect_uri: REDIRECT, client_id: google.clientId, client_secret: google.clientSecret, code_verifier: "guess" }), + }); + assert.equal(res.status, 400); + }); + + test("unverified e-mail is refused and creates nothing", async () => { + google.account = { sub: "g-3003", email: "fake@example.com", email_verified: false }; + const a = await login(); + await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }), /не подтверждена/); + assert.equal(await core.getUserByLogin(db, "fake"), null); + google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" }; + }); + + test("a disabled user is not allowed", async () => { + const a = await login(); + const r = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }); + await core.setUserDisabled(db, r.user.id, true); + const b = await login(); + const r2 = await core.completeGoogleFlow(db, { state: b.state, code: b.code, cookieState: b.f.state }); + assert.equal(await core.isUserAllowed(db, r2.user), false); + await core.setUserDisabled(db, r.user.id, false); + }); + + test("link Google to an eGov account, taken account refused, unlink guard", async () => { + const egov = await core.registerEgovUser(db, { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" }); + await assert.rejects(core.startGoogleFlow(db, "link", REDIRECT, null), /после входа/); + google.account = { sub: "g-2002", email: "asel@example.com", email_verified: true }; + const l = await login("link", egov.id); + const r = await core.completeGoogleFlow(db, { state: l.state, code: l.code, cookieState: l.f.state }); + assert.equal(r.purpose, "link"); + assert.equal(r.user.id, egov.id); + assert.equal(r.user.googleSub, "g-2002"); + const again = await login(); + const r2 = await core.completeGoogleFlow(db, { state: again.state, code: again.code, cookieState: again.f.state }); + assert.equal(r2.user.id, egov.id, "Google now leads into the eGov account"); + + // g-1001 belongs to anna.petrova: the eGov account cannot take it. + google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true }; + const t = await login("link", egov.id); + await assert.rejects(core.completeGoogleFlow(db, { state: t.state, code: t.code, cookieState: t.f.state }), /уже привязан/); + + const unlinked = await core.unlinkGoogle(db, egov.id); + assert.equal(unlinked.googleSub, null); + // Google-only account cannot drop its only way in. + const [anna] = await db.select().from((await import("@peppa/db")).users).where((await import("drizzle-orm")).eq((await import("@peppa/db")).users.googleSub, "g-1001")); + await assert.rejects(core.unlinkGoogle(db, anna!.id), /единственный/); + }); +}); -- 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
    + ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index c8125ae7..7dc3ef3c 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -7,6 +7,8 @@ import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; +import { useT } from "@/components/I18n"; +import { m } from "@peppa/shared/i18n"; interface Item { href: string; @@ -21,45 +23,46 @@ interface Item { } const ITEMS: Item[] = [ - { href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" }, - { href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") }, - { 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 }, - { href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, - { href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, - { href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, - { href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true }, - { href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") }, + { href: "/", label: m("Главная"), icon: House, match: (p) => p === "/", count: "questions" }, + { href: "/chats", label: m("Чаты"), icon: MessagesSquare, match: (p) => p.startsWith("/chats") }, + { href: "/projects", label: m("Проекты"), icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, + { href: "/runners", label: m("Работа агентов"), icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, + { href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, + { href: "/welcome", label: m("О Пеппе"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true }, + { href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") }, + { href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, + { href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, + { href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, + { href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, + { href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, + { href: "/users", label: m("Пользователи"), icon: Users, match: (p) => p.startsWith("/users"), admin: true }, + { href: "/settings", label: m("Настройки"), icon: Settings, match: (p) => p.startsWith("/settings") }, ]; -const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" }; +const COUNT_TITLE = { questions: m("{n} вопросов ждут тебя"), waitingRunners: m("{n} раннеров ждут тебя") }; /** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number>; superadmin?: boolean }) { const path = usePathname(); + const t = useT(); return (
    - фабрика + {t("фабрика")} {/* PEP-52: the palette listens for clicks on [data-open-palette]. */}
    @@ -54,7 +54,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ {googleEnabled() && } -

    Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.

    +

    Вы с телефона? Войти можно и отсюда, но управлять заводом удобнее с ноутбука.

    diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts index 9a0fba3c..91a37abf 100644 --- a/apps/web/app/manifest.ts +++ b/apps/web/app/manifest.ts @@ -3,8 +3,8 @@ import type { MetadataRoute } from "next"; /** Installable as an app (PEP-55): Chrome «Установить Пеппу», badge on the app icon. */ export default function manifest(): MetadataRoute.Manifest { return { - name: "Peppa — софтвейр-фабрика", - short_name: "Peppa", + name: "Пеппа ЗАВОД", + short_name: "Пеппа ЗАВОД", description: "Проекты, стори и агенты", start_url: "/", scope: "/", diff --git a/apps/web/components/Brand.tsx b/apps/web/components/Brand.tsx index f32319b5..37d3ade6 100644 --- a/apps/web/components/Brand.tsx +++ b/apps/web/components/Brand.tsx @@ -1,11 +1,13 @@ -/** Peppa mark: pink tile with a glow + mono word. */ +/** PEP-97: the mark users see — pink tile with a glow + «Пеппа ЗАВОД». */ export function Brand({ large = false }: { large?: boolean }) { return ( P - peppa + + Пеппа ЗАВОД + ); } diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx index 64914c84..189ab87d 100644 --- a/apps/web/components/Footer.tsx +++ b/apps/web/components/Footer.tsx @@ -9,7 +9,7 @@ export function Footer() { const dirty = process.env.NEXT_PUBLIC_PEPPA_DIRTY; return (
    - Peppa v{version} + Пеппа ЗАВОД v{version} {commit && ( <> {" · "} diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx index 66f0ee1e..26e52745 100644 --- a/apps/web/components/Onboarding.tsx +++ b/apps/web/components/Onboarding.tsx @@ -15,7 +15,7 @@ export function OnboardingChecklist({ data, botUsername = null }: { data: Onboar
    -

    {fresh ? "Добро пожаловать! Запустим вашу фабрику за шесть шагов" : "С чего начать"}

    +

    {fresh ? "Добро пожаловать! Запустим ваш завод за шесть шагов" : "С чего начать"}

    {fresh ? "Вы описываете задачу обычными словами — команда ИИ-агентов пишет код и показывает результат. Программировать не нужно. Идите по шагам сверху вниз." diff --git a/apps/web/components/OwnBotSteps.tsx b/apps/web/components/OwnBotSteps.tsx index 10c8e0e4..896aff8a 100644 --- a/apps/web/components/OwnBotSteps.tsx +++ b/apps/web/components/OwnBotSteps.tsx @@ -23,7 +23,7 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:

    {!bare && (

    - Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования. + Через Telegram завод зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.

    )}
      diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index c8125ae7..88ee0afe 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -45,7 +45,6 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
      - фабрика {/* PEP-52: the palette listens for clicks on [data-open-palette]. */} + {/* PEP-100: the BotFather dialogue message by message — a PM has never seen it. */} +
        +
      1. + Нажмите Start (или «Запустить») внизу чата. +
      2. +
      3. + Отправьте ему сообщение /newbot — это команда «создать нового бота». +
      4. +
      5. + BotFather спросит имя бота. Напишите любое — так бот будет подписан в ваших чатах, например Мой завод. +
      6. +
      7. + Затем спросит адрес (username): латиницей, без пробелов, в конце обязательно bot, например{" "} + aigerim_zavod_bot. Если ответит, что адрес занят, — придумайте другой. +
      8. +
      9. + Готово: BotFather ответит «Done! Congratulations…». В этом сообщении после слов Use this token to access the HTTP API стоит + длинная строка — это токен, он нужен на следующем шаге. Нажмите на него, и Telegram скопирует. +
      10. +
      )}
    @@ -55,7 +72,8 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: ) : ( <> - BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает. + Токен выглядит так: 1234567890:AAH… (цифры, двоеточие, буквы). Вставьте его сюда — Пеппа хранит его + зашифрованным и никому не показывает. Никому, кроме Пеппы, токен не отправляйте.
    @@ -70,7 +88,10 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
    Откройте своего бота и нажмите Start - Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения. + + Это уже ваш бот, не BotFather. Кнопка ниже откроет его в Telegram — нажмите там Start, и бот узнает, куда вам писать. Удобнее на + телефоне: туда и будут приходить сообщения. + {hasBot && ( diff --git a/openspec/changes/pep-100-own-bot-steps/proposal.md b/openspec/changes/pep-100-own-bot-steps/proposal.md new file mode 100644 index 00000000..ed308199 --- /dev/null +++ b/openspec/changes/pep-100-own-bot-steps/proposal.md @@ -0,0 +1,9 @@ +# Proposal: PEP-100 — понятное подключение своего Telegram-бота + +## Why +PM не сразу понял, что бота нужно создать у @BotFather, потом дать имя и адрес. + +## What Changes +- Шаг 1 «Создайте бота у @BotFather» — переписка по сообщениям: Start → `/newbot` → имя → адрес на …bot → где в ответе токен. +- Шаг 2 — как выглядит токен; шаг 3 — что это уже свой бот, не BotFather. +- Подсказка онбординга называет эти шаги. diff --git a/openspec/changes/pep-100-own-bot-steps/specs/onboarding/spec.md b/openspec/changes/pep-100-own-bot-steps/specs/onboarding/spec.md new file mode 100644 index 00000000..771507d2 --- /dev/null +++ b/openspec/changes/pep-100-own-bot-steps/specs/onboarding/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: Подключение своего бота по шагам +Веб SHALL объяснять создание бота у @BotFather по сообщениям. + +#### Scenario: Новый пользователь подключает бота +- **WHEN** пользователь открывает шаги подключения своего бота +- **THEN** он видит: открыть @BotFather, Start, /newbot, имя, адрес на …bot, где взять токен, куда вставить diff --git a/openspec/changes/pep-100-own-bot-steps/tasks.md b/openspec/changes/pep-100-own-bot-steps/tasks.md new file mode 100644 index 00000000..0af94484 --- /dev/null +++ b/openspec/changes/pep-100-own-bot-steps/tasks.md @@ -0,0 +1 @@ +- [x] 1.1 шаги BotFather по сообщениям diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts index 3902f1f9..0ed6e850 100644 --- a/packages/core/src/onboarding.ts +++ b/packages/core/src/onboarding.ts @@ -76,7 +76,7 @@ export async function onboardingChecklist(db: Db, user: Pick Date: Sun, 15 Nov 2026 14:22:21 +0500 Subject: [PATCH 017/394] =?UTF-8?q?PEP-100:=20opening=20the=20bot=20keeps?= =?UTF-8?q?=20Peppa=20open=20=E2=80=94=20new=20tab,=20the=20page=20refresh?= =?UTF-8?q?es=20until=20Start=20is=20pressed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/actions.ts | 9 ++++ apps/web/components/OpenBotButton.tsx | 52 +++++++++++++++++++ apps/web/components/OwnBotSteps.tsx | 15 +++--- .../changes/pep-100-own-bot-steps/proposal.md | 1 + .../changes/pep-100-own-bot-steps/tasks.md | 1 + 5 files changed, 69 insertions(+), 9 deletions(-) create mode 100644 apps/web/components/OpenBotButton.tsx diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 65e9ed3b..6bd71fa4 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -418,6 +418,15 @@ export async function removeProjectMember(f: FormData) { }); } +/** PEP-100: the pairing link for the client to open in a new tab — Peppa stays where it is. */ +export async function pairingLinkAction(): Promise<{ url?: string; error?: string }> { + const user = asWebActor(await requireUser()); + const token = loadEnv().TELEGRAM_BOT_TOKEN; + const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username; + if (!token || !username) return { error: "Telegram-бот Пеппы не запущен" }; + return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` }; +} + export async function pairTelegram(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { diff --git a/apps/web/components/OpenBotButton.tsx b/apps/web/components/OpenBotButton.tsx new file mode 100644 index 00000000..dcd96ff2 --- /dev/null +++ b/apps/web/components/OpenBotButton.tsx @@ -0,0 +1,52 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { pairingLinkAction } from "@/app/(app)/actions"; + +/** + * PEP-100: opens the user's bot (with the pairing code) in a new tab / the Telegram app and keeps + * Peppa open — a plain redirect used to take the page away mid-steps. While the user presses + * Start, the page refreshes itself so the step turns done. + */ +export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) { + const router = useRouter(); + const [waiting, setWaiting] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + if (!waiting) return; + const t = setInterval(() => router.refresh(), 3000); + const stop = setTimeout(() => setWaiting(false), 3 * 60_000); + return () => { + clearInterval(t); + clearTimeout(stop); + }; + }, [waiting, router]); + + async function open() { + setError(null); + // Opened synchronously in the click, so the browser doesn't block it as a popup. + const tab = window.open("about:blank", "_blank"); + const r = await pairingLinkAction(); + if (!r.url) { + tab?.close(); + setError(r.error ?? "Не получилось открыть бота"); + return; + } + if (tab) tab.location.href = r.url; + else window.location.href = r.url; + setWaiting(true); + } + + return ( + + + {waiting && Нажмите Start в Telegram и вернитесь сюда — шаг отметится сам.} + {error && {error}} + + ); +} diff --git a/apps/web/components/OwnBotSteps.tsx b/apps/web/components/OwnBotSteps.tsx index 0f65e4c6..fe43138b 100644 --- a/apps/web/components/OwnBotSteps.tsx +++ b/apps/web/components/OwnBotSteps.tsx @@ -1,4 +1,5 @@ -import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram } from "@/app/(app)/actions"; +import { connectOwnBotAction, disconnectOwnBotAction } from "@/app/(app)/actions"; +import { OpenBotButton } from "@/components/OpenBotButton"; import { Hidden } from "@/components/cards"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -93,10 +94,7 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: телефоне: туда и будут приходить сообщения. {hasBot && ( - - - - + )}
    @@ -107,11 +105,10 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: ) : ( -
    - +
    Не хотите создавать бота? - - + +
    )}
    ); diff --git a/openspec/changes/pep-100-own-bot-steps/proposal.md b/openspec/changes/pep-100-own-bot-steps/proposal.md index ed308199..c62eb3ba 100644 --- a/openspec/changes/pep-100-own-bot-steps/proposal.md +++ b/openspec/changes/pep-100-own-bot-steps/proposal.md @@ -7,3 +7,4 @@ PM не сразу понял, что бота нужно создать у @Bot - Шаг 1 «Создайте бота у @BotFather» — переписка по сообщениям: Start → `/newbot` → имя → адрес на …bot → где в ответе токен. - Шаг 2 — как выглядит токен; шаг 3 — что это уже свой бот, не BotFather. - Подсказка онбординга называет эти шаги. +- «Открыть @бота» и «общий бот» открывают Telegram в новой вкладке (`pairingLinkAction` + `OpenBotButton`), страница Пеппы остаётся и сама обновляется, пока пользователь жмёт Start (раньше redirect уводил страницу). diff --git a/openspec/changes/pep-100-own-bot-steps/tasks.md b/openspec/changes/pep-100-own-bot-steps/tasks.md index 0af94484..0b48c39f 100644 --- a/openspec/changes/pep-100-own-bot-steps/tasks.md +++ b/openspec/changes/pep-100-own-bot-steps/tasks.md @@ -1 +1,2 @@ - [x] 1.1 шаги BotFather по сообщениям +- [x] 1.2 бот открывается в новой вкладке, страница остаётся и обновляется -- 2.45.2 From 60fa861303c9c56536116df8881bd10408567ef3 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 14:23:11 +0500 Subject: [PATCH 018/394] =?UTF-8?q?PEP-100:=20popups=20blocked=20=E2=80=94?= =?UTF-8?q?=20a=20new-tab=20link=20instead=20of=20leaving=20Peppa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/components/OpenBotButton.tsx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/web/components/OpenBotButton.tsx b/apps/web/components/OpenBotButton.tsx index dcd96ff2..9371ec5d 100644 --- a/apps/web/components/OpenBotButton.tsx +++ b/apps/web/components/OpenBotButton.tsx @@ -14,6 +14,7 @@ export function OpenBotButton({ label, variant = "default", size = "sm" }: { lab const router = useRouter(); const [waiting, setWaiting] = useState(false); const [error, setError] = useState(null); + const [link, setLink] = useState(null); useEffect(() => { if (!waiting) return; @@ -35,8 +36,9 @@ export function OpenBotButton({ label, variant = "default", size = "sm" }: { lab setError(r.error ?? "Не получилось открыть бота"); return; } + // Popups blocked: never take Peppa away — show a link that opens in a new tab instead. if (tab) tab.location.href = r.url; - else window.location.href = r.url; + else setLink(r.url); setWaiting(true); } @@ -45,6 +47,11 @@ export function OpenBotButton({ label, variant = "default", size = "sm" }: { lab + {link && ( + + Браузер не открыл новую вкладку — нажмите здесь, чтобы открыть бота + + )} {waiting && Нажмите Start в Telegram и вернитесь сюда — шаг отметится сам.} {error && {error}} -- 2.45.2 From 6d91a5473dc3854c9c2f985695b16e4e327712e8 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 14:24:58 +0500 Subject: [PATCH 019/394] PEP-102: a new project from the product's name only; PEP-100: own bot only, no shared-bot shortcut Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/actions.ts | 6 +- apps/web/app/(app)/projects/new/page.tsx | 70 +++++++----------- apps/web/app/(app)/settings/page.tsx | 8 ++- apps/web/components/ActivityAside.tsx | 2 +- apps/web/components/OwnBotSteps.tsx | 8 +-- apps/web/components/ProjectBasics.tsx | 72 +++++++++++++++++++ .../changes/pep-100-own-bot-steps/proposal.md | 1 + .../pep-102-new-project-plain/proposal.md | 10 +++ .../specs/web-workspace/spec.md | 8 +++ .../pep-102-new-project-plain/tasks.md | 2 + 10 files changed, 129 insertions(+), 58 deletions(-) create mode 100644 apps/web/components/ProjectBasics.tsx create mode 100644 openspec/changes/pep-102-new-project-plain/proposal.md create mode 100644 openspec/changes/pep-102-new-project-plain/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-102-new-project-plain/tasks.md diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 6bd71fa4..962947dc 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -422,8 +422,10 @@ export async function removeProjectMember(f: FormData) { export async function pairingLinkAction(): Promise<{ url?: string; error?: string }> { const user = asWebActor(await requireUser()); const token = loadEnv().TELEGRAM_BOT_TOKEN; - const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username; - if (!token || !username) return { error: "Telegram-бот Пеппы не запущен" }; + // Every user has their own bot: no pairing link through the shared one. + const username = user.telegramBotUsername; + if (!username) return { error: "Сначала подключите своего бота (шаги 1–2)" }; + if (!token) return { error: "Telegram-сервис Пеппы не запущен" }; return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` }; } diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx index 40e4b445..5f40b638 100644 --- a/apps/web/app/(app)/projects/new/page.tsx +++ b/apps/web/app/(app)/projects/new/page.tsx @@ -3,7 +3,8 @@ import { loadEnv } from "@peppa/shared"; import { Flash, PageHeader } from "@/components/common"; import { Hidden } from "@/components/cards"; import { Button } from "@/components/ui/button"; -import { Input, Label, NativeSelect } from "@/components/ui/input"; +import { Label, NativeSelect } from "@/components/ui/input"; +import { ProjectBasics } from "@/components/ProjectBasics"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; @@ -37,61 +38,38 @@ export default async function NewProject({ searchParams }: { searchParams: Promi return (
    - + Проект — это ваш продукт. Создайте его, а потом описывайте задачи словами: агенты будут их делать.
    - -
    - - -
    - {local ? ( -

    - У вас нет аккаунта Gitea — репозиторий будет {giteaUrl}/{botLogin}/<slug>. Доступ к коду — только через - Пеппу (агенты, PR, проверки); соавтором в Gitea вас добавить нельзя. -

    - ) : ( - <> + + {local ? ( +

    + Код хранится на заводе: {giteaUrl}/{botLogin}/…. Работать с ним вам не нужно — это делают агенты. +

    + ) : ( -

    - Репозиторий будет {giteaUrl}/<пространство>/<slug>. В личном пространстве приватный репозиторий видите - только вы, peppa-bot и участники проекта; в организации — ещё её участники с доступом к репозиториям. - {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."} -

    - - )} -
    - Видимость - Публичный — все, у кого есть доступ к Gitea - Приватный — только те, кому выдан доступ -
    -
    - Репозиторий - Создать новый - Подключить существующий (нужны права админа; видимость не меняется) -
    -

    - Пеппа добавит peppa-bot соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит - openspec init. Занимает до ~15 секунд. -

    + )} +
    + Кто может посмотреть код + Открытый — другие пользователи завода тоже могут его посмотреть + Закрытый — только вы и участники проекта +
    +
    + Код продукта + Начать с нуля — агенты напишут код сами + У меня уже есть код в Gitea — подключить его (адрес кода = имя репозитория) +
    +
    +

    Завод заведёт хранилище кода и подготовит его для агентов — это займёт до 15 секунд.

    diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 70d86853..e27f2a84 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -157,10 +157,12 @@ export default async function Settings({ searchParams }: { searchParams: Promise ) : ( ownBotSteps )} + {/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */} {user.telegramChatId && !hasBot && ( - -
    {ownBotSteps}
    -
    + <> + Сейчас сообщения приходят от общего бота Пеппы. Подключите своего бота — так у каждого пользователя свой канал с заводом. + {ownBotSteps} + )} {user.telegramChatId && hasBot && (
    diff --git a/apps/web/components/ActivityAside.tsx b/apps/web/components/ActivityAside.tsx index d7a274b5..d692cd85 100644 --- a/apps/web/components/ActivityAside.tsx +++ b/apps/web/components/ActivityAside.tsx @@ -25,7 +25,7 @@ export async function ActivityAside({ questions = true }: { questions?: boolean )} )} - + {sessions.length === 0 ? (

    Сейчас ничего не запущено.

    ) : ( diff --git a/apps/web/components/OwnBotSteps.tsx b/apps/web/components/OwnBotSteps.tsx index fe43138b..8b01adaf 100644 --- a/apps/web/components/OwnBotSteps.tsx +++ b/apps/web/components/OwnBotSteps.tsx @@ -99,16 +99,12 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
    - {hasBot ? ( + {/* PEP-100: every user has their own bot — no shared-bot shortcut. */} + {hasBot && ( - ) : ( -
    - Не хотите создавать бота? - -
    )}
    ); diff --git a/apps/web/components/ProjectBasics.tsx b/apps/web/components/ProjectBasics.tsx new file mode 100644 index 00000000..ce30ca40 --- /dev/null +++ b/apps/web/components/ProjectBasics.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { useState, type ReactNode } from "react"; +import { ChevronRight } from "lucide-react"; +import { Input, Label } from "@/components/ui/input"; + +const RU: Record = { + а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "y", к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s", + т: "t", у: "u", ф: "f", х: "h", ц: "ts", ч: "ch", ш: "sh", щ: "sch", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya", + ә: "a", ғ: "g", қ: "k", ң: "n", ө: "o", ұ: "u", ү: "u", һ: "h", і: "i", +}; +const latin = (s: string) => [...s.toLowerCase()].map((c) => RU[c] ?? c).join(""); + +/** «Сервис бронирования столиков» → `servis-bronirovaniya-stolikov` (the code's address). */ +export function slugFrom(name: string): string { + return latin(name).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); +} + +/** «Сервис бронирования столиков» → `SBS` (story numbers SBS-1, SBS-2…). */ +export function keyFrom(name: string): string { + const words = latin(name).split(/[^a-z0-9]+/).filter(Boolean); + let key = words.length > 1 ? words.map((w) => w[0]).join("") : (words[0] ?? "").slice(0, 3); + key = key.replace(/^[0-9]+/, "").slice(0, 5).toUpperCase(); + return key.length >= 2 ? key : (key + "PRJ").slice(0, 3); +} + +/** + * PEP-102: a product manager types the product's name; the code's address and the short code of + * story numbers fill in by themselves (editable under «Дополнительно» until touched). + */ +export function ProjectBasics({ children }: { children?: ReactNode }) { + const [name, setName] = useState(""); + const [slug, setSlug] = useState(null); + const [key, setKey] = useState(null); + const autoSlug = slugFrom(name) || "my-product"; + const autoKey = keyFrom(name); + return ( + <> + +

    + Задачи проекта будут называться {key ?? autoKey}-1,{" "} + {key ?? autoKey}-2 и так далее — по ним удобно говорить с агентами и ботом. +

    +
    + + Дополнительно — можно не трогать + +
    +
    + + +
    + {children} +
    +
    + + ); +} diff --git a/openspec/changes/pep-100-own-bot-steps/proposal.md b/openspec/changes/pep-100-own-bot-steps/proposal.md index c62eb3ba..b201c65c 100644 --- a/openspec/changes/pep-100-own-bot-steps/proposal.md +++ b/openspec/changes/pep-100-own-bot-steps/proposal.md @@ -8,3 +8,4 @@ PM не сразу понял, что бота нужно создать у @Bot - Шаг 2 — как выглядит токен; шаг 3 — что это уже свой бот, не BotFather. - Подсказка онбординга называет эти шаги. - «Открыть @бота» и «общий бот» открывают Telegram в новой вкладке (`pairingLinkAction` + `OpenBotButton`), страница Пеппы остаётся и сама обновляется, пока пользователь жмёт Start (раньше redirect уводил страницу). +- У каждого пользователя только свой бот: вариант «общий бот Пеппы» убран; кто ещё на общем — в «Настройках» видит предложение подключить своего. diff --git a/openspec/changes/pep-102-new-project-plain/proposal.md b/openspec/changes/pep-102-new-project-plain/proposal.md new file mode 100644 index 00000000..1cee6609 --- /dev/null +++ b/openspec/changes/pep-102-new-project-plain/proposal.md @@ -0,0 +1,10 @@ +# Proposal: PEP-102 — создание проекта понятно продакту + +## Why +Форма «Новый проект» говорила slug, ключ стори, Gitea, видимость репозитория — продакту непонятно. + +## What Changes +- Видно: «Как называется ваш продукт» и пример номеров задач (SBS-1, SBS-2). +- Адрес кода и код задач заполняются из названия (транслит, RU/KZ), правятся под «Дополнительно». +- Под «Дополнительно»: где хранить код, кто видит код (открытый/закрытый), начать с нуля / подключить свой код. +- Правая панель: «Агенты за работой» вместо «Активные раннеры». diff --git a/openspec/changes/pep-102-new-project-plain/specs/web-workspace/spec.md b/openspec/changes/pep-102-new-project-plain/specs/web-workspace/spec.md new file mode 100644 index 00000000..0e19eab5 --- /dev/null +++ b/openspec/changes/pep-102-new-project-plain/specs/web-workspace/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: Новый проект одним полем +Веб SHALL создавать проект по одному названию продукта, заполняя технические поля сам. + +#### Scenario: Продакт вводит название +- **WHEN** пользователь пишет «Бронирование столиков» +- **THEN** адрес кода `bronirovanie-stolikov` и код задач `BS` заполняются сами, форму можно отправить без «Дополнительно» diff --git a/openspec/changes/pep-102-new-project-plain/tasks.md b/openspec/changes/pep-102-new-project-plain/tasks.md new file mode 100644 index 00000000..50026fba --- /dev/null +++ b/openspec/changes/pep-102-new-project-plain/tasks.md @@ -0,0 +1,2 @@ +- [x] 1.1 форма и автозаполнение +- [x] 1.2 подпись панели -- 2.45.2 From 80a3bb79ad6ba29bad70e1d08ab77830e8059aac 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 14:34:03 +0500 Subject: [PATCH 020/394] =?UTF-8?q?PEP-97:=20the=20name=20users=20see=20is?= =?UTF-8?q?=20=C2=ABPeppa=20FACTORY=C2=BB=20everywhere?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/help/page.tsx | 2 +- apps/web/app/(app)/hosts/page.tsx | 2 +- apps/web/app/(app)/p/[key]/tabs.tsx | 2 +- apps/web/app/(app)/platform/page.tsx | 2 +- apps/web/app/(app)/projects/new/page.tsx | 6 +++--- apps/web/app/(app)/secrets/page.tsx | 2 +- apps/web/app/(app)/settings/page.tsx | 2 +- apps/web/app/(app)/subscriptions/page.tsx | 2 +- apps/web/app/(app)/team/page.tsx | 2 +- apps/web/app/(app)/welcome/page.tsx | 4 ++-- apps/web/app/layout.tsx | 2 +- apps/web/app/login/page.tsx | 6 +++--- apps/web/app/manifest.ts | 4 ++-- apps/web/components/Brand.tsx | 4 ++-- apps/web/components/Footer.tsx | 2 +- apps/web/components/Onboarding.tsx | 2 +- apps/web/components/OwnBotSteps.tsx | 6 +++--- openspec/changes/pep-97-peppa-zavod/proposal.md | 8 ++++---- .../pep-97-peppa-zavod/specs/web-workspace/spec.md | 4 ++-- packages/core/src/onboarding.ts | 2 +- 20 files changed, 33 insertions(+), 33 deletions(-) diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index dc177c66..2e9bd509 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -23,7 +23,7 @@ const TOOLS: Array<[string, string]> = [ ["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"], ["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"], ["get_usage", "лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали"], - ["get_metrics", "метрики завода по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"], + ["get_metrics", "метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"], ["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 + мини-промпт триажёра"], ]; diff --git a/apps/web/app/(app)/hosts/page.tsx b/apps/web/app/(app)/hosts/page.tsx index 977730d3..b162344b 100644 --- a/apps/web/app/(app)/hosts/page.tsx +++ b/apps/web/app/(app)/hosts/page.tsx @@ -13,7 +13,7 @@ import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { addHostAction, checkHostAction, deleteHostAction, toggleHostAction, updateHostAction } from "./actions"; -export const metadata = { title: "Хосты — Пеппа ЗАВОД" }; +export const metadata = { title: "Хосты — Peppa FACTORY" }; function StatusOf({ h }: { h: RunnerHostView }) { if (h.disabledAt) return отключён; diff --git a/apps/web/app/(app)/p/[key]/tabs.tsx b/apps/web/app/(app)/p/[key]/tabs.tsx index 64a40c83..b71fc070 100644 --- a/apps/web/app/(app)/p/[key]/tabs.tsx +++ b/apps/web/app/(app)/p/[key]/tabs.tsx @@ -298,7 +298,7 @@ export function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projec const AGENTS_MD_STARTER = `# AGENTS.md -Проект ведётся на **Пеппа ЗАВОД**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы; +Проект ведётся на **Peppa FACTORY**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы; здесь — только стандарты этого проекта. ## Стек и команды diff --git a/apps/web/app/(app)/platform/page.tsx b/apps/web/app/(app)/platform/page.tsx index 8f5d70f7..977be1d4 100644 --- a/apps/web/app/(app)/platform/page.tsx +++ b/apps/web/app/(app)/platform/page.tsx @@ -11,7 +11,7 @@ import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions"; -export const metadata = { title: "Платформа — Пеппа ЗАВОД" }; +export const metadata = { title: "Платформа — Peppa FACTORY" }; /** Telegram HTML of the digest → plain text for the preview. */ const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&"); diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx index 5f40b638..9263044a 100644 --- a/apps/web/app/(app)/projects/new/page.tsx +++ b/apps/web/app/(app)/projects/new/page.tsx @@ -45,7 +45,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi {local ? (

    - Код хранится на заводе: {giteaUrl}/{botLogin}/…. Работать с ним вам не нужно — это делают агенты. + Код хранится на фабрике: {giteaUrl}/{botLogin}/…. Работать с ним вам не нужно — это делают агенты.

    ) : (
    -

    Завод заведёт хранилище кода и подготовит его для агентов — это займёт до 15 секунд.

    +

    Фабрика заведёт хранилище кода и подготовит его для агентов — это займёт до 15 секунд.

    diff --git a/apps/web/app/(app)/secrets/page.tsx b/apps/web/app/(app)/secrets/page.tsx index 7d1507ae..846e3dc5 100644 --- a/apps/web/app/(app)/secrets/page.tsx +++ b/apps/web/app/(app)/secrets/page.tsx @@ -11,7 +11,7 @@ import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { checkGiteaTokenAction, markSecretRotatedAction, reencryptSecretsAction, revokeClientTokensAction } from "../actions"; -export const metadata = { title: "Секреты — Пеппа ЗАВОД" }; +export const metadata = { title: "Секреты — Peppa FACTORY" }; type Params = { error?: string; reencrypted?: string; unreadable?: string; revoked?: string; gitea?: string }; diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index e27f2a84..d32d7f99 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -160,7 +160,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise {/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */} {user.telegramChatId && !hasBot && ( <> - Сейчас сообщения приходят от общего бота Пеппы. Подключите своего бота — так у каждого пользователя свой канал с заводом. + Сейчас сообщения приходят от общего бота Пеппы. Подключите своего бота — так у каждого пользователя свой канал с фабрикой. {ownBotSteps} )} diff --git a/apps/web/app/(app)/subscriptions/page.tsx b/apps/web/app/(app)/subscriptions/page.tsx index 99b44df6..99a8cad3 100644 --- a/apps/web/app/(app)/subscriptions/page.tsx +++ b/apps/web/app/(app)/subscriptions/page.tsx @@ -24,7 +24,7 @@ import { updatePoolAction, } from "./actions"; -export const metadata = { title: "Подписки — Пеппа ЗАВОД" }; +export const metadata = { title: "Подписки — Peppa FACTORY" }; const hhmm = (d: Date) => d.toLocaleString("ru-RU", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); diff --git a/apps/web/app/(app)/team/page.tsx b/apps/web/app/(app)/team/page.tsx index b41c81a3..553c3027 100644 --- a/apps/web/app/(app)/team/page.tsx +++ b/apps/web/app/(app)/team/page.tsx @@ -12,7 +12,7 @@ import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions"; -export const metadata = { title: "Команда — Пеппа ЗАВОД" }; +export const metadata = { title: "Команда — Peppa FACTORY" }; /** PEP-75: the platform's team of agents — names and characters. Everyone sees it; a superadmin edits. */ export default async function Team({ searchParams }: { searchParams: Promise<{ error?: string; saved?: string }> }) { diff --git a/apps/web/app/(app)/welcome/page.tsx b/apps/web/app/(app)/welcome/page.tsx index 1b463c51..054ca268 100644 --- a/apps/web/app/(app)/welcome/page.tsx +++ b/apps/web/app/(app)/welcome/page.tsx @@ -31,11 +31,11 @@ export default async function Welcome() { await requireUser(); return ( - Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат. + Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат.
    -

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

    +

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

    Начать с первых шагов diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 59dfa96b..6e5133ab 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -7,7 +7,7 @@ import { THEME_COOKIE } from "@/lib/theme"; import { ErrorReporter } from "@/components/ErrorReporter"; import "./app.css"; -export const metadata = { title: "Пеппа ЗАВОД", description: "Пеппа ЗАВОД: опишите идею словами — ИИ-агенты сделают продукт", icons: { icon: "/icon.svg" } }; +export const metadata = { title: "Peppa FACTORY", description: "Peppa FACTORY: опишите идею словами — ИИ-агенты сделают продукт", icons: { icon: "/icon.svg" } }; export default async function RootLayout({ children }: { children: ReactNode }) { // Dark by default; the cookie is read on the server so a light choice renders without a dark flash. diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 6f33271a..cfcbe17d 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -26,7 +26,7 @@ const STEPS = [ ]; const NEED = [ - { icon: Laptop, text: "Ноутбук — управлять заводом удобнее с большого экрана" }, + { icon: Laptop, text: "Ноутбук — управлять фабрикой удобнее с большого экрана" }, { icon: ShieldCheck, text: "eGov Mobile на телефоне — для входа" }, { icon: MessageCircle, text: "Telegram — туда приходят вопросы агентов и «готово»" }, { icon: Sparkles, text: "Платная подписка Claude или ChatGPT — на ней работают агенты" }, @@ -43,7 +43,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{

    Опишите идею словами — команда ИИ-агентов сделает продукт

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

    @@ -54,7 +54,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ {googleEnabled() && } -

    Вы с телефона? Войти можно и отсюда, но управлять заводом удобнее с ноутбука.

    +

    Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.

    diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts index 91a37abf..9a7c38ff 100644 --- a/apps/web/app/manifest.ts +++ b/apps/web/app/manifest.ts @@ -3,8 +3,8 @@ import type { MetadataRoute } from "next"; /** Installable as an app (PEP-55): Chrome «Установить Пеппу», badge on the app icon. */ export default function manifest(): MetadataRoute.Manifest { return { - name: "Пеппа ЗАВОД", - short_name: "Пеппа ЗАВОД", + name: "Peppa FACTORY", + short_name: "Peppa FACTORY", description: "Проекты, стори и агенты", start_url: "/", scope: "/", diff --git a/apps/web/components/Brand.tsx b/apps/web/components/Brand.tsx index 37d3ade6..e3165d85 100644 --- a/apps/web/components/Brand.tsx +++ b/apps/web/components/Brand.tsx @@ -1,4 +1,4 @@ -/** PEP-97: the mark users see — pink tile with a glow + «Пеппа ЗАВОД». */ +/** PEP-97: the mark users see — pink tile with a glow + «Peppa FACTORY». */ export function Brand({ large = false }: { large?: boolean }) { return ( @@ -6,7 +6,7 @@ export function Brand({ large = false }: { large?: boolean }) { P - Пеппа ЗАВОД + Peppa FACTORY ); diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx index 189ab87d..781abf49 100644 --- a/apps/web/components/Footer.tsx +++ b/apps/web/components/Footer.tsx @@ -9,7 +9,7 @@ export function Footer() { const dirty = process.env.NEXT_PUBLIC_PEPPA_DIRTY; return (
    - Пеппа ЗАВОД v{version} + Peppa FACTORY v{version} {commit && ( <> {" · "} diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx index 26e52745..66f0ee1e 100644 --- a/apps/web/components/Onboarding.tsx +++ b/apps/web/components/Onboarding.tsx @@ -15,7 +15,7 @@ export function OnboardingChecklist({ data, botUsername = null }: { data: Onboar
    -

    {fresh ? "Добро пожаловать! Запустим ваш завод за шесть шагов" : "С чего начать"}

    +

    {fresh ? "Добро пожаловать! Запустим вашу фабрику за шесть шагов" : "С чего начать"}

    {fresh ? "Вы описываете задачу обычными словами — команда ИИ-агентов пишет код и показывает результат. Программировать не нужно. Идите по шагам сверху вниз." diff --git a/apps/web/components/OwnBotSteps.tsx b/apps/web/components/OwnBotSteps.tsx index 8b01adaf..daa72d01 100644 --- a/apps/web/components/OwnBotSteps.tsx +++ b/apps/web/components/OwnBotSteps.tsx @@ -24,7 +24,7 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:

    {!bare && (

    - Через Telegram завод зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. Для этого у вас будет свой + Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. Для этого у вас будет свой Telegram-бот: его не нужно программировать — его создают в самом Telegram через официальный бот @BotFather, это пять коротких шагов в чате.

    )} @@ -47,11 +47,11 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: Отправьте ему сообщение /newbot — это команда «создать нового бота».
  • - BotFather спросит имя бота. Напишите любое — так бот будет подписан в ваших чатах, например Мой завод. + BotFather спросит имя бота. Напишите любое — так бот будет подписан в ваших чатах, например Моя фабрика.
  • Затем спросит адрес (username): латиницей, без пробелов, в конце обязательно bot, например{" "} - aigerim_zavod_bot. Если ответит, что адрес занят, — придумайте другой. + aigerim_factory_bot. Если ответит, что адрес занят, — придумайте другой.
  • Готово: BotFather ответит «Done! Congratulations…». В этом сообщении после слов Use this token to access the HTTP API стоит diff --git a/openspec/changes/pep-97-peppa-zavod/proposal.md b/openspec/changes/pep-97-peppa-zavod/proposal.md index 219f3a50..11b20a63 100644 --- a/openspec/changes/pep-97-peppa-zavod/proposal.md +++ b/openspec/changes/pep-97-peppa-zavod/proposal.md @@ -1,9 +1,9 @@ -# Proposal: PEP-97 — «Пеппа ЗАВОД» для пользователей +# Proposal: PEP-97 — «Peppa FACTORY» для пользователей ## Why -Для пользователя пространство называется «Пеппа ЗАВОД»; в интерфейсе были «Peppa», «peppa», «софтвейр-фабрика». +Для пользователя пространство называется «Peppa FACTORY»; в интерфейсе были «Peppa», «peppa», «софтвейр-фабрика». ## What Changes -- Логотип «Пеппа ЗАВОД», заголовки вкладок «… — Пеппа ЗАВОД», имя PWA, описание сайта, подвал. -- Тексты для пользователя: «фабрика» → «завод» (вход, «О Пеппе», онбординг, бот-шаги, помощь, заготовка AGENTS.md). +- Логотип «Peppa FACTORY», заголовки вкладок «… — Peppa FACTORY», имя PWA, описание сайта, подвал. +- Тексты для пользователя: «софтвейр-фабрика» → «фабрика» (вход, «О Пеппе», онбординг, бот-шаги, помощь, заготовка AGENTS.md). - Код, имена пакетов и команд не меняются. diff --git a/openspec/changes/pep-97-peppa-zavod/specs/web-workspace/spec.md b/openspec/changes/pep-97-peppa-zavod/specs/web-workspace/spec.md index 194338dd..9907dae5 100644 --- a/openspec/changes/pep-97-peppa-zavod/specs/web-workspace/spec.md +++ b/openspec/changes/pep-97-peppa-zavod/specs/web-workspace/spec.md @@ -1,8 +1,8 @@ ## ADDED Requirements ### Requirement: Название для пользователя -Веб SHALL называть пространство «Пеппа ЗАВОД». +Веб SHALL называть пространство «Peppa FACTORY». #### Scenario: Вход - **WHEN** пользователь открывает страницу входа -- **THEN** он видит логотип «Пеппа ЗАВОД» и заголовок вкладки «Пеппа ЗАВОД» +- **THEN** он видит логотип «Peppa FACTORY» и заголовок вкладки «Peppa FACTORY» diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts index 0ed6e850..eae14e08 100644 --- a/packages/core/src/onboarding.ts +++ b/packages/core/src/onboarding.ts @@ -76,7 +76,7 @@ export async function onboardingChecklist(db: Db, user: Pick Date: Sun, 15 Nov 2026 14:40:34 +0500 Subject: [PATCH 021/394] =?UTF-8?q?PEP-103:=20bug=20stories=20first=20?= =?UTF-8?q?=E2=80=94=20the=20dispatcher=20takes=20fixes=20before=20feature?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-103-bugs-first/proposal.md | 7 +++++ .../specs/project-autonomy/spec.md | 8 +++++ openspec/changes/pep-103-bugs-first/tasks.md | 1 + packages/runner/src/autonomy.ts | 20 +++++++++++-- packages/testkit/test/bugs-first.test.ts | 29 +++++++++++++++++++ 5 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 openspec/changes/pep-103-bugs-first/proposal.md create mode 100644 openspec/changes/pep-103-bugs-first/specs/project-autonomy/spec.md create mode 100644 openspec/changes/pep-103-bugs-first/tasks.md create mode 100644 packages/testkit/test/bugs-first.test.ts diff --git a/openspec/changes/pep-103-bugs-first/proposal.md b/openspec/changes/pep-103-bugs-first/proposal.md new file mode 100644 index 00000000..c3903df4 --- /dev/null +++ b/openspec/changes/pep-103-bugs-first/proposal.md @@ -0,0 +1,7 @@ +# Proposal: PEP-103 — ошибки в приоритете + +## Why +PM: исправление ошибок — в первую очередь. + +## What Changes +- `readyBacklog` (диспетчер, пуш простоя) ставит первыми стори-баги: созданные из инцидентов Bugsink (`incidents.task_id`) или в эпике «Стабильность»; дальше — порядок доски. diff --git a/openspec/changes/pep-103-bugs-first/specs/project-autonomy/spec.md b/openspec/changes/pep-103-bugs-first/specs/project-autonomy/spec.md new file mode 100644 index 00000000..70c8267b --- /dev/null +++ b/openspec/changes/pep-103-bugs-first/specs/project-autonomy/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: Баги раньше фич +Диспетчер SHALL брать из бэклога сначала стори-исправления ошибок. + +#### Scenario: В бэклоге фичи и баг +- **WHEN** выше на доске фича, ниже стори из инцидента +- **THEN** агент берёт стори из инцидента первой diff --git a/openspec/changes/pep-103-bugs-first/tasks.md b/openspec/changes/pep-103-bugs-first/tasks.md new file mode 100644 index 00000000..fdbcc861 --- /dev/null +++ b/openspec/changes/pep-103-bugs-first/tasks.md @@ -0,0 +1 @@ +- [x] 1.1 `bugTaskIds`, порядок в `readyBacklog`, тест diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index 983793fb..03642900 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -34,9 +34,9 @@ import { projectAgentWarning, intakePendingTasks, } from "@peppa/core"; -import { questions, type Db } from "@peppa/db"; +import { goals, incidents, questions, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { and, eq, isNull } from "drizzle-orm"; +import { and, eq, isNotNull, isNull } from "drizzle-orm"; import { acceptTask, moveTask } from "./flow.ts"; import { autoMergeTask } from "./ci-feedback.ts"; import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts"; @@ -291,7 +291,21 @@ export async function readyBacklog(db: const blocked = await blockedTaskIds(db, projectId); // PEP-84: stories «продакт» and «аналитик» have not finished with stay out of the dispatcher's reach. const refining = await intakePendingTasks(db, projectId); - return list.filter((t) => !blocked.has(t.id) && !refining.has(t.id)); + const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id)); + // PEP-103: fixing errors comes first — bug stories, then the rest, each in board order. + const bugs = await bugTaskIds(db, projectId); + return [...ready.filter((t) => bugs.has(t.id)), ...ready.filter((t) => !bugs.has(t.id))]; +} + +/** Bug stories of a project: made from a production error (PEP-58) or in the «Стабильность» epic. */ +export async function bugTaskIds(db: Db, projectId: number): Promise> { + const fromIncidents = await db.select({ id: incidents.taskId }).from(incidents).where(and(eq(incidents.projectId, projectId), isNotNull(incidents.taskId))); + const inStability = await db + .select({ id: tasks.id }) + .from(tasks) + .innerJoin(goals, eq(goals.id, tasks.goalId)) + .where(and(eq(tasks.projectId, projectId), eq(goals.title, "Стабильность"))); + return new Set([...fromIncidents.map((r) => r.id!), ...inStability.map((r) => r.id)]); } /** Sessions that hold a WIP slot: their story is being worked on (not in review). */ diff --git a/packages/testkit/test/bugs-first.test.ts b/packages/testkit/test/bugs-first.test.ts new file mode 100644 index 00000000..41598d42 --- /dev/null +++ b/packages/testkit/test/bugs-first.test.ts @@ -0,0 +1,29 @@ +// PEP-103: the dispatcher takes bug stories first — from production errors or the «Стабильность» epic. +import assert from "node:assert/strict"; +import { after, describe, test } from "node:test"; +import { sql } from "drizzle-orm"; +import { core, db, runner, teardown } from "./helpers.ts"; + +after(teardown); + +describe("PEP-103: bugs first", () => { + test("bug stories come before features, each in board order", async () => { + const p = await core.createProject(db, { slug: "mock-bugs", key: "MBUG", name: "Bugs", giteaOwner: "x", workspacePath: "/tmp/mock-bugs" }); + const feature1 = await core.createTask(db, { projectId: p.id, title: "Фича 1" }); + const feature2 = await core.createTask(db, { projectId: p.id, title: "Фича 2" }); + const stability = await core.createGoal(db, p.id, "Стабильность"); + const epicBug = await core.createTask(db, { projectId: p.id, title: "Падает оплата", goalId: stability.id }); + const incidentBug = await core.createTask(db, { projectId: p.id, title: "TypeError на главной" }); + db.run(sql`insert into incidents (project_id, source, bugsink_issue_id, title, status, task_id, events, first_seen, last_seen, created_at, updated_at) values (${p.id}, 'api', 'mock-issue-1', 'TypeError', 'open', ${incidentBug.task.id}, 1, 0, 0, 0, 0)`); + const order = (await runner.readyBacklog(db, p.id)).map((t) => t.title); + assert.deepEqual(order, ["Падает оплата", "TypeError на главной", "Фича 1", "Фича 2"]); + assert.ok(feature1 && feature2); + }); + + test("no bugs — the board order is kept", async () => { + const p = await core.createProject(db, { slug: "mock-nobugs", key: "MNOB", name: "No bugs", giteaOwner: "x", workspacePath: "/tmp/mock-nobugs" }); + await core.createTask(db, { projectId: p.id, title: "A" }); + await core.createTask(db, { projectId: p.id, title: "B" }); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.title), ["A", "B"]); + }); +}); -- 2.45.2 From 1f16286dca5a33cdaa074579dcc1ac87fe496e6c 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 14:47:50 +0500 Subject: [PATCH 022/394] =?UTF-8?q?PEP-98:=20English=20for=20web,=20bot,?= =?UTF-8?q?=20notifications=20and=20runner=20messages;=20product=20name=20?= =?UTF-8?q?=C2=ABPeppa=20FACTORY=C2=BB=20everywhere?= 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 | 178 +++---- apps/bot/src/render.ts | 47 +- apps/bot/src/transcribe.ts | 5 +- apps/web/app/(app)/actions.ts | 51 +- apps/web/app/(app)/board-actions.ts | 11 +- apps/web/app/(app)/chats/[chat]/page.tsx | 91 ++-- apps/web/app/(app)/chats/actions.ts | 5 +- apps/web/app/(app)/help/page.tsx | 288 +++++------ apps/web/app/(app)/help/shortcuts/page.tsx | 14 +- apps/web/app/(app)/hosts/actions.ts | 4 +- apps/web/app/(app)/hosts/page.tsx | 80 +-- apps/web/app/(app)/journal/page.tsx | 8 +- apps/web/app/(app)/p/[key]/page.tsx | 266 +++++----- .../app/(app)/p/[key]/plan/[epic]/page.tsx | 45 +- apps/web/app/(app)/p/[key]/tabs.tsx | 150 +++--- apps/web/app/(app)/page.tsx | 14 +- apps/web/app/(app)/platform/actions.ts | 7 +- apps/web/app/(app)/platform/page.tsx | 57 ++- apps/web/app/(app)/projects/new/page.tsx | 47 +- apps/web/app/(app)/projects/page.tsx | 12 +- apps/web/app/(app)/runners/page.tsx | 27 +- apps/web/app/(app)/secrets/page.tsx | 102 ++-- apps/web/app/(app)/settings/page.tsx | 130 ++--- apps/web/app/(app)/subscriptions/actions.ts | 9 +- apps/web/app/(app)/subscriptions/page.tsx | 145 +++--- apps/web/app/(app)/t/[key]/page.tsx | 120 ++--- apps/web/app/(app)/t/[key]/tabs.tsx | 181 +++---- apps/web/app/(app)/team/actions.ts | 8 +- apps/web/app/(app)/team/page.tsx | 44 +- apps/web/app/(app)/users/page.tsx | 21 +- apps/web/app/(app)/welcome/page.tsx | 59 +-- apps/web/app/api/live/route.ts | 8 +- .../app/api/releases/[id]/shots/[n]/route.ts | 6 +- .../app/api/runners/[id]/terminal/route.ts | 20 +- apps/web/app/auth/egov/complete/route.ts | 6 +- apps/web/app/auth/egov/start/route.ts | 3 +- apps/web/app/auth/egov/status/route.ts | 3 +- apps/web/app/auth/google/callback/route.ts | 8 +- apps/web/app/auth/google/start/route.ts | 5 +- apps/web/app/auth/link/route.ts | 5 +- apps/web/app/login/page.tsx | 63 +-- apps/web/app/manifest.ts | 11 +- apps/web/app/oauth/authorize/page.tsx | 18 +- apps/web/components/Accounting.tsx | 202 ++++---- apps/web/components/ActivityAside.tsx | 14 +- apps/web/components/AgentBadge.tsx | 6 +- apps/web/components/AgentModel.tsx | 76 +-- apps/web/components/AgentSteps.tsx | 43 +- apps/web/components/Autonomy.tsx | 60 +-- apps/web/components/Board.tsx | 56 ++- apps/web/components/Brand.tsx | 4 +- apps/web/components/CommandPalette.tsx | 40 +- apps/web/components/EgovSign.tsx | 37 +- apps/web/components/Footer.tsx | 9 +- apps/web/components/Incidents.tsx | 68 +-- apps/web/components/LiveRefresh.tsx | 15 +- apps/web/components/LocalTime.tsx | 7 +- apps/web/components/Onboarding.tsx | 26 +- apps/web/components/OwnBotSteps.tsx | 37 +- apps/web/components/ProgressOverview.tsx | 49 +- apps/web/components/ProjectSecrets.tsx | 20 +- apps/web/components/PugMascot.tsx | 18 +- apps/web/components/PushNotifications.tsx | 20 +- apps/web/components/ReviewPreview.tsx | 16 +- apps/web/components/RunnerConsole.tsx | 87 ++-- apps/web/components/RunnerTerminal.tsx | 35 +- apps/web/components/Runners.tsx | 117 ++--- apps/web/components/SettingsDialog.tsx | 4 +- apps/web/components/Sidebar.tsx | 1 - apps/web/components/SubscriptionSetup.tsx | 37 +- apps/web/components/TimezoneField.tsx | 6 +- apps/web/components/VoiceInput.tsx | 9 +- apps/web/components/Workspace.tsx | 6 +- apps/web/components/cards.tsx | 89 ++-- apps/web/components/common.tsx | 25 +- apps/web/lib/queries.ts | 3 +- apps/web/lib/shortcuts.ts | 27 +- apps/web/lib/status.ts | 31 +- openspec/changes/pep-98-english-ui/tasks.md | 12 +- packages/core/src/access.ts | 5 +- packages/core/src/agent-model.ts | 13 +- packages/core/src/analytics.ts | 3 +- packages/core/src/audit.ts | 17 +- packages/core/src/autonomy.ts | 45 +- packages/core/src/backup.ts | 7 +- packages/core/src/budgets.ts | 14 +- packages/core/src/chats.ts | 103 ++-- packages/core/src/ci.ts | 17 +- packages/core/src/deps.ts | 9 +- packages/core/src/digest.ts | 42 +- packages/core/src/egov.ts | 19 +- packages/core/src/google.ts | 25 +- packages/core/src/hosts.ts | 21 +- packages/core/src/incidents.ts | 64 +-- packages/core/src/intake.ts | 15 +- packages/core/src/local-users.ts | 17 +- packages/core/src/memory.ts | 9 +- packages/core/src/monitor.ts | 19 +- packages/core/src/notifications.ts | 34 +- packages/core/src/oauth.ts | 9 +- packages/core/src/onboarding.ts | 57 ++- packages/core/src/palette.ts | 33 +- packages/core/src/platform-channel.ts | 56 ++- packages/core/src/preview.ts | 12 +- packages/core/src/progress.ts | 3 +- packages/core/src/repo-info.ts | 14 +- packages/core/src/reviews.ts | 13 +- packages/core/src/runners.ts | 17 +- packages/core/src/secrets-audit.ts | 113 ++--- packages/core/src/secrets.ts | 13 +- packages/core/src/subscriptions.ts | 29 +- packages/core/src/tasks.ts | 11 +- packages/core/src/team.ts | 13 +- packages/core/src/telegram.ts | 9 +- packages/core/src/usage.ts | 27 +- packages/core/src/users.ts | 13 +- packages/core/src/webpush.ts | 5 +- packages/runner/src/agents-md.ts | 9 +- packages/runner/src/autonomy.ts | 35 +- packages/runner/src/budgets.ts | 11 +- packages/runner/src/chats.ts | 53 +- packages/runner/src/ci-feedback.ts | 11 +- packages/runner/src/ci.ts | 13 +- packages/runner/src/claude-print.ts | 9 +- packages/runner/src/code.ts | 7 +- packages/runner/src/deploy.ts | 28 +- packages/runner/src/exec.ts | 3 +- packages/runner/src/flow.ts | 17 +- packages/runner/src/gitea-events.ts | 3 +- packages/runner/src/hook.ts | 9 +- packages/runner/src/hosts.ts | 5 +- packages/runner/src/incidents.ts | 42 +- packages/runner/src/intake.ts | 21 +- packages/runner/src/limits.ts | 11 +- packages/runner/src/live.ts | 9 +- packages/runner/src/planner.ts | 21 +- packages/runner/src/platform-release.ts | 13 +- packages/runner/src/project-subscription.ts | 17 +- packages/runner/src/provision.ts | 19 +- packages/runner/src/recovery.ts | 40 +- packages/runner/src/reviewer.ts | 13 +- packages/runner/src/rotation.ts | 18 +- packages/runner/src/runner-client.ts | 19 +- packages/runner/src/runner-service.ts | 7 +- packages/runner/src/runners.ts | 19 +- packages/runner/src/sessions.ts | 21 +- packages/runner/src/share.ts | 25 +- packages/runner/src/subscription-login.ts | 27 +- packages/runner/src/subscriptions.ts | 9 +- packages/runner/src/terminal.ts | 17 +- packages/runner/src/transfer.ts | 15 +- packages/runner/src/triage.ts | 5 +- packages/runner/src/watchdog.ts | 15 +- packages/runner/src/worktree.ts | 13 +- packages/shared/src/i18n/en/admin.ts | 264 ++++++++++ packages/shared/src/i18n/en/bot.ts | 462 ++++++++++++++++++ packages/shared/src/i18n/en/common.ts | 3 +- packages/shared/src/i18n/en/help.ts | 290 +++++++++++ packages/shared/src/i18n/en/index.ts | 9 +- packages/shared/src/i18n/en/project.ts | 390 +++++++++++++++ packages/shared/src/i18n/en/runner.ts | 411 ++++++++++++++++ packages/shared/src/i18n/en/settings.ts | 275 +++++++++++ packages/shared/src/i18n/en/story.ts | 419 ++++++++++++++++ packages/shared/src/i18n/index.ts | 58 ++- packages/testkit/test/i18n.test.ts | 120 +++++ scripts/i18n-check.ts | 20 +- 167 files changed, 5535 insertions(+), 2455 deletions(-) create mode 100644 packages/shared/src/i18n/en/admin.ts create mode 100644 packages/shared/src/i18n/en/bot.ts create mode 100644 packages/shared/src/i18n/en/help.ts create mode 100644 packages/shared/src/i18n/en/project.ts create mode 100644 packages/shared/src/i18n/en/runner.ts create mode 100644 packages/shared/src/i18n/en/settings.ts create mode 100644 packages/shared/src/i18n/en/story.ts create mode 100644 packages/testkit/test/i18n.test.ts diff --git a/AGENTS.md b/AGENTS.md index b3c2855f..0c7b417b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,6 +67,7 @@ - **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` сверен с 2.1.323 (PEP-3: `context_window.total_*_tokens` — последний запрос, не сумма; токены только из transcript), `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:` / `budget.task:` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой - **Память проекта (PEP-30)**: `.peppa/memory.md` в репо проекта (разделы Команды/Соглашения/Грабли/Решения), `core/memory.ts` (`rememberFact` — дубли пропускаются, предел `PEPPA_MEMORY_MAX_CHARS` 12 000 → отказ с просьбой ужать; `replaceMemory`; `memoryContext` = файл рабочей копии + 5 последних `done` стори). MCP агента `get_memory`/`remember` (файл рядом с `.peppa/project.json`, коммитит агент в ветке стори). Раннер (`launch` в runner/sessions.ts) дописывает `memoryContext` к общим правилам при каждом запуске/resume. Правило — «Завершение» в `template/RULES.md`; веб — вкладка «Спеки» (`MemorySection`) - **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:` → `task.agent:` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer; у клиентов PEP-21 — команда сервиса `sendEscalated`): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent k=v…` +- **Язык интерфейса (PEP-98)**: `@peppa/shared/i18n` — ключ словаря = русская строка-шаблон (`{name}`), словари `packages/shared/src/i18n/en/*.ts` (по разделам), `kk.ts` (PEP-99, пока откат на русский). `t(locale, key, vars)` / `translator(locale)` (`t.n` — множественное, `t.text` — перевод уже собранного текста), `m(key, vars)` — пометка шаблона в core/runner/bot (рендерит русский), `localizeText` — обратное сопоставление по шаблонам (целиком → строки → куски между HTML-тегами → «a · b», «Метка: значение»; захваченные значения переводятся рекурсивно). Язык: `settings` `user.locale:` (`getUserLocale`/`setUserLocale`, core/locale.ts) + cookie `peppa_lang`; веб `getLocale`/`getT` (lib/i18n.ts: пользователь → cookie → Accept-Language до входа → ru), клиент `useT()`/`LanguageSwitcher` (components/I18n.tsx), вход переносит язык (`adoptLocale`); ошибки server actions — `t.text` в `attempt()`. Бот переводит `text`/`caption`/кнопки/тосты по языку читателя (`localizeParams`, `telegramChatLocale`: группа — язык связавшего); push — в `deliverToUser`. Английское название — «Peppa FACTORY». Новый текст пользователю = ключ в `en/*.ts`, иначе падает `node scripts/i18n-check.ts` (тест `i18n.test.ts`); тексты агентам не переводятся (`// i18n-ignore`) - **Вход и старт для продактов (PEP-83)**: `/login` — зачем фабрика, пять шагов, что понадобится, вход справа (на телефоне: заголовок → вход → подробности); шаги `onboardingChecklist` для обычного пользователя: telegram → project → subscription (нет `projectAgentWarning` хотя бы у одного проекта) → story → started → accepted (первая `done`), у шага `action` — подпись кнопки; суперадмину subscription первым; тексты для непрограммиста - **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта - `template/` — содержимое репо `peppa/template` в Gitea (`GITEA_TEMPLATE_REPO`) (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index ef9a461f..ee88a9ec 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -2,8 +2,8 @@ // 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, telegramChatLocale } from "@peppa/core"; -import { localizeText } from "@peppa/shared/i18n"; +import { localizeMessage, reportPlatformError, telegramChatLocale } from "@peppa/core"; +import { m as tr } from "@peppa/shared/i18n"; import { accountUsageForUser, describeUsage, @@ -99,30 +99,34 @@ export interface BotOptions { log?: (msg: string) => void; } -const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя. - -• Кнопки под сообщением — быстрый ответ. -• Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию. -• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу. -• /status — активные сессии и открытые вопросы. -• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`; +// One key per line: localizeMessage translates a multi-line message line by line. +const HELP = [ + tr("Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя."), + "", + tr("• Кнопки под сообщением — быстрый ответ."), + tr("• Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию."), + tr("• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу."), + tr("• /status — активные сессии и открытые вопросы."), + tr("• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления)."), +].join("\n"); const PUSH_MAX_AGE_MS = 30 * 60_000; const PUSH_TITLE: Record = { - questions: "Агент ждёт ответа", - review: "Готово к ревью", - failures: "Раннер остановился", - releases: "Релиз", - incidents: "Ошибка в проде", - monitoring: "Мониторинг", - digest: "Сводка", - platform: "Обновления Пеппы", + questions: tr("Агент ждёт ответа"), + review: tr("Готово к ревью"), + failures: tr("Раннер остановился"), + releases: tr("Релиз"), + incidents: tr("Ошибка в проде"), + monitoring: tr("Мониторинг"), + digest: tr("Сводка"), + platform: tr("Обновления Пеппы"), }; /** Browser notification text for a question. */ function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } { - const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`; + const what = q.kind === "approval" ? tr("нужно одобрение") : q.kind === "permission" ? tr("нужно разрешение") : PUSH_TITLE[event]; + const title = ctx.taskKey ? `${ctx.taskKey}: ${what}` : what; const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text; return { title, body }; } @@ -156,13 +160,13 @@ export function createBot(o: BotOptions) { if (chatId == null) return params; const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const); if (locale === "ru") return params; - const tr = (v: unknown) => (typeof v === "string" ? localizeText(locale, v) : v); - const out: Record = { ...params, text: tr(params.text), caption: tr(params.caption) }; + const loc = (v: unknown) => (typeof v === "string" ? localizeMessage(locale, v) : v); + const out: Record = { ...params, text: loc(params.text), caption: loc(params.caption) }; if (params.text === undefined) delete out.text; if (params.caption === undefined) delete out.caption; const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined; if (markup && typeof markup === "object") { - const btn = (b: B): B => (typeof b === "string" ? (tr(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: tr((b as { text: string }).text) } as B) : b); + const btn = (b: B): B => (typeof b === "string" ? (loc(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: loc((b as { text: string }).text) } as B) : b); out.reply_markup = { ...markup, ...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}), @@ -336,8 +340,10 @@ export function createBot(o: BotOptions) { buttons = r.buttons; questionId = q.id; } else { - const who = m.kind === "user" ? `${esc(m.authorLogin ?? "?")}${m.via === "telegram" ? "" : " (веб)"}: ` : m.authorKind === "agent" ? "🤖 " : ""; - text = `${where ? `${where}\n` : ""}${who}${esc(m.text.slice(0, 3500))}${m.url ? `\n${esc(m.url)}` : ""}`; + const said = esc(m.text.slice(0, 3500)); + const who = m.kind === "user" ? `${esc(m.authorLogin ?? "?")}` : m.authorKind === "agent" ? "🤖 " : ""; + const body = m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said; + text = `${where ? `${where}\n` : ""}${who}${body}${m.url ? `\n${esc(m.url)}` : ""}`; } await enqueueTelegram(db, { dedupeKey: `cm:${m.id}:${tgChatId}`, @@ -401,10 +407,10 @@ export function createBot(o: BotOptions) { async function answer(q: Question, text: string): Promise { const fresh = await getQuestion(db, q.id); - if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`; + if (fresh.answeredAt) return fresh.answeredVia === "system" ? tr("Уже отвечено: {answer}", { answer: fresh.answer }) : tr("Уже отвечено ({via}): {answer}", { via: fresh.answeredVia, answer: fresh.answer }); const { delivered } = await answerAndDeliver(db, q.id, text, "telegram"); scheduleReconcile(); - return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори."; + return delivered ? tr("Отправлено в сессию ✅") : tr("Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори."); } const canAccess = (user: User, projectId: number) => @@ -417,17 +423,17 @@ export function createBot(o: BotOptions) { const ids = new Set(await userProjectIds(db, user.id)); const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId)); const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId)); - const lines = [`Активные сессии: ${sessions.length}`]; + const lines = ["" + tr("Активные сессии: {n}", { n: sessions.length }) + ""]; for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})${usageTotals(s.usage).hasData ? ` · ${esc(describeUsage(s.usage))}` : ""}`); - lines.push("", `Открытых вопросов: ${open.length}`); + lines.push("", "" + tr("Открытых вопросов: {n}", { n: open.length }) + ""); // PEP-5: subscription limit windows. const accounts = await accountUsageForUser(db, user); - lines.push("", "Лимиты", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : ["нет данных о лимитах"])); + lines.push("", "" + tr("Лимиты") + "", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : [tr("нет данных о лимитах")])); return lines.join("\n"); } // ── stories from messages (PEP-45) ───────────────────────────────────────────── - const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }]; + const cancelRow = (d: Draft): InlineButton[] => [{ text: tr("✖️ Отмена"), callback_data: `d:${d.id}:x` }]; const rows = (buttons: InlineButton[], per = 2) => buttons.reduce((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []); const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`; @@ -444,24 +450,25 @@ export function createBot(o: BotOptions) { for (const r of await db.select({ projectId: tasks.projectId, at: sql`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0); projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id); const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` })); - const more = projects.length > 12 ? "\nНет нужного — напиши заново с ключом: «KEY: …»." : ""; - await show(d.chatId, `📝 Новая стори ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId); + const text = [tr("📝 Новая стори {story}", { story: storyLine(d) }), tr("В какой проект?"), projects.length > 12 ? tr("Нет нужного — напиши заново с ключом: «KEY: …».") : null]; + await show(d.chatId, text.filter((l) => l != null).join("\n"), [...rows(buttons, 3), cancelRow(d)], editId); } async function askEpic(d: Draft, project: Project, editId?: number) { const epics = (await listGoals(db, project.id)).slice(0, 10); const buttons = epics.length - ? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }] - : [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }]; - await show(d.chatId, `📝 Новая стори в ${esc(project.key)}: ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId); + ? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: tr("Без эпика"), callback_data: `d:${d.id}:g:0` }] + : [{ text: tr("✅ Создать в {key}", { key: project.key }), callback_data: `d:${d.id}:g:0` }]; + const text = tr("📝 Новая стори в {key}: {story}", { key: esc(project.key), story: storyLine(d) }) + (epics.length ? "\n" + tr("Эпик?") : ""); + await show(d.chatId, text, [...rows(buttons), cancelRow(d)], editId); } /** A plain message (or a transcribed voice note) → a draft and the next question. */ async function startStory(user: User, chatId: number, text: string, voice: boolean) { const projects = await listUserProjects(db, user.id); - if (!projects.length) return reply(chatId, `У тебя пока нет проектов — создай первый: ${esc(o.webUrl)}/projects/new`); + if (!projects.length) return reply(chatId, tr("У тебя пока нет проектов — создай первый: {url}/projects/new", { url: esc(o.webUrl) })); const parsed = parseStoryText(text, projects); - if (!parsed.body) return reply(chatId, "Пустая стори — напиши, что сделать."); + if (!parsed.body) return reply(chatId, tr("Пустая стори — напиши, что сделать.")); const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null); const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice }); if (project) await askEpic(d, project); @@ -471,20 +478,20 @@ export function createBot(o: BotOptions) { async function onVoice(user: User, m: TgMessage) { const f = m.voice ?? m.audio!; const cfg = transcribeConfig(); - if (!cfg) return reply(m.chat.id, "Голосовые пока не настроены — напиши задачу текстом.", m.message_id); - if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) — запиши короче или напиши текстом.`, m.message_id); + if (!cfg) return reply(m.chat.id, tr("Голосовые пока не настроены — напиши задачу текстом."), m.message_id); + if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, tr("Слишком длинное голосовое (больше {n} минут) — запиши короче или напиши текстом.", { n: VOICE_MAX_SEC / 60 }), m.message_id); let text: string; try { const file = await api.getFile(f.file_id); - if (!file.file_path) throw new TranscribeError("Telegram не отдал файл"); + if (!file.file_path) throw new TranscribeError(tr("Telegram не отдал файл")); const audio = await api.downloadFile(file.file_path); text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg"); } catch (e) { log(`voice: ${(e as Error).message}`); - return reply(m.chat.id, `Не получилось расшифровать голосовое (${esc((e as Error).message)}). Напиши текстом.`, m.message_id); + return reply(m.chat.id, tr("Не получилось расшифровать голосовое ({error}). Напиши текстом.", { error: esc((e as Error).message) }), m.message_id); } - if (!text) return reply(m.chat.id, "Не разобрал ни слова — попробуй ещё раз или напиши текстом.", m.message_id); - await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id); + if (!text) return reply(m.chat.id, tr("Не разобрал ни слова — попробуй ещё раз или напиши текстом."), m.message_id); + await reply(m.chat.id, tr("🎙 Расслышал: «{text}»", { text: esc(text) }), m.message_id); await startStory(user, m.chat.id, text, true); } @@ -494,63 +501,63 @@ export function createBot(o: BotOptions) { const chatId = c.message!.chat.id; if (parts[0] === "t") { const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1]))); - if (!t || !(await canAccess(user, t.projectId))) return "Стори не найдена"; + if (!t || !(await canAccess(user, t.projectId))) return tr("Стори не найдена"); const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId)); const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) }; const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`; if (parts[2] === "keep") { - await show(chatId, `${head}\nВ бэклоге.`, [], msgId); - return "Оставил в бэклоге"; + await show(chatId, head + "\n" + tr("В бэклоге."), [], msgId); + return tr("Оставил в бэклоге"); } - if (parts[2] !== "start") return "Неизвестная кнопка"; + if (parts[2] !== "start") return tr("Неизвестная кнопка"); if (t.status !== "backlog") { - await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId); - return `${ref.key} уже ${t.status}`; + await show(chatId, head + "\n" + tr("Уже не в бэклоге ({status}).", { status: esc(t.status) }), [], msgId); + return tr("{key} уже {status}", { key: ref.key, status: t.status }); } try { await moveTask(db, ref, "in_progress"); } catch (e) { return (e as Error).message; } - await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId); - return `${ref.key}: агент взялся ▶️`; + await show(chatId, head + "\n" + tr("▶️ В работе — агент взялся."), [], msgId); + return tr("{key}: агент взялся ▶️", { key: ref.key }); } const d = await loadDraft(db, Number(parts[1]), user.id); if (!d) { - await show(chatId, "Черновик не найден или устарел — напиши заново.", [], msgId); - return "Черновик устарел"; + await show(chatId, tr("Черновик не найден или устарел — напиши заново."), [], msgId); + return tr("Черновик устарел"); } if (parts[2] === "x") { await dropDraft(db, d.id); - await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId); - return "Отменено"; + await show(chatId, tr("✖️ Отменено: {story}", { story: storyLine(d) }), [], msgId); + return tr("Отменено"); } if (parts[2] === "p") { const projectId = Number(parts[3]); const project = await projectForUser(db, user.id, projectId).catch(() => null); - if (!project) return "Проект не найден"; + if (!project) return tr("Проект не найден"); await updateDraft(db, { ...d, projectId }); await askEpic(d, project, msgId); return project.key; } if (parts[2] === "g" && d.projectId) { const project = await projectForUser(db, user.id, d.projectId).catch(() => null); - if (!project) return "Проект не найден"; + if (!project) return tr("Проект не найден"); const goalId = Number(parts[3]) || undefined; - if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден"; + if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return tr("Эпик не найден"); const { title, rest } = splitStory(d.text); - const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`; + const from = d.voice ? tr("Создано из Telegram ({login}, расшифровка голосового).", { login: user.login }) : tr("Создано из Telegram ({login}).", { login: user.login }); const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` }); await dropDraft(db, d.id); await show( chatId, - `📥 Создал ${esc(ref.key)}: ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`, - [[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]], + [tr("📥 Создал {key}: {title}", { key: esc(ref.key), title: esc(title) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`, tr("Взять в работу сейчас?")].join("\n"), + [[{ text: tr("▶️ Взять в работу"), callback_data: `t:${ref.task.id}:start` }, { text: tr("Оставить в бэклоге"), callback_data: `t:${ref.task.id}:keep` }]], msgId, ); - return `Создал ${ref.key}`; + return tr("Создал {key}", { key: ref.key }); } - return "Неизвестная кнопка"; + return tr("Неизвестная кнопка"); } /** A message in a group (PEP-62): linking by code, then replies and commands of the linked chat. */ @@ -558,11 +565,18 @@ export function createBot(o: BotOptions) { const text = m.text?.trim() ?? ""; const link = /^\/(?:start|link)(?:@\w+)?\s+(\S+)$/.exec(text); if (link) { - if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done"); + if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, tr("Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».")).then(() => "done"); const chat = await acceptChatLink(db, o.secret, link[1]!, { tgChatId: m.chat.id, title: m.chat.title ?? null }); - if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done"); - const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом"; - await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь реплаем — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды.`); + if (!chat) return reply(m.chat.id, tr("Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».")).then(() => "done"); + const name = chat.projectId ? tr("чатом проекта {key}", { key: esc(await projectKey(chat.projectId)) }) : tr("мастер-чатом"); + await reply( + m.chat.id, + [ + tr("Группа связана с {name} ✅", { name }), + "", + tr("Сюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь реплаем — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды."), + ].join("\n"), + ); return "done"; } const chat = await chatByTelegram(db, m.chat.id); @@ -571,7 +585,7 @@ export function createBot(o: BotOptions) { if (!m.reply_to_message && !text.startsWith("/")) return "ignored"; const user = await telegramAccountUser(db, m.from.id); if (!user || !(await mayWriteChat(db, user, chat))) { - await reply(m.chat.id, user ? "У тебя нет доступа к этому чату." : `Не знаю тебя в Пеппе — привяжи Telegram: ${esc(o.webUrl)}/settings → Telegram.`, m.message_id); + await reply(m.chat.id, user ? tr("У тебя нет доступа к этому чату.") : tr("Не знаю тебя в Пеппе — привяжи Telegram: {url}/settings → Telegram.", { url: esc(o.webUrl) }), m.message_id); return "done"; } enterActor({ kind: "user", userId: user.id, channel: "telegram" }); @@ -605,11 +619,11 @@ export function createBot(o: BotOptions) { const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId }); if (b) { await syncOwnBots().catch(() => {}); // the chat now belongs to this bot - await reply(m.chat.id, `Привязано ✅\n\n${HELP}`); + await reply(m.chat.id, tr("Привязано ✅") + "\n\n" + HELP); scheduleReconcile(); return "done"; } - await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`); + await reply(m.chat.id, tr("Код привязки неверный или истёк. Получи новый: {url}/settings → Telegram", { url: esc(o.webUrl) })); return "done"; } const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null; @@ -624,14 +638,14 @@ export function createBot(o: BotOptions) { if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done"); if (/^\/digest\b/.test(text)) { const d = await buildDigest(db, user); - await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`)); + await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: tr("Сводка за сутки") }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`)); return "done"; } if (m.reply_to_message) { const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id); if (!q || !(await canAccess(user, q.projectId))) { - await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id); + await reply(m.chat.id, tr("Не нашёл вопрос для этого сообщения."), m.message_id); return "done"; } await reply(m.chat.id, esc(await answer(q, text)), m.message_id); @@ -642,7 +656,7 @@ export function createBot(o: BotOptions) { return "done"; } if (!text || text.startsWith("/")) { - await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею."); + await reply(m.chat.id, tr("Чтобы ответить агенту, ответь реплаем на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею.")); return "done"; } // PEP-45: any other text is a new story (created only after a button press). @@ -659,32 +673,32 @@ export function createBot(o: BotOptions) { if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who; } if (!user) { - await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {}); + await api.answerCallbackQuery(c.id, tr("Нет доступа")).catch(() => {}); return "ignored"; } enterActor({ kind: "user", userId: user.id, channel: "telegram" }); const parts = (c.data ?? "").split(":"); if (parts[0] === "d" || parts[0] === "t") { - const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка")); + const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), tr("Ошибка"))); await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); return "done"; } const [kind, idStr, choice] = parts; const id = Number(idStr); - let toast = "Неизвестная кнопка"; + let toast = tr("Неизвестная кнопка"); const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null; const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null; const i0 = kind === "i" ? await getIncident(db, id).catch(() => null) : null; const projectId = q0?.projectId ?? s0?.projectId ?? i0?.projectId; if (projectId == null || !(await canAccess(user, projectId))) { // Unknown or someone else's question/session: don't reveal which. - await api.answerCallbackQuery(c.id, kind === "s" ? "Сессия не найдена" : kind === "i" ? "Ошибка не найдена" : "Вопрос не найден").catch(() => {}); + await api.answerCallbackQuery(c.id, kind === "s" ? tr("Сессия не найдена") : kind === "i" ? tr("Ошибка не найдена") : tr("Вопрос не найден")).catch(() => {}); return "done"; } if (kind === "q" && choice === "accept") { try { const ref = await acceptTask(db, id, "telegram"); - toast = `${ref.key} принята ✅`; + toast = tr("{key} принята ✅", { key: ref.key }); } catch (e) { toast = (e as Error).message; } @@ -692,29 +706,29 @@ export function createBot(o: BotOptions) { } else if (kind === "q") { const q = await getQuestion(db, id).catch(() => null); const text = q && choice ? choiceToAnswer(q, choice) : null; - toast = q && text ? await answer(q, text) : "Вопрос не найден"; + toast = q && text ? await answer(q, text) : tr("Вопрос не найден"); } else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) { // Decision on a new production error (PEP-58). try { const r = await decideIncident(db, id, choice, user.login); - toast = r.task ? `${r.task.key}: ${choice === "start" ? "агент взялся ▶️" : "в бэклоге 📥"}` : "Игнорируем 🙈"; + toast = r.task ? (choice === "start" ? tr("{key}: агент взялся ▶️", { key: r.task.key }) : tr("{key}: в бэклоге 📥", { key: r.task.key })) : tr("Игнорируем 🙈"); } catch (e) { toast = (e as Error).message; } wakeOutbox?.(); } else if (kind === "s") { const s = await getSession(db, id).catch(() => null); - if (!s) toast = "Сессия не найдена"; + if (!s) toast = tr("Сессия не найдена"); else if (choice === "resume") { try { const r = await resumeSession(db, s.id); - toast = `Перезапущено (поколение ${r.generation}) 🔁`; + toast = tr("Перезапущено (поколение {n}) 🔁", { n: r.generation }); } catch (e) { toast = (e as Error).message; } } else if (choice === "stop") { await stopSession(db, s.id); - toast = "Сессия остановлена ⏹"; + toast = tr("Сессия остановлена ⏹"); } scheduleReconcile(); } diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 890c9fdd..2d069dd9 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -1,15 +1,17 @@ // Telegram message texts and buttons for PM questions. HTML parse mode. import type { Question, SessionView } from "@peppa/core"; import type { InlineButton } from "./telegram.ts"; +import { m as tr } from "@peppa/shared/i18n"; export const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); +const italic = (s: string) => `${s}`; const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s); const KIND: Record = { - approval: "📝 Нужно одобрение proposal", - question: "❓ Вопрос", - permission: "🔐 Нужно разрешение", - attention: "👀 Сессия ждёт тебя", + approval: tr("📝 Нужно одобрение proposal"), + question: tr("❓ Вопрос"), + permission: tr("🔐 Нужно разрешение"), + attention: tr("👀 Сессия ждёт тебя"), }; export interface Rendered { @@ -22,7 +24,7 @@ export function renderQuestion( q: Question, ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, ): Rendered { - const head = [`${esc(ctx.taskKey ?? (q.sessionId ? `Сессия ${q.sessionId}` : "Релизы проекта"))}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] + const head = ["" + esc(ctx.taskKey ?? (q.sessionId ? tr("Сессия {id}", { id: q.sessionId }) : tr("Релизы проекта"))) + "", ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); const body = esc(clip(q.text, 3300)); @@ -30,31 +32,31 @@ export function renderQuestion( const buttons: InlineButton[][] = []; if (q.kind === "approval") { - buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]); - lines.push("", "Чтобы вернуть на доработку — ответь на это сообщение комментарием."); + buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]); + lines.push("", italic(tr("Чтобы вернуть на доработку — ответь на это сообщение комментарием."))); } else if (q.kind === "permission") { buttons.push([ - { text: "✅ Разрешить", callback_data: `q:${q.id}:allow` }, - { text: "♾ Всегда", callback_data: `q:${q.id}:always` }, - { text: "⛔ Запретить", callback_data: `q:${q.id}:deny` }, + { text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` }, + { text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` }, + { text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` }, ]); } else if (q.kind === "question") { (q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }])); - lines.push("", "Выбери вариант или ответь на это сообщение своим текстом."); + lines.push("", italic(tr("Выбери вариант или ответь на это сообщение своим текстом."))); } else if (ctx.taskStatus === "review") { - lines[1] = "✅ Готово к ревью"; - buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]); - lines.push("", "Есть замечания — ответь на это сообщение, агент доработает."); + lines[1] = tr("✅ Готово к ревью"); + buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]); + lines.push("", italic(tr("Есть замечания — ответь на это сообщение, агент доработает."))); } else { const s = ctx.session; if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) { buttons.push([ - { text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` }, - { text: "⏹ Остановить", callback_data: `s:${s.id}:stop` }, + { text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` }, + { text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` }, ]); } else { - buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]); - lines.push("", "Или ответь на это сообщение — текст уйдёт в сессию."); + buttons.push([{ text: tr("▶️ Продолжай"), callback_data: `q:${q.id}:cont` }]); + lines.push("", italic(tr("Или ответь на это сообщение — текст уйдёт в сессию."))); } } if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); @@ -64,15 +66,16 @@ export function renderQuestion( /** Text after the question is closed: original + who answered what, no buttons. */ export function renderAnswered(original: string, q: Question): string { const mark = q.answeredVia === "system" ? "⌛" : "✅"; - const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"]; - return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: ${esc(clip(q.answer ?? "", 500))}`}`; + const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"]; + const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: {answer}", { via, answer: esc(clip(q.answer ?? "", 500)) }); + return `${original}\n\n${mark} ${said}`; } /** The answer text a button stands for. */ export function choiceToAnswer(q: Question, choice: string): string | null { - if (q.kind === "approval" && choice === "approve") return "ок"; + if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice; - if (q.kind === "attention" && choice === "cont") return "Продолжай."; + if (q.kind === "attention" && choice === "cont") return "Продолжай."; // i18n-ignore: the answer goes to the agent const m = /^o(\d+)$/.exec(choice); if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null; return null; diff --git a/apps/bot/src/transcribe.ts b/apps/bot/src/transcribe.ts index 11bfe038..b39fc607 100644 --- a/apps/bot/src/transcribe.ts +++ b/apps/bot/src/transcribe.ts @@ -4,6 +4,7 @@ // OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1, // whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use // mock-transcribe (packages/testkit). +import { m as tr } from "@peppa/shared/i18n"; export interface TranscribeConfig { url: string; @@ -41,12 +42,12 @@ export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename signal: AbortSignal.timeout(120_000), }); } catch (e) { - throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`); + throw new TranscribeError(tr("сервис расшифровки недоступен: {error}", { error: (e as Error).message })); } const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string }; if (!res.ok) { const msg = typeof body.error === "string" ? body.error : body.error?.message; - throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`); + throw new TranscribeError(tr("расшифровка не удалась: {status}", { status: `${res.status}${msg ? ` ${msg}` : ""}` })); } return (body.text ?? "").trim(); } diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 21c3c71c..7d0fd57d 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -66,6 +66,7 @@ import { redirect } from "next/navigation"; import { asWebActor, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; +import { m, PRODUCT_NAME } from "@peppa/shared/i18n"; const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); const back = (f: FormData) => str(f, "back") || "/"; @@ -106,8 +107,8 @@ export async function answerQuestion(f: FormData) { const q = await getQuestion(db, Number(str(f, "questionId"))); await projectForUser(db, user.id, q.projectId); const answer = str(f, "choice") || str(f, "answer"); - if (!answer) throw new PeppaError("Пустой ответ"); - if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`); + if (!answer) throw new PeppaError(m("Пустой ответ")); + if (q.answeredAt) throw new PeppaError(q.answeredVia === "system" ? m("Уже отвечено: {answer}", { answer: q.answer }) : m("Уже отвечено ({via}): {answer}", { via: q.answeredVia, answer: q.answer })); if (answer === "__accept") { await acceptTask(db, q.id, "web"); return; @@ -120,7 +121,7 @@ export async function addTask(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); - if (!str(f, "title")) throw new PeppaError("Нужно название стори"); + if (!str(f, "title")) throw new PeppaError(m("Нужно название стори")); const epic = Number(str(f, "epicId")) || undefined; const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic }); return `/t/${ref.key}`; @@ -132,7 +133,7 @@ export async function addEpic(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); - if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика"); + if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика")); await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined); }); } @@ -146,7 +147,7 @@ export async function editEpic(f: FormData) { await updateEpic(db, p.id, id, { status: "archived" }); return; } - if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика"); + if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика")); await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null }); }); } @@ -158,7 +159,7 @@ export async function editStoryAction(f: FormData) { const ref = await resolveTask(db, str(f, "taskKey")); await projectForUser(db, user.id, ref.project.id); const title = str(f, "title"); - if (title.length < 2) throw new PeppaError("Нужно название стори"); + if (title.length < 2) throw new PeppaError(m("Нужно название стори")); const epic = str(f, "epicId"); await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login); }); @@ -173,7 +174,8 @@ export async function commentStoryAction(f: FormData) { const c = await addStoryComment(db, ref, user, String(f.get("text") ?? "")); if (str(f, "toAgent")) { const [live] = await listSessions(db, { active: true, taskId: ref.task.id }); - if (!live) throw new PeppaError("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task"); + if (!live) throw new PeppaError(m("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task")); + // i18n-ignore — text for the agent await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`); } }); @@ -193,7 +195,7 @@ export async function acceptStoryAction(f: FormData) { async function launchChoice(f: FormData, user: Awaited>) { const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : ""; const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined; - if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку"); + if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError(m("Отметьте хотя бы одну подписку")); const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined; const provider = str(f, "provider") as Provider | ""; return { provider: provider || undefined, subscriptionIds, poolId }; @@ -309,7 +311,7 @@ export async function messageSession(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const s = await ownedSession(user.id, Number(str(f, "sessionId"))); - if (!str(f, "text")) throw new PeppaError("Пустое сообщение"); + if (!str(f, "text")) throw new PeppaError(m("Пустое сообщение")); await sendToSession(db, s.id, str(f, "text")); }); } @@ -344,7 +346,7 @@ export async function moveTaskCard(f: FormData) { const ref = await resolveTask(db, str(f, "taskKey")); await projectForUser(db, user.id, ref.project.id); const to = str(f, "to") as BoardColumn; - if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка"); + if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError(m("Неизвестная колонка")); await moveTask(db, ref, to); }); } @@ -362,7 +364,7 @@ export async function addProjectMember(f: FormData) { await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); const r = await shareProject(db, user, p, str(f, "login")); - if (!r.repoAccess) throw new PeppaError(`${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную`); + if (!r.repoAccess) throw new PeppaError(m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login })); }); } @@ -371,7 +373,7 @@ export async function grantRepoAccessToMembers(f: FormData) { await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); const r = await grantRepoAccess(db, user, p); - if (r.failed.length) throw new PeppaError(`Не удалось выдать доступ к репозиторию: ${r.failed.join(", ")} — нет прав администратора в Gitea, добавьте соавторов вручную`); + if (r.failed.length) throw new PeppaError(m("Не удалось выдать доступ к репозиторию: {logins} — нет прав администратора в Gitea, добавьте соавторов вручную", { logins: r.failed.join(", ") })); }); } @@ -427,7 +429,7 @@ export async function pairTelegram(f: FormData) { const token = loadEnv().TELEGRAM_BOT_TOKEN; // PEP-85: the user's own bot if they connected one, else the platform's shared bot. const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username; - if (!token || !username) throw new PeppaError("Telegram-бот Пеппы не запущен"); + if (!token || !username) throw new PeppaError(m("Telegram-бот Пеппы не запущен")); return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`; }); } @@ -457,7 +459,7 @@ export async function saveNotifyPrefsAction(f: FormData) { const events = { ...d.events }; for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" }; const tz = str(f, "timezone") || cur.timezone; - if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`); + if (!isValidTimezone(tz)) throw new PeppaError(m("Неизвестная таймзона: {tz}", { tz })); const shown = f.getAll("projectShown").map(Number); const enabled = new Set(f.getAll("project").map(Number)); // Projects not on the form (no access any more) keep their old state. @@ -497,9 +499,10 @@ export async function deletePushSubscriptionAction(endpoint: string) { export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> { const user = asWebActor(await requireUser()); const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint); - if (!sub) return { ok: false, error: "Этот браузер не подписан" }; + const t = await getT(); + if (!sub) return { ok: false, error: t("Этот браузер не подписан") }; const prefs = await getNotifyPrefs(db, user.id); - const r = await sendWebPush(db, sub, { title: "Пеппа", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound }); + const r = await sendWebPush(db, sub, { title: PRODUCT_NAME, body: t("Уведомления в этом браузере работают ✅"), url: "/settings#notifications", tag: "test", sound: prefs.sound }); if (r.ok) return { ok: true }; if (r.gone) await deletePushSubscription(db, user.id, endpoint); return { ok: false, error: r.error }; @@ -510,7 +513,7 @@ export async function testPushAction(endpoint: string): Promise<{ ok: boolean; e async function incidentInProject(userId: number, f: FormData) { const p = await projectForUser(db, userId, Number(str(f, "projectId"))); const i = await getIncident(db, Number(str(f, "incidentId"))); - if (i.projectId !== p.id) throw new PeppaError("Не найдено"); + if (i.projectId !== p.id) throw new PeppaError(m("Не найдено")); return i; } @@ -518,7 +521,7 @@ export async function connectErrorTrackingAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); - if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта"); + if (!(await managesProject(db, user, p))) throw new PeppaError(m("Подключает владелец проекта")); await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase()); }); } @@ -556,7 +559,7 @@ export async function decideIncidentAction(f: FormData) { await attempt(f, async () => { const i = await incidentInProject(user.id, f); const action = str(f, "action"); - if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError("Неизвестное решение"); + if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError(m("Неизвестное решение")); await decideIncident(db, i.id, action, user.login); }); } @@ -574,7 +577,7 @@ export async function resolveIncidentAction(f: FormData) { /** Superadmin-only actions: everybody else gets "not found", nothing changes. */ async function requireSuperadmin() { const user = asWebActor(await requireUser()); - if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено"); + if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Не найдено")); return user; } @@ -584,8 +587,8 @@ export async function setUserDisabledAction(f: FormData) { await attempt(f, async () => { const admin = await requireSuperadmin(); const u = await getUser(db, Number(str(f, "userId"))); - if (!u) throw new PeppaError("Не найдено"); - if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя"); + if (!u) throw new PeppaError(m("Не найдено")); + if (u.id === admin.id) throw new PeppaError(m("Нельзя отключить самого себя")); await setUserDisabled(db, u.id, str(f, "disabled") === "1"); }); } @@ -602,7 +605,7 @@ export async function saveTaskBudgetAction(f: FormData) { const mode = str(f, "mode"); const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f); await setTaskBudget(db, ref.task.id, budget); - await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } }); + await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } }); // i18n-ignore — stored value await budgetChanged(db, ref.task.id); }); } @@ -688,7 +691,7 @@ export async function connectOwnSubscriptionAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const kind = str(f, "kind") as OwnSubscriptionKind; - if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить"); + if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError(m("Выберите, что подключить")); const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? "")); }); diff --git a/apps/web/app/(app)/board-actions.ts b/apps/web/app/(app)/board-actions.ts index 7556b808..61b0baca 100644 --- a/apps/web/app/(app)/board-actions.ts +++ b/apps/web/app/(app)/board-actions.ts @@ -8,6 +8,7 @@ import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; +import { m } from "@peppa/shared/i18n"; const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); @@ -16,7 +17,7 @@ async function attempt(f: FormData, fn: () => Promise): Promise [orig, i + 1])); const stories: PlannedStory[] = kept.map((i) => { const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => { if (typeof d !== "number") return d; - if (!renum.has(d)) throw new PeppaError(`Стори ${i} зависит от №${d}, которую вы сняли — уберите зависимость или оставьте стори`); + if (!renum.has(d)) throw new PeppaError(m("Стори {i} зависит от №{d}, которую вы сняли — уберите зависимость или оставьте стори", { i, d })); return renum.get(d)!; }); return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps }; diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 8b915adf..cf067537 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import { PRODUCT_NAME } from "@peppa/shared/i18n"; import { notFound } from "next/navigation"; import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react"; import { chatMessagesView, chatThreads, chatTtlMs, getSetting, listChats, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core"; @@ -14,6 +15,7 @@ import { Textarea } from "@/components/ui/input"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { cn } from "@/lib/utils"; +import { getT } from "@/lib/i18n"; import { linkChatAction, postChatAction, unlinkChatAction } from "../actions"; type Params = { error?: string; thread?: string; link?: string }; @@ -23,6 +25,7 @@ const CHANNEL = "channel"; /** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */ export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise }) { const user = await requireUser(); + const t = await getT(); const { chat: slug } = await params; const { error, thread: rawThread, link } = await searchParams; // Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too). @@ -35,7 +38,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi const threads = master ? [] : await chatThreads(db, chat.id); const messages = master ? await masterFeed(db, user, { limit: 150 }) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 }); - const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null; + const current = thread ? (threads.find((th) => th.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null; // Live state of the questions in view (answer buttons, «отвечено» marks). const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null); @@ -55,10 +58,10 @@ export default async function ChatPage({ params, searchParams }: { params: Promi const placeholder = master ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : taskThread - ? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу" + ? t("Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу") : thread - ? "Заметка в тред или команда /help" - : "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress"; + ? t("Заметка в тред или команда /help") + : t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress"); const aside = (
    @@ -67,45 +70,48 @@ export default async function ChatPage({ params, searchParams }: { params: Promi {chat.tgTitle ? ( <>

    - Связан с группой {chat.tgTitle}. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}. + {t("Связан с группой")} {chat.tgTitle}.{" "} + {master + ? t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред.") + : t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред (в треде стори — агенту).")}

    ) : link ? (
    -

    Код действует 10 минут.

    +

    {t("Код действует 10 минут.")}

    {bot && ( - Добавить @{bot} в группу → + {t("Добавить @{bot} в группу →", { bot })} )} -

    Или добавь бота в группу сам и отправь там:

    +

    {t("Или добавь бота в группу сам и отправь там:")}

    /link {link}
    ) : ( <> -

    {master ? "Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам." : "Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}

    +

    {master ? t("Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам.") : t("Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение.")}

    )} -

    Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только ты)" : "проекту"}.

    +

    {t("Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {target}.", { target: master ? t("мастер-чату (только ты)") : t("проекту") })}

  • -

    Как это устроено

    -

    {master ? "Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM." : "Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной."}

    -

    Переписка хранится {ttlDays} дн.; стори, вопросы и события остаются на своих страницах.

    +

    {t("Как это устроено")}

    +

    {master ? t("Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM.") : t("Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной.")}

    +

    {t("Переписка хранится {n} дн.; стори, вопросы и события остаются на своих страницах.", { n: ttlDays })}

    ); @@ -114,23 +120,23 @@ export default async function ChatPage({ params, searchParams }: { params: Promi - Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту. + {t("Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.")} -