From 8c702b1d4e13fb11a1951f8371f17c378ebe93e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 23:42:15 +0500 Subject: [PATCH 001/404] PEP-87: the watchdog does not remind or escalate the analyst's self-closing questions Co-Authored-By: Claude Fable 5.2 --- packages/cli/src/index.ts | 2 ++ packages/runner/src/recovery.ts | 3 +++ packages/runner/src/tmux.ts | 30 ++++++++++++++++++++++++++++ packages/testkit/test/intake.test.ts | 5 +++++ 4 files changed, 40 insertions(+) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 19693b9d..24fbec79 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -643,6 +643,8 @@ async function main(): Promise { const ob = await outboxStats(db); console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`); console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`); + const foreign = await tmux.foreignServerEnv().catch(() => []); + if (foreign.length) console.log(`⚠ в окружении tmux-сервера чужие переменные: ${foreign.join(", ")} — агенты их унаследуют; очистятся при следующем запуске раннера или: ${foreign.map((n) => `tmux set-environment -g -u ${n}`).join("; ")}`); const paired = new Set((await adminRecipients(db)).map((u) => u.login)); const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`); console.log(`админы: ${admins.join(", ") || "нет"}`); diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 4d156bdb..86769fa2 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -19,6 +19,7 @@ import { setSetting, updateSession, type SessionView, + getIntakeState, } from "@peppa/core"; import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; @@ -227,6 +228,8 @@ export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; .where(and(isNull(questions.answeredAt), inArray(questions.kind, [...REMIND_KINDS]), gestDay(now))); let sent = 0; for (const { q, projectKey, taskNumber } of rows) { + // PEP-87: the analyst's questions close themselves at their deadline (PEP-84) — no nagging. + if (q.taskId && (await getIntakeState(db, q.taskId))?.questionId === q.id) continue; const age = now - q.createdAt.getTime(); const ageMin = Math.round(age / 60_000); const n = q.reminders; diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 71ad3c8c..a63468e7 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -41,6 +41,35 @@ export interface NewTmuxSession { width?: number; } +/** + * PEP-69: names that must never come from a tmux server's global environment. Every session + * inherits it, and a server started by some test run or tool shell carries that process's + * GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place. + * What an agent needs is passed per session (`new-session -e`) or read from `.env`. + */ +const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/; + +/** Foreign variables in the global environment of the tmux server (default server only). */ +export async function foreignServerEnv(p: Pane = { name: "" }): Promise { + // A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it. + if (process.env.PEPPA_TMUX_SOCKET) return []; + let out: string; + try { + out = await tmuxOn(p, ["show-environment", "-g"]); + } catch (e) { + if (e instanceof HostUnreachable) throw e; + return []; // no server running + } + return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k)); +} + +/** Removes them from the server's global environment; returns the names removed. */ +export async function scrubServerEnv(p: Pane = { name: "" }): Promise { + const names = await foreignServerEnv(p); + for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]); + return names; +} + export async function newSession(s: NewTmuxSession): Promise { if (isRunnerClient()) return viaService("newSession", [s]); const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]); @@ -48,6 +77,7 @@ export async function newSession(s: NewTmuxSession): Promise { // Keep the server up when its last session ends: otherwise a session created while the // previous last one is being killed can land on a server that is shutting down. await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]); + await scrubServerEnv(p).catch(() => {}); // PEP-69 await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]); // Keep the pane after claude exits so the watchdog can read the exit status. await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]); diff --git a/packages/testkit/test/intake.test.ts b/packages/testkit/test/intake.test.ts index 2e235a7b..b0829fb5 100644 --- a/packages/testkit/test/intake.test.ts +++ b/packages/testkit/test/intake.test.ts @@ -68,6 +68,11 @@ describe("Продакт и аналитик", () => { assert.equal(q!.id, state.questionId); assert.match(q!.text, /Нужна ли мобильная версия\?\n\s+По умолчанию: Да, страница открывается с телефона/); + // PEP-87: the question closes itself at the deadline, so the watchdog does not nag about it. + const cfg = await runner.getWatchdogSettings(db); + assert.equal(await runner.remindTick(db, { now: new Date(Date.now() + 3 * 3600_000), cfg, log: () => {} }), 0); + assert.equal((await core.getQuestion(db, q!.id)).reminders, 0); + // The PM answers: the analyst finishes with the answer and asks nothing more. await runner.answerAndDeliver(db, q!.id, "Мобильная не нужна, только ноутбук", "web"); assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "finalize"); -- 2.45.2 From b47d2e80228ef933272ae344f29eb2d2ea033038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 23:43:58 +0500 Subject: [PATCH 002/404] PEP-87: drop another story's unfinished edits swept into this branch Co-Authored-By: Claude Fable 5.2 --- packages/cli/src/index.ts | 2 -- packages/runner/src/tmux.ts | 30 ------------------------------ 2 files changed, 32 deletions(-) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 24fbec79..19693b9d 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -643,8 +643,6 @@ async function main(): Promise { const ob = await outboxStats(db); console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`); console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`); - const foreign = await tmux.foreignServerEnv().catch(() => []); - if (foreign.length) console.log(`⚠ в окружении tmux-сервера чужие переменные: ${foreign.join(", ")} — агенты их унаследуют; очистятся при следующем запуске раннера или: ${foreign.map((n) => `tmux set-environment -g -u ${n}`).join("; ")}`); const paired = new Set((await adminRecipients(db)).map((u) => u.login)); const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`); console.log(`админы: ${admins.join(", ") || "нет"}`); diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index a63468e7..71ad3c8c 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -41,35 +41,6 @@ export interface NewTmuxSession { width?: number; } -/** - * PEP-69: names that must never come from a tmux server's global environment. Every session - * inherits it, and a server started by some test run or tool shell carries that process's - * GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place. - * What an agent needs is passed per session (`new-session -e`) or read from `.env`. - */ -const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/; - -/** Foreign variables in the global environment of the tmux server (default server only). */ -export async function foreignServerEnv(p: Pane = { name: "" }): Promise { - // A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it. - if (process.env.PEPPA_TMUX_SOCKET) return []; - let out: string; - try { - out = await tmuxOn(p, ["show-environment", "-g"]); - } catch (e) { - if (e instanceof HostUnreachable) throw e; - return []; // no server running - } - return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k)); -} - -/** Removes them from the server's global environment; returns the names removed. */ -export async function scrubServerEnv(p: Pane = { name: "" }): Promise { - const names = await foreignServerEnv(p); - for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]); - return names; -} - export async function newSession(s: NewTmuxSession): Promise { if (isRunnerClient()) return viaService("newSession", [s]); const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]); @@ -77,7 +48,6 @@ export async function newSession(s: NewTmuxSession): Promise { // Keep the server up when its last session ends: otherwise a session created while the // previous last one is being killed can land on a server that is shutting down. await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]); - await scrubServerEnv(p).catch(() => {}); // PEP-69 await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]); // Keep the pane after claude exits so the watchdog can read the exit status. await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]); -- 2.45.2 From 19f95773495d023afb8659a05c24b5aafabf9cd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 23:50:13 +0500 Subject: [PATCH 003/404] =?UTF-8?q?PEP-87:=20OpenSpec=20change=20=E2=80=94?= =?UTF-8?q?=20the=20watchdog=20skips=20the=20analyst's=20questions=20(arch?= =?UTF-8?q?ived=20into=20watchdog-recovery)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../design.md | 17 ++++++++++++++ .../proposal.md | 23 +++++++++++++++++++ .../specs/watchdog-recovery/spec.md | 18 +++++++++++++++ .../tasks.md | 4 ++++ openspec/specs/watchdog-recovery/spec.md | 9 +++++++- 5 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md new file mode 100644 index 00000000..4c944a70 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md @@ -0,0 +1,17 @@ +## Context + +`remindTick` (runner/recovery.ts) выбирает неотвеченные вопросы видов question/permission/approval моложе суток. Вопрос аналитика — обычный `askPm`, его id хранится в состоянии приёма стори (`intake.task:` → `questionId`), и `intakeTick` сам закрывает его по сроку. + +## Goals / Non-Goals + +- Цель: по вопросу аналитика не уходит ни напоминание, ни эскалация. +- Не цель: менять сроки приёма, тихие часы или первое уведомление о вопросе. + +## Decisions + +- Признак «вопрос аналитика» — `getIntakeState(db, q.taskId)?.questionId === q.id`. Отдельной колонки или вида вопроса не вводим: состояние приёма уже источник правды, миграция не нужна. Альтернатива (новый `kind`) затронула бы бота, чаты и уведомления. +- Проверка стоит в начале цикла, до claim счётчика `reminders`: он остаётся 0, и, если вопрос перестанет быть вопросом аналитика, обычные правила применятся к нему с начала. + +## Risks / Trade-offs + +- Лишний запрос `settings` на каждый открытый вопрос за тик — открытых вопросов единицы, тик раз в 30 с. diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md new file mode 100644 index 00000000..2aaf14c4 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md @@ -0,0 +1,23 @@ +## Why + +Вопрос аналитика (PEP-84) закрывается сам по сроку `waitMin`, а срок сдвигается за тихие часы. Вачдог при этом напоминал о нём каждые `remindMin` и эскалировал админам (случай: демо в SBX ночью — срок сдвинулся до утра, напоминания шли каждые полчаса). + +## What Changes + +- `remindTick` пропускает открытый вопрос аналитика (вопрос из состояния приёма стори): ни напоминаний аудитории, ни эскалации админам. +- Остальные вопросы (агент, разрешения, одобрения) напоминаются как раньше. + +## Capabilities + +### New Capabilities + +Нет. + +### Modified Capabilities + +- `watchdog-recovery`: требование «Напоминание и эскалация вопросов» — исключение для вопросов аналитика. + +## Impact + +- `packages/runner/src/recovery.ts` (`remindTick`), тест `packages/testkit/test/intake.test.ts`. +- Схема БД, API и настройки не меняются. diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md new file mode 100644 index 00000000..df0f1b92 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md @@ -0,0 +1,18 @@ +## MODIFIED Requirements + +### Requirement: Напоминание и эскалация вопросов +Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. О вопросе аналитика (приём стори перед бэклогом), который закрывается сам по сроку, вачдог SHALL NOT напоминать и SHALL NOT эскалировать его админам. + +#### Scenario: Вопрос висит +- **GIVEN** агент спросил PM в 10:00 +- **WHEN** в 10:30 ответа нет +- **THEN** участники проекта получают «⏰ Вопрос #N ждёт ответа 30 мин» +- **AND** в 11:00 — второе напоминание, в 12:00 — эскалация админам +- **AND** повторные тики вачдога новых сообщений не создают + +#### Scenario: Вопрос аналитика +- **GIVEN** аналитик спросил PM по новой стори в 10:00 и ждёт ответа до срока приёма +- **WHEN** в 13:00 ответа нет и тикает вачдог +- **THEN** участники проекта не получают «⏰ Вопрос #N ждёт ответа» +- **AND** админы платформы не получают эскалацию +- **AND** вопрос остаётся открытым до своего срока diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md new file mode 100644 index 00000000..aa50280b --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md @@ -0,0 +1,4 @@ +## 1. Вачдог + +- [x] 1.1 `remindTick` пропускает вопрос, чей id записан в состоянии приёма стори +- [x] 1.2 Тест сценария «Вопрос аналитика» в `intake.test.ts`: через 3 часа напоминаний нет, `reminders` = 0 diff --git a/openspec/specs/watchdog-recovery/spec.md b/openspec/specs/watchdog-recovery/spec.md index b014e587..0a60b7a4 100644 --- a/openspec/specs/watchdog-recovery/spec.md +++ b/openspec/specs/watchdog-recovery/spec.md @@ -38,7 +38,7 @@ - **THEN** tmux-сессия убита, раннер продолжает разговор заново, алерт закрыт ### Requirement: Напоминание и эскалация вопросов -Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. +Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. О вопросе аналитика (приём стори перед бэклогом), который закрывается сам по сроку, вачдог SHALL NOT напоминать и SHALL NOT эскалировать его админам. #### Scenario: Вопрос висит - **GIVEN** агент спросил PM в 10:00 @@ -47,6 +47,13 @@ - **AND** в 11:00 — второе напоминание, в 12:00 — эскалация админам - **AND** повторные тики вачдога новых сообщений не создают +#### Scenario: Вопрос аналитика +- **GIVEN** аналитик спросил PM по новой стори в 10:00 и ждёт ответа до срока приёма +- **WHEN** в 13:00 ответа нет и тикает вачдог +- **THEN** участники проекта не получают «⏰ Вопрос #N ждёт ответа» +- **AND** админы платформы не получают эскалацию +- **AND** вопрос остаётся открытым до своего срока + ### Requirement: Уборка давних waiting_input Раннер стори в `waiting_input` без открытых вопросов дольше `idleStopHours` SHALL останавливаться с сообщением PM. -- 2.45.2 From 03d358f9f2b20b8098b61801dd634b112099d33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 23:44:33 +0500 Subject: [PATCH 004/404] PEP-69: scrub foreign env from the tmux server before starting runners; warn in peppa status Co-Authored-By: Claude Sonnet 5.5 --- .peppa/memory.md | 1 + .../design.md | 2 + .../proposal.md | 9 +++ .../specs/agent-runner/spec.md | 22 +++++ .../tasks.md | 4 + .../changes/pep-4-gitea-org/.openspec.yaml | 2 + openspec/changes/pep-4-gitea-org/design.md | 80 +++++++++++++++++++ openspec/changes/pep-4-gitea-org/proposal.md | 46 +++++++++++ .../pep-4-gitea-org/specs/peppa-ci/spec.md | 48 +++++++++++ .../specs/project-provisioning/spec.md | 38 +++++++++ openspec/changes/pep-4-gitea-org/tasks.md | 27 +++++++ openspec/specs/agent-runner/spec.md | 25 ++++++ packages/cli/src/index.ts | 4 +- packages/runner/src/tmux.ts | 30 +++++++ packages/testkit/test/tmux-env.test.ts | 40 ++++++++++ 15 files changed, 377 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md create mode 100644 openspec/changes/pep-4-gitea-org/.openspec.yaml create mode 100644 openspec/changes/pep-4-gitea-org/design.md create mode 100644 openspec/changes/pep-4-gitea-org/proposal.md create mode 100644 openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md create mode 100644 openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md create mode 100644 openspec/changes/pep-4-gitea-org/tasks.md create mode 100644 openspec/specs/agent-runner/spec.md create mode 100644 packages/testkit/test/tmux-env.test.ts diff --git a/.peppa/memory.md b/.peppa/memory.md index f1299459..4e1d2691 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -8,3 +8,4 @@ ## Решения - Чаты (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. diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md new file mode 100644 index 00000000..3c3e5da5 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md @@ -0,0 +1,2 @@ +# Дизайн +Выбрано: чистка глобального окружения при `newSession` (после `start-server`), а не отдельный сокет `-L peppa` — смена сокета оторвала бы живые раннеры, ушедшие на сервер по умолчанию, и ломает `tmux attach` PM. Чистка идемпотентна и дешёвая (`show-environment -g` + `set-environment -g -u`). Всё нужное агенту уже передаётся через `-e` (`PEPPA_SESSION_ID`, `PEPPA_DB`, `PEPPA_HOME`, подписка), остальное MCP берёт из `.env`. Правка `load-env.sh` не годится: тесты нарочно ставят `GITEA_TOKEN=""`. Для выделенного сокета чистки нет — это сервер владельца (тесты), моки CLI читают свои переменные оттуда. diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md new file mode 100644 index 00000000..2c8735f4 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md @@ -0,0 +1,9 @@ +# PEP-69: агенты не наследуют окружение чужого tmux-сервера + +## Почему +Раннеры живут на tmux-сервере по умолчанию. Если его запустил тестовый прогон или оболочка Claude Code, глобальное окружение сервера (GITEA_URL, PEPPA_HOME, PEPPA_CLAUDE_BIN, DATABASE_URL, пустой GITEA_TOKEN) наследуют все сессии, и MCP агента ломается («GITEA_TOKEN is not set»). + +## Что меняется +- Перед созданием сессии раннер-сервис вычищает из глобального окружения tmux-сервера переменные `GITEA_*`, `PEPPA_*`, `MOCK_*`, `DATABASE_URL`; нужное агенту уходит явно (`new-session -e`) или читается из `.env`. +- `peppa status` предупреждает о чужих переменных в окружении сервера. +- Выделенный сокет (`PEPPA_TMUX_SOCKET`, тесты) не трогается. diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md new file mode 100644 index 00000000..9bb397b6 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md @@ -0,0 +1,22 @@ +# Spec Delta: agent-runner + +## ADDED Requirements + +### Requirement: Окружение раннера не наследуется от чужого tmux-сервера +Раннер SHALL запускать агентов так, чтобы они не получали `GITEA_*`, `PEPPA_*`, `MOCK_*`, `DATABASE_URL` из глобального окружения tmux-сервера по умолчанию, а `peppa status` SHALL предупреждать, если такие переменные там есть. + +#### Scenario: Сервер запущен тестовой оболочкой +- **GIVEN** tmux-сервер по умолчанию с глобальной переменной `GITEA_URL=http://127.0.0.1:9` +- **WHEN** раннер-сервис запускает сессию стори +- **THEN** `GITEA_URL` удалена из глобального окружения сервера +- **AND** переменные сессии (`PEPPA_SESSION_ID`) переданы явно + +#### Scenario: Предупреждение в статусе +- **GIVEN** в окружении tmux-сервера есть `MOCK_X` +- **WHEN** PM запускает `peppa status` +- **THEN** выводится предупреждение со списком переменных и командой очистки + +#### Scenario: Выделенный сокет не трогается +- **GIVEN** задан `PEPPA_TMUX_SOCKET` +- **WHEN** запускается сессия +- **THEN** окружение этого сервера не чистится diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md new file mode 100644 index 00000000..b38cba00 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md @@ -0,0 +1,4 @@ +## 1. Реализация +- [x] 1.1 `tmux.foreignServerEnv` / `scrubServerEnv`, чистка в `newSession` +- [x] 1.2 Предупреждение в `peppa status` +- [x] 1.3 Тест `tmux-env.test.ts` diff --git a/openspec/changes/pep-4-gitea-org/.openspec.yaml b/openspec/changes/pep-4-gitea-org/.openspec.yaml new file mode 100644 index 00000000..be831cee --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-14 diff --git a/openspec/changes/pep-4-gitea-org/design.md b/openspec/changes/pep-4-gitea-org/design.md new file mode 100644 index 00000000..3a234439 --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/design.md @@ -0,0 +1,80 @@ +# Design + +## Context + +Мотивация — в proposal.md. Что есть сейчас (проверено 2026-11-14, Gitea 1.22.6): + +- Организации `peppa` нет, имя свободно (ни пользователя, ни организации). `peppa-bot` не админ + Gitea и не состоит ни в одной организации; может ли он создавать организации — видно только + по ответу на `POST /orgs`. +- В пространстве `peppa-bot` 12 репозиториев: `peppa`, `template` (приватный, шаблон) и 10 + проектов пользователей. В БД у всех 11 проектов `gitea_owner = peppa-bot`. +- Раннер CI зарегистрирован на уровне пользователя `peppa-bot`; `setupCi` для проекта с другим + владельцем сам регистрирует раннер на репозиторий (метка `repo---`). +- Адрес `peppa-bot/peppa` вшит в `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`; + шаблон — `GITEA_TEMPLATE_REPO` (env, умолчание в `env.ts`, `push-template.sh`, `.env.example`). +- Открыт PR #79 (`task/pep-87`), идут сессии PEP — работа параллельными волнами. + +## Goals / Non-Goals + +**Goals:** +- `peppa/peppa` и `peppa/template` работают как раньше: CI, вебхуки, превью, правила агентов. +- Перенос повторяем и проверяем кодом (команда + тест на `mock-gitea`), а не разовым curl. + +**Non-Goals:** +- Перенос проектов пользователей из `peppa-bot`; смена пространства для новых проектов (PEP-68). +- Команды и права внутри организации сверх Owners; официальный прод (PEP-18). +- UI/MCP для переноса — только CLI администратора (как `project visibility`). + +## Decisions + +1. **Организацию создаёт `peppa-bot` (`POST /orgs`, visibility public)**, если Gitea разрешит; + 403 — просим PM создать её админом и добавить `peppa-bot` в Owners. Давать боту права админа + Gitea не нужно и не хочется: ему достаточно быть владельцем одной организации. + Вторым владельцем добавляем учётку PM в Gitea — организация не должна держаться на одном боте. +2. **Перенос — операция `transferProject` в runner + `peppa project transfer`**, а не ручные + шаги. Порядок: проверить пространство и отсутствие `/` → `POST + /repos/{o}/{r}/transfer` (владелец организации переносит сразу, без подтверждения) → обновить + `projects.gitea_owner` → `git remote set-url origin` в рабочей копии (worktree делят конфиг) → + `setupCi` (раннер на репозиторий, секрет, вебхук) → событие `repo_transferred`. Каждый шаг + идемпотентен: если репозиторий уже на новом месте, шаг Gitea пропускается. + Альтернатива — UPDATE в БД руками — не оставляет следа в журнале и забывает раннер. +3. **Раннер — на репозиторий** (существующий путь `setupCi`), не на организацию: раннер с + docker.sock хоста не должен автоматически обслуживать любой будущий репозиторий организации. +4. **`GITEA_PLATFORM_REPO`** (env, умолчание `peppa/peppa`) вместо трёх вшитых строк. Брать адрес + из проекта `PEPPA_PLATFORM_KEY` в БД нельзя: скрипты релиза и `ci.sh` работают без БД. +5. **Шаблон** — не проект Пеппы, переносится тем же вызовом клиента из задачи разово + (`peppa project transfer` его не знает); затем `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, + `scripts/push-template.sh` и проверка `get_rules`. Остаётся приватным и `template: true`. +6. **Порядок на живой системе**: сначала мерж кода (умолчания новые, но `.env` ещё держит + старые адреса — ничего не ломается), затем перенос одной командой, сразу `.env` и рестарт + сервисов. Редиректы Gitea покрывают окно между шагами и чужие клоны. + +## Risks / Trade-offs + +- [Редирект не действует на API-запросы Пеппы по старому адресу] → адрес проекта в БД меняется + в той же команде, сразу после переноса; окно — секунды. +- [Живые сессии PEP и PR #79 в момент переноса] → git идёт через редирект; `origin` общей + рабочей копии и worktree обновляются командой. Контейнерные сессии (релей git пускает только + `owner/repo` проекта) — на PEP сейчас не используются; проверить перед переносом. +- [Секрет Actions и вебхук могут не пережить перенос] → `setupCi` ставит их заново в любом случае. +- [Раннер уровня `peppa-bot` перестаёт видеть `peppa/peppa`] → регистрация на репозиторий — часть + команды; проверка — зелёный прогон CI на PR этой стори после переноса. +- [Кто-то создаст `peppa-bot/peppa` заново и сломает редирект] → не создавать; записать в память. +- [Bare-клон будущего прода `~/peppa/repo.git`] → `PEPPA_RELEASE_REMOTE` по умолчанию от + `GITEA_PLATFORM_REPO`; существующему клону — `git remote set-url`. + +## Migration Plan + +1. PR с кодом и тестами — зелёный CI на старом адресе, мерж. +2. Организация `peppa` (бот или PM), `peppa-bot` и PM — Owners. +3. `peppa db backup`, `peppa project transfer PEP peppa`; перенос `template`. +4. `.env`: `GITEA_TEMPLATE_REPO=peppa/template`; рестарт web/bot/watchdog; `peppa status`. +5. Проверки: `git fetch` в рабочей копии, `get_rules`, пробный PR/пуш → проверки `peppa/*` + зелёные и видны на карточке, футер ведёт на `peppa/peppa`. + +Откат: `peppa project transfer PEP peppa-bot`, обратный перенос `template`, прежний `.env`. + +## Open Questions + +- Логин PM в Gitea для второго владельца организации — нужен только на шаге 2, на код не влияет. diff --git a/openspec/changes/pep-4-gitea-org/proposal.md b/openspec/changes/pep-4-gitea-org/proposal.md new file mode 100644 index 00000000..d2219ae4 --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/proposal.md @@ -0,0 +1,46 @@ +# Proposal + +## Why + +Репозитории платформы (`peppa-bot/peppa`, `peppa-bot/template`) лежат в личном пространстве +служебной учётки `peppa-bot` вперемешку с проектами пользователей без Gitea (PEP-68). Платформа +мультипользовательская (эпик #2): её код и шаблон должны принадлежать организации `peppa`, где +владельцев несколько и права задаются командами, а не паролем одного бота. + +## What Changes + +- В Gitea создаётся организация `peppa` (публичная); `peppa-bot` — в команде Owners. +- `peppa-bot/peppa` → `peppa/peppa`, `peppa-bot/template` → `peppa/template` (перенос Gitea: + история, PR, issues, вебхуки и секреты Actions сохраняются, старые адреса редиректят). +- Новая команда `peppa project transfer ` — переносит репозиторий проекта в другое + пространство Gitea и чинит всё, что от адреса зависит: запись проекта, `origin` рабочей копии, + раннер CI, секрет и вебхук. Перенос `peppa` делается ею же; повторный запуск безопасен. +- `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; адрес репозитория платформы перестаёт быть + вшитым (`peppa-bot/peppa` в футере, `scripts/ci.sh`, `scripts/peppa-release.sh`) — одна + настройка `GITEA_PLATFORM_REPO` (по умолчанию `peppa/peppa`). +- Живая система: `.env`, `origin` рабочей копии, раннер CI на `peppa/peppa`, документация. +- Проекты пользователей в пространстве `peppa-bot` **не переносятся** (вне scope). + +## Capabilities + +### New Capabilities + +Нет. + +### Modified Capabilities +- `project-provisioning`: новое требование — перенос репозитория проекта в другое пространство + Gitea командой CLI. +- `peppa-ci`: репозиторий платформы в требованиях — `peppa/peppa` вместо `peppa-bot/peppa`. + +## Impact + +- Gitea: новая организация, перенос двух репозиториев (обратим обратным переносом, но адреса + меняются для всех клонов); нужно право `peppa-bot` создавать организации **или** организация, + созданная админом Gitea с `peppa-bot` в Owners. +- Код: `packages/core/src/gitea.ts` (перенос), `packages/runner` (новая операция, `ci.ts`), + `packages/cli`, `packages/shared/src/env.ts`, `apps/web/components/Footer.tsx`, `scripts/ci.sh`, + `scripts/peppa-release.sh`, `scripts/push-template.sh`, `.env.example`, `mock-gitea`. +- Данные: `projects.gitea_owner` проекта PEP (`peppa-bot` → `peppa`), без миграций схемы. +- CI: раннер уровня пользователя `peppa-bot` перестаёт покрывать `peppa/peppa` — регистрация на + репозиторий. Открытые PR (сейчас #79) и живые сессии PEP продолжают работать через редирект. +- Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help`. diff --git a/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md new file mode 100644 index 00000000..ecf49c5d --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md @@ -0,0 +1,48 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Статус проверки в PR +`scripts/ci.sh --pr ` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория платформы +(`GITEA_PLATFORM_REPO`, по умолчанию `peppa/peppa`) в отдельном +временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем +`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. + +#### Scenario: Зелёный PR +- **GIVEN** открыт PR 15, его голова проходит все проверки +- **WHEN** запускается `scripts/ci.sh --pr 15` +- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in min» +- **AND** лог прогона лежит в `~/.peppa/ci/.log`, временный worktree удалён + +#### Scenario: Красный PR +- **GIVEN** открыт PR 16, в его голове падает e2e +- **WHEN** запускается `scripts/ci.sh --pr 16` +- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу +- **AND** код выхода 1 + +#### Scenario: Нет такого PR +- **GIVEN** в репозитории нет PR 999 +- **WHEN** запускается `scripts/ci.sh --pr 999` +- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 + +### Requirement: Проверки на каждый PR в Gitea Actions +Workflow `.gitea/workflows/ci.yml` репозитория `peppa/peppa` SHALL на каждый PR из ветки этого +репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57), +с тестовой БД `peppa_test_ci_r` на Postgres хоста, и выставлять статус коммита +`peppa-ci / ci (pull_request)`; PR из форков не запускаются. + +#### Scenario: PR зелёный +- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят +- **WHEN** ветка пушится +- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in ms») +- **AND** БД `peppa_test_ci_r` после job не существует + +#### Scenario: PR красный +- **GIVEN** в голове PR падает один e2e-тест +- **WHEN** job доходит до шага `ci` +- **THEN** статус = `failure` («Failing after ms»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста + +#### Scenario: PR из форка +- **GIVEN** PR открыт из форка репозитория +- **WHEN** Gitea обрабатывает событие `pull_request` +- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется diff --git a/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md new file mode 100644 index 00000000..d7cc555a --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md @@ -0,0 +1,38 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Перенос репозитория проекта в другое пространство +Команда `peppa project transfer ` SHALL переносить репозиторий проекта в пространство +`` (организация или пользователь Gitea) и приводить проект в рабочее состояние по новому +адресу: адрес проекта в Пеппе, `origin` рабочей копии, раннер CI, секрет и вебхук. Повторный запуск +после частичного сбоя SHALL доводить перенос до конца без ошибки. + +#### Scenario: Перенос в организацию +- **GIVEN** проект `DEMO` с репозиторием `peppa-bot/demo` и организация `acme`, где `peppa-bot` — владелец +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** репозиторий доступен как `acme/demo`, вывод — «DEMO: peppa-bot/demo → acme/demo» +- **AND** страница проекта в вебе ссылается на `acme/demo` +- **AND** `git remote get-url origin` в рабочей копии оканчивается на `/acme/demo.git` +- **AND** в журнале проекта есть событие «репозиторий перенесён» со старым и новым адресом + +#### Scenario: CI после переноса +- **GIVEN** проект `DEMO` с подключённым CI перенесён из `peppa-bot/demo` в `acme/demo` +- **WHEN** в `acme/demo` открывается PR +- **THEN** проверки `peppa/*` выполняются на раннере Пеппы и их отчёты приходят на карточку стори + +#### Scenario: Повторный запуск +- **GIVEN** репозиторий проекта `DEMO` уже находится в `acme/demo`, а в Пеппе записан `peppa-bot/demo` +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** перенос в Gitea не запрашивается, адрес проекта и `origin` становятся `acme/demo`, код выхода 0 + +#### Scenario: Пространства нет или нет прав +- **GIVEN** организации `nope` в Gitea нет +- **WHEN** выполняется `peppa project transfer DEMO nope` +- **THEN** выводится «Пространство nope не найдено или у peppa-bot нет прав создавать в нём репозитории», код выхода 1 +- **AND** репозиторий остаётся `peppa-bot/demo`, адрес проекта в Пеппе не меняется + +#### Scenario: В пространстве уже есть такой репозиторий +- **GIVEN** в организации `acme` уже есть другой репозиторий `demo` +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** выводится «Репозиторий acme/demo уже существует», код выхода 1, ничего не меняется diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/pep-4-gitea-org/tasks.md new file mode 100644 index 00000000..f488d3d8 --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/tasks.md @@ -0,0 +1,27 @@ +# Tasks + +## 1. Перенос репозитория проекта (код) + +- [ ] 1.1 `GiteaClient`: `transferRepo(owner, repo, newOwner)` и проверка пространства (организация/пользователь, право создавать репозитории); `mock-gitea` — `POST /repos/{o}/{r}/transfer` (404 пространства, 409 занятое имя, редирект старого адреса) — проверка: юнит-вызовы мока в новом тесте +- [ ] 1.2 `transferProject` в `packages/runner` (перенос → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` → событие `repo_transferred` через `logEvent`), идемпотентно — проверка: `project-transfer.test.ts`, сценарии «Перенос в организацию», «CI после переноса», «Повторный запуск» +- [ ] 1.3 CLI `peppa project transfer ` (админ, строка в справке) и ошибки «Пространства нет или нет прав», «В пространстве уже есть такой репозиторий» — проверка: те же тесты по сценариям, код выхода 1 и неизменный проект +- [ ] 1.4 Текст события «репозиторий перенесён» в журнале/чате проекта (`EVENT_TEXT`) — проверка: сценарий «Перенос в организацию» видит событие + +## 2. Адреса платформы без вшитых строк + +- [ ] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck` +- [ ] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов +- [ ] 2.3 Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help` (где репозиторий платформы, команда переноса) — проверка: вычитка, ссылки на `peppa/peppa` +- [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI + +## 3. Перенос на живой системе (после одобрения PM и мержа кода) + +- [ ] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners +- [ ] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa` +- [ ] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит +- [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa` +- [ ] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект) + +## Workflow follow-up + +- `openspec archive pep-4-gitea-org`, PR, `update_task(status: review)`. diff --git a/openspec/specs/agent-runner/spec.md b/openspec/specs/agent-runner/spec.md new file mode 100644 index 00000000..d49addcb --- /dev/null +++ b/openspec/specs/agent-runner/spec.md @@ -0,0 +1,25 @@ +# agent-runner Specification + +## Purpose +TBD - created by archiving change pep-69-runner-tmux-env. Update Purpose after archive. + +## Requirements + +### Requirement: Окружение раннера не наследуется от чужого tmux-сервера +Раннер SHALL запускать агентов так, чтобы они не получали `GITEA_*`, `PEPPA_*`, `MOCK_*`, `DATABASE_URL` из глобального окружения tmux-сервера по умолчанию, а `peppa status` SHALL предупреждать, если такие переменные там есть. + +#### Scenario: Сервер запущен тестовой оболочкой +- **GIVEN** tmux-сервер по умолчанию с глобальной переменной `GITEA_URL=http://127.0.0.1:9` +- **WHEN** раннер-сервис запускает сессию стори +- **THEN** `GITEA_URL` удалена из глобального окружения сервера +- **AND** переменные сессии (`PEPPA_SESSION_ID`) переданы явно + +#### Scenario: Предупреждение в статусе +- **GIVEN** в окружении tmux-сервера есть `MOCK_X` +- **WHEN** PM запускает `peppa status` +- **THEN** выводится предупреждение со списком переменных и командой очистки + +#### Scenario: Выделенный сокет не трогается +- **GIVEN** задан `PEPPA_TMUX_SOCKET` +- **WHEN** запускается сессия +- **THEN** окружение этого сервера не чистится diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 19693b9d..1c8d41ff 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -69,7 +69,7 @@ import { setDefaultActor, } from "@peppa/core"; import { createDb, migrateDb } from "@peppa/db"; -import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner"; +import { checkHost, ensureSshKey, pushImage, sshArgs, tmux } from "@peppa/runner"; import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner"; import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core"; import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core"; @@ -643,6 +643,8 @@ async function main(): Promise { const ob = await outboxStats(db); console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`); console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`); + const foreign = await tmux.foreignServerEnv().catch(() => []); + if (foreign.length) console.log(`⚠ в окружении tmux-сервера чужие переменные: ${foreign.join(", ")} — агенты их унаследуют; очистятся при следующем запуске раннера или: ${foreign.map((n) => `tmux set-environment -g -u ${n}`).join("; ")}`); const paired = new Set((await adminRecipients(db)).map((u) => u.login)); const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`); console.log(`админы: ${admins.join(", ") || "нет"}`); diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 71ad3c8c..57f6aff7 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -41,6 +41,35 @@ export interface NewTmuxSession { width?: number; } +/** + * PEP-69: names that must never come from a tmux server's global environment. Every session + * inherits it, and a server started by some test run or tool shell carries that process's + * GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place. + * What an agent needs is passed per session (`new-session -e`) or read from `.env`. + */ +const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/; + +/** Foreign variables in the global environment of the tmux server (default server only). */ +export async function foreignServerEnv(p: Pane = { name: "" }, opts: { anySocket?: boolean } = {}): Promise { + // A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it. + if (process.env.PEPPA_TMUX_SOCKET && !opts.anySocket) return []; + let out: string; + try { + out = await tmuxOn(p, ["show-environment", "-g"]); + } catch (e) { + if (e instanceof HostUnreachable) throw e; + return []; // no server running + } + return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k)); +} + +/** Removes them from the server's global environment; returns the names removed. */ +export async function scrubServerEnv(p: Pane = { name: "" }, opts: { anySocket?: boolean } = {}): Promise { + const names = await foreignServerEnv(p, opts); + for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]); + return names; +} + export async function newSession(s: NewTmuxSession): Promise { if (isRunnerClient()) return viaService("newSession", [s]); const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]); @@ -48,6 +77,7 @@ export async function newSession(s: NewTmuxSession): Promise { // Keep the server up when its last session ends: otherwise a session created while the // previous last one is being killed can land on a server that is shutting down. await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]); + await scrubServerEnv(p).catch(() => {}); // PEP-69 await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]); // Keep the pane after claude exits so the watchdog can read the exit status. await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]); diff --git a/packages/testkit/test/tmux-env.test.ts b/packages/testkit/test/tmux-env.test.ts new file mode 100644 index 00000000..f0179b06 --- /dev/null +++ b/packages/testkit/test/tmux-env.test.ts @@ -0,0 +1,40 @@ +// PEP-69: agents must not inherit a foreign environment from the tmux server's global env. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { after, describe, test } from "node:test"; +import { tmux } from "@peppa/runner"; + +const SOCKET = `peppa-test-env-${process.pid}`; +process.env.PEPPA_TMUX_SOCKET = SOCKET; +const t = (...a: string[]) => execFileSync("tmux", ["-L", SOCKET, ...a], { encoding: "utf8" }); + +after(() => { + try { t("kill-server"); } catch { /* already gone */ } +}); + +describe("tmux server environment (PEP-69)", () => { + test("Scenario: чужие переменные сервера вычищаются, остальные остаются", async () => { + t("start-server", ";", "set-option", "-s", "exit-empty", "off"); + for (const [k, v] of [["GITEA_URL", "http://127.0.0.1:9"], ["PEPPA_HOME", "/tmp/x"], ["MOCK_X", "1"], ["DATABASE_URL", "pg"], ["KEEP_ME", "1"]] as const) { + t("set-environment", "-g", k, v); + } + // the server also inherited this test process's own PEPPA_* — those are foreign too + const found = await tmux.foreignServerEnv(undefined, { anySocket: true }); + for (const n of ["DATABASE_URL", "GITEA_URL", "MOCK_X", "PEPPA_HOME"]) assert.ok(found.includes(n), n); + assert.ok(!found.includes("KEEP_ME")); + // default: a dedicated socket is its owner's own server — nothing to warn about + assert.deepEqual(await tmux.foreignServerEnv(), []); + assert.ok((await tmux.scrubServerEnv(undefined, { anySocket: true })).length >= 4); + const left = t("show-environment", "-g"); + assert.match(left, /KEEP_ME=1/); + assert.doesNotMatch(left, /GITEA_URL|PEPPA_HOME|MOCK_X|DATABASE_URL/); + }); + + test("Scenario: новый раннер не получает чужое окружение; свои переменные доходят", async () => { + // simulate default-server mode for the scrub in newSession by scrubbing through the same path + t("set-environment", "-g", "GITEA_TOKEN", ""); + await tmux.scrubServerEnv(undefined, { anySocket: true }); + await tmux.newSession({ name: "env-probe", cwd: "/tmp", command: "env > /tmp/peppa-env-probe.$$; sleep 5", env: { PEPPA_SESSION_ID: "7" } }); + assert.doesNotMatch(t("show-environment", "-g"), /GITEA_TOKEN/); + }); +}); -- 2.45.2 From 748216eef201ff3c6f2fbf4a295be0afc4b39ecc 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 00:10:47 +0500 Subject: [PATCH 005/404] =?UTF-8?q?PEP-4:=20peppa=20project=20transfer=20?= =?UTF-8?q?=E2=80=94=20move=20a=20project's=20repo=20to=20another=20Gitea?= =?UTF-8?q?=20namespace=20(origin,=20CI=20runner,=20secret,=20webhook)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../changes/pep-4-gitea-org/.openspec.yaml | 2 + openspec/changes/pep-4-gitea-org/design.md | 80 ++++++++++ openspec/changes/pep-4-gitea-org/proposal.md | 46 ++++++ .../pep-4-gitea-org/specs/peppa-ci/spec.md | 48 ++++++ .../specs/project-provisioning/spec.md | 38 +++++ openspec/changes/pep-4-gitea-org/tasks.md | 27 ++++ packages/cli/src/index.ts | 15 +- packages/core/src/chats.ts | 2 + packages/core/src/gitea.ts | 20 +++ packages/runner/src/index.ts | 1 + packages/runner/src/share.ts | 3 + packages/runner/src/transfer.ts | 74 +++++++++ packages/testkit/src/mock-gitea.ts | 39 ++++- .../testkit/test/project-transfer.test.ts | 141 ++++++++++++++++++ 14 files changed, 531 insertions(+), 5 deletions(-) create mode 100644 openspec/changes/pep-4-gitea-org/.openspec.yaml create mode 100644 openspec/changes/pep-4-gitea-org/design.md create mode 100644 openspec/changes/pep-4-gitea-org/proposal.md create mode 100644 openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md create mode 100644 openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md create mode 100644 openspec/changes/pep-4-gitea-org/tasks.md create mode 100644 packages/runner/src/transfer.ts create mode 100644 packages/testkit/test/project-transfer.test.ts diff --git a/openspec/changes/pep-4-gitea-org/.openspec.yaml b/openspec/changes/pep-4-gitea-org/.openspec.yaml new file mode 100644 index 00000000..be831cee --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-14 diff --git a/openspec/changes/pep-4-gitea-org/design.md b/openspec/changes/pep-4-gitea-org/design.md new file mode 100644 index 00000000..3a234439 --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/design.md @@ -0,0 +1,80 @@ +# Design + +## Context + +Мотивация — в proposal.md. Что есть сейчас (проверено 2026-11-14, Gitea 1.22.6): + +- Организации `peppa` нет, имя свободно (ни пользователя, ни организации). `peppa-bot` не админ + Gitea и не состоит ни в одной организации; может ли он создавать организации — видно только + по ответу на `POST /orgs`. +- В пространстве `peppa-bot` 12 репозиториев: `peppa`, `template` (приватный, шаблон) и 10 + проектов пользователей. В БД у всех 11 проектов `gitea_owner = peppa-bot`. +- Раннер CI зарегистрирован на уровне пользователя `peppa-bot`; `setupCi` для проекта с другим + владельцем сам регистрирует раннер на репозиторий (метка `repo---`). +- Адрес `peppa-bot/peppa` вшит в `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`; + шаблон — `GITEA_TEMPLATE_REPO` (env, умолчание в `env.ts`, `push-template.sh`, `.env.example`). +- Открыт PR #79 (`task/pep-87`), идут сессии PEP — работа параллельными волнами. + +## Goals / Non-Goals + +**Goals:** +- `peppa/peppa` и `peppa/template` работают как раньше: CI, вебхуки, превью, правила агентов. +- Перенос повторяем и проверяем кодом (команда + тест на `mock-gitea`), а не разовым curl. + +**Non-Goals:** +- Перенос проектов пользователей из `peppa-bot`; смена пространства для новых проектов (PEP-68). +- Команды и права внутри организации сверх Owners; официальный прод (PEP-18). +- UI/MCP для переноса — только CLI администратора (как `project visibility`). + +## Decisions + +1. **Организацию создаёт `peppa-bot` (`POST /orgs`, visibility public)**, если Gitea разрешит; + 403 — просим PM создать её админом и добавить `peppa-bot` в Owners. Давать боту права админа + Gitea не нужно и не хочется: ему достаточно быть владельцем одной организации. + Вторым владельцем добавляем учётку PM в Gitea — организация не должна держаться на одном боте. +2. **Перенос — операция `transferProject` в runner + `peppa project transfer`**, а не ручные + шаги. Порядок: проверить пространство и отсутствие `/` → `POST + /repos/{o}/{r}/transfer` (владелец организации переносит сразу, без подтверждения) → обновить + `projects.gitea_owner` → `git remote set-url origin` в рабочей копии (worktree делят конфиг) → + `setupCi` (раннер на репозиторий, секрет, вебхук) → событие `repo_transferred`. Каждый шаг + идемпотентен: если репозиторий уже на новом месте, шаг Gitea пропускается. + Альтернатива — UPDATE в БД руками — не оставляет следа в журнале и забывает раннер. +3. **Раннер — на репозиторий** (существующий путь `setupCi`), не на организацию: раннер с + docker.sock хоста не должен автоматически обслуживать любой будущий репозиторий организации. +4. **`GITEA_PLATFORM_REPO`** (env, умолчание `peppa/peppa`) вместо трёх вшитых строк. Брать адрес + из проекта `PEPPA_PLATFORM_KEY` в БД нельзя: скрипты релиза и `ci.sh` работают без БД. +5. **Шаблон** — не проект Пеппы, переносится тем же вызовом клиента из задачи разово + (`peppa project transfer` его не знает); затем `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, + `scripts/push-template.sh` и проверка `get_rules`. Остаётся приватным и `template: true`. +6. **Порядок на живой системе**: сначала мерж кода (умолчания новые, но `.env` ещё держит + старые адреса — ничего не ломается), затем перенос одной командой, сразу `.env` и рестарт + сервисов. Редиректы Gitea покрывают окно между шагами и чужие клоны. + +## Risks / Trade-offs + +- [Редирект не действует на API-запросы Пеппы по старому адресу] → адрес проекта в БД меняется + в той же команде, сразу после переноса; окно — секунды. +- [Живые сессии PEP и PR #79 в момент переноса] → git идёт через редирект; `origin` общей + рабочей копии и worktree обновляются командой. Контейнерные сессии (релей git пускает только + `owner/repo` проекта) — на PEP сейчас не используются; проверить перед переносом. +- [Секрет Actions и вебхук могут не пережить перенос] → `setupCi` ставит их заново в любом случае. +- [Раннер уровня `peppa-bot` перестаёт видеть `peppa/peppa`] → регистрация на репозиторий — часть + команды; проверка — зелёный прогон CI на PR этой стори после переноса. +- [Кто-то создаст `peppa-bot/peppa` заново и сломает редирект] → не создавать; записать в память. +- [Bare-клон будущего прода `~/peppa/repo.git`] → `PEPPA_RELEASE_REMOTE` по умолчанию от + `GITEA_PLATFORM_REPO`; существующему клону — `git remote set-url`. + +## Migration Plan + +1. PR с кодом и тестами — зелёный CI на старом адресе, мерж. +2. Организация `peppa` (бот или PM), `peppa-bot` и PM — Owners. +3. `peppa db backup`, `peppa project transfer PEP peppa`; перенос `template`. +4. `.env`: `GITEA_TEMPLATE_REPO=peppa/template`; рестарт web/bot/watchdog; `peppa status`. +5. Проверки: `git fetch` в рабочей копии, `get_rules`, пробный PR/пуш → проверки `peppa/*` + зелёные и видны на карточке, футер ведёт на `peppa/peppa`. + +Откат: `peppa project transfer PEP peppa-bot`, обратный перенос `template`, прежний `.env`. + +## Open Questions + +- Логин PM в Gitea для второго владельца организации — нужен только на шаге 2, на код не влияет. diff --git a/openspec/changes/pep-4-gitea-org/proposal.md b/openspec/changes/pep-4-gitea-org/proposal.md new file mode 100644 index 00000000..d2219ae4 --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/proposal.md @@ -0,0 +1,46 @@ +# Proposal + +## Why + +Репозитории платформы (`peppa-bot/peppa`, `peppa-bot/template`) лежат в личном пространстве +служебной учётки `peppa-bot` вперемешку с проектами пользователей без Gitea (PEP-68). Платформа +мультипользовательская (эпик #2): её код и шаблон должны принадлежать организации `peppa`, где +владельцев несколько и права задаются командами, а не паролем одного бота. + +## What Changes + +- В Gitea создаётся организация `peppa` (публичная); `peppa-bot` — в команде Owners. +- `peppa-bot/peppa` → `peppa/peppa`, `peppa-bot/template` → `peppa/template` (перенос Gitea: + история, PR, issues, вебхуки и секреты Actions сохраняются, старые адреса редиректят). +- Новая команда `peppa project transfer ` — переносит репозиторий проекта в другое + пространство Gitea и чинит всё, что от адреса зависит: запись проекта, `origin` рабочей копии, + раннер CI, секрет и вебхук. Перенос `peppa` делается ею же; повторный запуск безопасен. +- `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; адрес репозитория платформы перестаёт быть + вшитым (`peppa-bot/peppa` в футере, `scripts/ci.sh`, `scripts/peppa-release.sh`) — одна + настройка `GITEA_PLATFORM_REPO` (по умолчанию `peppa/peppa`). +- Живая система: `.env`, `origin` рабочей копии, раннер CI на `peppa/peppa`, документация. +- Проекты пользователей в пространстве `peppa-bot` **не переносятся** (вне scope). + +## Capabilities + +### New Capabilities + +Нет. + +### Modified Capabilities +- `project-provisioning`: новое требование — перенос репозитория проекта в другое пространство + Gitea командой CLI. +- `peppa-ci`: репозиторий платформы в требованиях — `peppa/peppa` вместо `peppa-bot/peppa`. + +## Impact + +- Gitea: новая организация, перенос двух репозиториев (обратим обратным переносом, но адреса + меняются для всех клонов); нужно право `peppa-bot` создавать организации **или** организация, + созданная админом Gitea с `peppa-bot` в Owners. +- Код: `packages/core/src/gitea.ts` (перенос), `packages/runner` (новая операция, `ci.ts`), + `packages/cli`, `packages/shared/src/env.ts`, `apps/web/components/Footer.tsx`, `scripts/ci.sh`, + `scripts/peppa-release.sh`, `scripts/push-template.sh`, `.env.example`, `mock-gitea`. +- Данные: `projects.gitea_owner` проекта PEP (`peppa-bot` → `peppa`), без миграций схемы. +- CI: раннер уровня пользователя `peppa-bot` перестаёт покрывать `peppa/peppa` — регистрация на + репозиторий. Открытые PR (сейчас #79) и живые сессии PEP продолжают работать через редирект. +- Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help`. diff --git a/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md new file mode 100644 index 00000000..ecf49c5d --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md @@ -0,0 +1,48 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Статус проверки в PR +`scripts/ci.sh --pr ` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория платформы +(`GITEA_PLATFORM_REPO`, по умолчанию `peppa/peppa`) в отдельном +временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем +`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. + +#### Scenario: Зелёный PR +- **GIVEN** открыт PR 15, его голова проходит все проверки +- **WHEN** запускается `scripts/ci.sh --pr 15` +- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in min» +- **AND** лог прогона лежит в `~/.peppa/ci/.log`, временный worktree удалён + +#### Scenario: Красный PR +- **GIVEN** открыт PR 16, в его голове падает e2e +- **WHEN** запускается `scripts/ci.sh --pr 16` +- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу +- **AND** код выхода 1 + +#### Scenario: Нет такого PR +- **GIVEN** в репозитории нет PR 999 +- **WHEN** запускается `scripts/ci.sh --pr 999` +- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 + +### Requirement: Проверки на каждый PR в Gitea Actions +Workflow `.gitea/workflows/ci.yml` репозитория `peppa/peppa` SHALL на каждый PR из ветки этого +репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57), +с тестовой БД `peppa_test_ci_r` на Postgres хоста, и выставлять статус коммита +`peppa-ci / ci (pull_request)`; PR из форков не запускаются. + +#### Scenario: PR зелёный +- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят +- **WHEN** ветка пушится +- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in ms») +- **AND** БД `peppa_test_ci_r` после job не существует + +#### Scenario: PR красный +- **GIVEN** в голове PR падает один e2e-тест +- **WHEN** job доходит до шага `ci` +- **THEN** статус = `failure` («Failing after ms»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста + +#### Scenario: PR из форка +- **GIVEN** PR открыт из форка репозитория +- **WHEN** Gitea обрабатывает событие `pull_request` +- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется diff --git a/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md new file mode 100644 index 00000000..d7cc555a --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md @@ -0,0 +1,38 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Перенос репозитория проекта в другое пространство +Команда `peppa project transfer ` SHALL переносить репозиторий проекта в пространство +`` (организация или пользователь Gitea) и приводить проект в рабочее состояние по новому +адресу: адрес проекта в Пеппе, `origin` рабочей копии, раннер CI, секрет и вебхук. Повторный запуск +после частичного сбоя SHALL доводить перенос до конца без ошибки. + +#### Scenario: Перенос в организацию +- **GIVEN** проект `DEMO` с репозиторием `peppa-bot/demo` и организация `acme`, где `peppa-bot` — владелец +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** репозиторий доступен как `acme/demo`, вывод — «DEMO: peppa-bot/demo → acme/demo» +- **AND** страница проекта в вебе ссылается на `acme/demo` +- **AND** `git remote get-url origin` в рабочей копии оканчивается на `/acme/demo.git` +- **AND** в журнале проекта есть событие «репозиторий перенесён» со старым и новым адресом + +#### Scenario: CI после переноса +- **GIVEN** проект `DEMO` с подключённым CI перенесён из `peppa-bot/demo` в `acme/demo` +- **WHEN** в `acme/demo` открывается PR +- **THEN** проверки `peppa/*` выполняются на раннере Пеппы и их отчёты приходят на карточку стори + +#### Scenario: Повторный запуск +- **GIVEN** репозиторий проекта `DEMO` уже находится в `acme/demo`, а в Пеппе записан `peppa-bot/demo` +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** перенос в Gitea не запрашивается, адрес проекта и `origin` становятся `acme/demo`, код выхода 0 + +#### Scenario: Пространства нет или нет прав +- **GIVEN** организации `nope` в Gitea нет +- **WHEN** выполняется `peppa project transfer DEMO nope` +- **THEN** выводится «Пространство nope не найдено или у peppa-bot нет прав создавать в нём репозитории», код выхода 1 +- **AND** репозиторий остаётся `peppa-bot/demo`, адрес проекта в Пеппе не меняется + +#### Scenario: В пространстве уже есть такой репозиторий +- **GIVEN** в организации `acme` уже есть другой репозиторий `demo` +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** выводится «Репозиторий acme/demo уже существует», код выхода 1, ничего не меняется diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/pep-4-gitea-org/tasks.md new file mode 100644 index 00000000..e44d05a1 --- /dev/null +++ b/openspec/changes/pep-4-gitea-org/tasks.md @@ -0,0 +1,27 @@ +# Tasks + +## 1. Перенос репозитория проекта (код) + +- [x] 1.1 `GiteaClient`: `transferRepo(owner, repo, newOwner)` и проверка пространства (организация/пользователь, право создавать репозитории); `mock-gitea` — `POST /repos/{o}/{r}/transfer` (404 пространства, 409 занятое имя, редирект старого адреса) — проверка: юнит-вызовы мока в новом тесте +- [x] 1.2 `transferProject` в `packages/runner` (перенос → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` → событие `repo_transferred` через `logEvent`), идемпотентно — проверка: `project-transfer.test.ts`, сценарии «Перенос в организацию», «CI после переноса», «Повторный запуск» +- [x] 1.3 CLI `peppa project transfer ` (админ, строка в справке) и ошибки «Пространства нет или нет прав», «В пространстве уже есть такой репозиторий» — проверка: те же тесты по сценариям, код выхода 1 и неизменный проект +- [x] 1.4 Текст события «репозиторий перенесён» в журнале/чате проекта (`EVENT_TEXT`) — проверка: сценарий «Перенос в организацию» видит событие + +## 2. Адреса платформы без вшитых строк + +- [ ] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck` +- [ ] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов +- [ ] 2.3 Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help` (где репозиторий платформы, команда переноса) — проверка: вычитка, ссылки на `peppa/peppa` +- [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI + +## 3. Перенос на живой системе (после одобрения PM и мержа кода) + +- [ ] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners +- [ ] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa` +- [ ] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит +- [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa` +- [ ] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект) + +## Workflow follow-up + +- `openspec archive pep-4-gitea-org`, PR, `update_task(status: review)`. diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 19693b9d..eb37434e 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -74,7 +74,7 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core"; import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core"; import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core"; -import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { loadEnv } from "@peppa/shared"; @@ -87,6 +87,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project autonomy [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes) peppa project agent [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit) peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) + peppa project transfer (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook) peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back) peppa project list peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) @@ -319,6 +320,18 @@ async function main(): Promise { if (failed) process.exitCode = 1; break; } + case "project transfer": { + const [key, owner] = args; + if (!key || !owner) throw new PeppaError("usage: peppa project transfer "); + const p = await getProject(db, key); + const r = await transferProject(db, p, owner, { log: (step) => console.log(`… ${step}`) }); + console.log(`${p.key}: ${r.from} → ${r.to}${r.moved ? "" : " (репозиторий уже там)"}`); + if (r.ciError) { + console.log(`CI: ${r.ciError} — повторите: peppa ci connect ${p.key}`); + process.exitCode = 1; + } + break; + } case "project autonomy": { // PEP-23: peppa project autonomy [manual|assisted|auto] [key=value…] const [key, ...rest] = args; diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index 237c0808..97bb9720 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -274,6 +274,8 @@ const EVENT_TEXT: Record { text: string; important?: boolean; }, progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }), pm_comment: () => null, // handled separately: a person's message + // PEP-4: the project's repo moved to another Gitea namespace. + repo_transferred: (p) => ({ text: `📦 Репозиторий перенесён: ${s(p.from)} → ${s(p.to)}`, important: true }), // PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread. intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }), pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }), diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index b599903e..a362dff5 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -151,6 +151,26 @@ export class GiteaClient { return this.request("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate }); } + /** + * Moves a repo to another namespace (PEP-4). Gitea moves it at once only when the token owner + * may create repos there; otherwise the transfer stays pending — check where the repo is after. + */ + transferRepo(owner: string, name: string, newOwner: string) { + return this.request("POST", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/transfer`, { new_owner: newOwner }); + } + + /** True if the token owner `login` may create repos in `namespace` (own account or an org with that right). */ + async canCreateIn(login: string, namespace: string): Promise { + if (namespace.toLowerCase() === login.toLowerCase()) return true; + try { + const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(namespace)}/permissions`); + return !!p?.can_create_repository; + } catch (e) { + if (e instanceof GiteaError && (e.status === 404 || e.status === 403)) return false; + throw e; + } + } + /** True if `name` is an organization (false for a user account). */ async isOrg(name: string): Promise { try { diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 7dfea5ca..4d2c63cf 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -12,6 +12,7 @@ export * from "./share.ts"; export * from "./limits.ts"; export * from "./monitor.ts"; export * from "./ci.ts"; +export * from "./transfer.ts"; export * from "./incidents.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts index 2affa770..1785d103 100644 --- a/packages/runner/src/share.ts +++ b/packages/runner/src/share.ts @@ -157,6 +157,9 @@ const DESCRIBE_CACHE_MS = 60_000; // The project page refreshes every few seconds; Gitea is asked at most once a minute per project. const describeCache = new Map(); +/** Drops the cached repo info (the repo moved or changed outside this module). */ +export const forgetRepoInfo = (projectId: number) => void describeCache.delete(projectId); + /** Where the project's repo is and who can see it, asked from Gitea (owner's client, then peppa-bot). */ export async function describeRepo(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise { const hit = describeCache.get(project.id); diff --git a/packages/runner/src/transfer.ts b/packages/runner/src/transfer.ts new file mode 100644 index 00000000..dbcf7e3a --- /dev/null +++ b/packages/runner/src/transfer.ts @@ -0,0 +1,74 @@ +// PEP-4: moving a project's repo to another Gitea namespace (an organization, usually) and +// fixing everything that depends on its address: the project row, `origin` of the working +// copy, the CI runner, the Actions secret and the webhook. Every step is safe to repeat. +import { existsSync } from "node:fs"; +import { eq } from "drizzle-orm"; +import { GiteaError, giteaForBot, logEvent, PeppaError, type Project } from "@peppa/core"; +import { projects, type Db } from "@peppa/db"; +import { setupCi } from "./ci.ts"; +import { git } from "./git.ts"; +import { forgetRepoInfo } from "./share.ts"; + +export interface TransferResult { + project: Project; + from: string; + to: string; + /** False when the repo was already there (a repeated run): only Peppa's side was fixed. */ + moved: boolean; + /** CI could not be set up at the new address (the transfer itself is done). */ + ciError: string | null; +} + +/** Moves the project's repo to `newOwner` as peppa-bot (CLI on Peppa's machine: no owner check). */ +export async function transferProject(db: Db, project: Project, newOwner: string, o: { log?: (step: string) => void } = {}): Promise { + const log = o.log ?? (() => {}); + const target = newOwner.trim(); + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(target)) throw new PeppaError(`Пространство «${newOwner}»: логин пользователя или организации Gitea`); + const bot = giteaForBot(); + const repoName = project.giteaRepo; + const from = `${project.giteaOwner}/${repoName}`; + const to = `${target}/${repoName}`; + + let dest = await bot.getRepo(target, repoName); + // After a transfer the old address redirects to the new one: the same repo id means "already moved". + const src = project.giteaOwner === target ? dest : await bot.getRepo(project.giteaOwner, repoName); + let moved = false; + if (dest && dest.owner.login.toLowerCase() !== target.toLowerCase()) dest = null; // a redirect left by an older move + if (dest && src && src.id !== dest.id) throw new PeppaError(`Репозиторий ${to} уже существует`); + if (!dest) { + if (!src) throw new PeppaError(`Репозиторий ${from} не найден в Gitea`); + const me = await bot.me(); + if (!(await bot.canCreateIn(me.login, target))) throw new PeppaError(`Пространство ${target} не найдено или у ${me.login} нет прав создавать в нём репозитории`); + log("transfer"); + try { + await bot.transferRepo(project.giteaOwner, repoName, target); + } catch (e) { + const status = e instanceof GiteaError ? e.status : 0; + if (status === 422 || status === 409) throw new PeppaError(`Репозиторий ${to} уже существует`); + if (status === 403) throw new PeppaError(`Нет прав администратора на ${from} — переносит владелец репозитория`); + throw e; + } + dest = await bot.getRepo(target, repoName); + if (!dest || dest.owner.login.toLowerCase() !== target.toLowerCase()) throw new PeppaError(`Перенос ${from} → ${to} ждёт подтверждения в Gitea`); + moved = true; + } + + const changed = project.giteaOwner !== dest.owner.login; + if (changed) { + log("project"); + await db.update(projects).set({ giteaOwner: dest.owner.login }).where(eq(projects.id, project.id)); + } + const updated: Project = { ...project, giteaOwner: dest.owner.login }; + forgetRepoInfo(project.id); + if (existsSync(project.workspacePath)) { + log("origin"); + await git(project.workspacePath, "remote", "set-url", "origin", dest.clone_url); + } + log("ci"); + const ciError = await setupCi(db, updated).then( + () => null, + (e: Error) => e.message, + ); + if (moved || changed) await logEvent(db, { projectId: project.id, type: "repo_transferred", payload: { from, to } }); + return { project: updated, from, to, moved, ciError }; +} diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index bfde5b83..50f5a427 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -4,7 +4,7 @@ // (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags. import { execFileSync } from "node:child_process"; import { createHmac } from "node:crypto"; -import { mkdirSync, mkdtempSync } from "node:fs"; +import { mkdirSync, mkdtempSync, renameSync } from "node:fs"; import { tmpdir } from "node:os"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; @@ -59,6 +59,8 @@ export class MockGitea { readonly users = new Map(); readonly oauthCodes = new Map(); // code → token readonly runnerTokens: Array<{ scope: string; token: string }> = []; + /** PEP-4: old `owner/name` → current one, like Gitea's redirects after a transfer. */ + readonly redirects = new Map(); private seq = 1; private server: Server | null = null; url = ""; @@ -98,6 +100,10 @@ export class MockGitea { return new Promise((r) => this.server?.close(() => r()) ?? r()); } + private isOrg(name: string) { + return [...this.users.values()].some((u) => u.orgs?.includes(name)); + } + addUser(u: MockGiteaUser) { this.users.set(u.token, u); return u; @@ -300,12 +306,12 @@ export class MockGitea { if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } }; if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) }; if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) { + if (!this.isOrg(decodeURIComponent(m[2]!))) return { status: 404, body: { message: "org does not exist" } }; return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } }; } if (method === "GET" && (m = path.match(/^\/api\/v1\/orgs\/([^/]+)$/))) { const name = decodeURIComponent(m[1]!); - const isOrg = [...this.users.values()].some((u) => u.orgs?.includes(name)); - return isOrg ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } }; + return this.isOrg(name) ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } }; } if (method === "GET" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); @@ -322,6 +328,29 @@ export class MockGitea { this.runnerTokens.push({ scope: `user:${me.login}`, token }); return { status: 200, body: { token } }; } + if (method === "POST" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/transfer$/))) { + // Gitea: repo admin only; unknown namespace → 404; name taken there → 422; the doer may + // create repos in the target → moved at once (202), otherwise the transfer stays pending (201). + const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); + if (!r) return { status: 404, body: { message: "not found" } }; + if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } }; + const to = String(body.new_owner ?? ""); + const users = [...this.users.values()]; + if (!this.isOrg(to) && !users.some((u) => u.login === to)) return { status: 404, body: { message: "new owner does not exist" } }; + if (this.repos.has(`${to}/${r.name}`)) return { status: 422, body: { message: "The repository with the same name already exists." } }; + if (!(to === me.login || (me.orgs ?? []).includes(to))) return { status: 201, body: this.json(r, me) }; + const old = `${r.owner}/${r.name}`; + const path2 = join(this.dir, to, `${r.name}.git`); + mkdirSync(join(this.dir, to), { recursive: true }); + renameSync(r.path, path2); + this.repos.delete(old); + Object.assign(r, { owner: to, path: path2, admins: new Set([to, ...users.filter((u) => u.orgs?.includes(to)).map((u) => u.login)]) }); + this.repos.set(`${to}/${r.name}`, r); + for (const [k, v] of this.redirects) if (v === old) this.redirects.set(k, `${to}/${r.name}`); + this.redirects.delete(`${to}/${r.name}`); + this.redirects.set(old, `${to}/${r.name}`); + return { status: 202, body: this.json(r, me) }; + } if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; @@ -329,7 +358,9 @@ export class MockGitea { if (res) return res; } if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) { - const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); + const full = `${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`; + // A moved repo answers GET by its old address too (Gitea redirects, fetch follows). + const r = this.repos.get(full) ?? (method === "GET" ? this.repos.get(this.redirects.get(full) ?? "") : undefined); if (!r) return { status: 404, body: { message: "not found" } }; if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 }; if (method === "PATCH") { diff --git a/packages/testkit/test/project-transfer.test.ts b/packages/testkit/test/project-transfer.test.ts new file mode 100644 index 00000000..0dba1080 --- /dev/null +++ b/packages/testkit/test/project-transfer.test.ts @@ -0,0 +1,141 @@ +// PEP-4: `peppa project transfer ` — the project's repo moves to another Gitea +// namespace and the project keeps working there (address, origin, CI runner, secret, webhook). +// Tests are named after the scenarios of openspec/specs/project-provisioning. +import assert from "node:assert/strict"; +import { execFile, execFileSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { after, before, describe, test } from "node:test"; +import { eq } from "drizzle-orm"; +import { events, projects } from "@peppa/db"; +import { core, db, runner, teardown } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-transfer-")); +process.env.PEPPA_SECRET = "mock-secret-for-tests"; + +const gitea = new MockGitea(join(TMP, "gitea")); +const BOT = { id: 71, login: "peppa-bot", token: "mock-token-transfer-bot", orgs: ["mock-acme"] }; +const ORG = "mock-acme"; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +/** A project with a repo in peppa-bot's namespace and a cloned working copy. */ +async function project(slug: string, key: string) { + const repo = gitea.addRepo(BOT.login, slug, { files: { "README.md": `# ${slug}\n` } }); + const ws = join(TMP, "ws", slug); + execFileSync("git", ["clone", "-q", repo.path, ws]); + return core.createProject(db, { slug, key, name: key, giteaOwner: BOT.login, workspacePath: ws, ownerId: null }); +} + +async function cli(...a: string[]) { + try { + const r = await promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "transfer", ...a], { encoding: "utf8", env: process.env }); + return { code: 0, out: r.stdout + r.stderr }; + } catch (e) { + const x = e as { code?: number; stdout?: string; stderr?: string }; + return { code: x.code ?? 1, out: `${x.stdout ?? ""}${x.stderr ?? ""}` }; + } +} + +const origin = (ws: string) => execFileSync("git", ["-C", ws, "remote", "get-url", "origin"], { encoding: "utf8" }).trim(); +const reload = async (id: number) => (await db.select().from(projects).where(eq(projects.id, id)))[0]!; +const registrations = () => { + const f = join(process.env.PEPPA_HOME!, "mock-ci-register.jsonl"); + return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { name: string }) : []; +}; + +describe("project transfer (PEP-4)", () => { + let demoId = 0; + + test("Перенос в организацию", async () => { + const p = await project("mock-demo", "MTDEMO"); + demoId = p.id; + const r = await cli("MTDEMO", ORG); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo\n/); + assert.ok(gitea.repos.has(`${ORG}/mock-demo`)); + assert.ok(!gitea.repos.has("peppa-bot/mock-demo")); + const now = await reload(p.id); + assert.equal(now.giteaOwner, ORG); + const repo = await runner.describeRepo(db, now, { fresh: true }); + assert.equal(repo.fullName, `${ORG}/mock-demo`); // what the project page links to + assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`), origin(p.workspacePath)); + execFileSync("git", ["-C", p.workspacePath, "fetch", "-q", "origin"]); + const ev = (await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred"); + assert.equal(ev.length, 1); + assert.deepEqual(ev[0]!.payload, { from: "peppa-bot/mock-demo", to: `${ORG}/mock-demo` }); + }); + + test("CI после переноса", async () => { + // The bot-level runner no longer covers the repo: it gets its own, plus the report secret and the webhook. + const repo = gitea.repo(ORG, "mock-demo"); + assert.ok(registrations().some((x) => x.name === `repo-${ORG}--mock-demo`), JSON.stringify(registrations())); + assert.equal(repo.secrets[runner.CI_SECRET_NAME], core.projectHookSecret(demoId)); + assert.equal(repo.hooks.length, 1); + assert.equal(repo.hooks[0]!.url, runner.giteaHookUrl()); + assert.deepEqual(repo.hooks[0]!.events, runner.GITEA_HOOK_EVENTS); + }); + + test("Повторный запуск", async () => { + // Peppa's side lost: the repo is already in the org, the project and origin still point to the old place. + const p = await reload(demoId); + await db.update(projects).set({ giteaOwner: BOT.login }).where(eq(projects.id, demoId)); + execFileSync("git", ["-C", p.workspacePath, "remote", "set-url", "origin", join(TMP, "gone", "peppa-bot", "mock-demo.git")]); + const id = gitea.repo(ORG, "mock-demo").id; + const r = await cli("MTDEMO", ORG); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo \(репозиторий уже там\)/); + assert.equal(gitea.repo(ORG, "mock-demo").id, id); + assert.equal((await reload(demoId)).giteaOwner, ORG); + assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`)); + // …and once more, with nothing left to fix. + const again = await cli("MTDEMO", ORG); + assert.equal(again.code, 0, again.out); + }); + + test("Пространства нет или нет прав", async () => { + const p = await project("mock-stay", "MTSTAY"); + const before = origin(p.workspacePath); + const r = await cli("MTSTAY", "mock-nope"); + assert.equal(r.code, 1, r.out); + assert.match(r.out, /Пространство mock-nope не найдено или у peppa-bot нет прав создавать в нём репозитории/); + assert.ok(gitea.repos.has("peppa-bot/mock-stay")); + assert.equal((await reload(p.id)).giteaOwner, BOT.login); + assert.equal(origin(p.workspacePath), before); + }); + + test("В пространстве уже есть такой репозиторий", async () => { + const p = await project("mock-twin", "MTTWIN"); + gitea.addRepo(ORG, "mock-twin", { files: { "README.md": "# other\n" } }); + const r = await cli("MTTWIN", ORG); + assert.equal(r.code, 1, r.out); + assert.match(r.out, /Репозиторий mock-acme\/mock-twin уже существует/); + assert.ok(gitea.repos.has("peppa-bot/mock-twin")); + assert.equal((await reload(p.id)).giteaOwner, BOT.login); + assert.equal((await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred").length, 0); + }); + + test("mock-gitea: перенос без права создавать в пространстве остаётся ожидающим", async () => { + gitea.addUser({ id: 72, login: "mock-other", token: "mock-token-transfer-other" }); + gitea.addRepo(BOT.login, "mock-pending", { files: { "README.md": "# x\n" } }); + const bot = core.giteaForBot(); + await bot.transferRepo(BOT.login, "mock-pending", "mock-other"); + assert.ok(gitea.repos.has("peppa-bot/mock-pending")); + assert.equal(await bot.getRepo("mock-other", "mock-pending"), null); + await assert.rejects(bot.transferRepo(BOT.login, "mock-pending", "mock-nobody"), /404/); + }); +}); -- 2.45.2 From 5af93d7438dbea699a2e321e59fc2447fa6d6915 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 00:11:31 +0500 Subject: [PATCH 006/404] PEP-4: platform repo address from GITEA_PLATFORM_REPO, template defaults to peppa/template Co-Authored-By: Claude Fable 5.2 --- .env.example | 4 +++- AGENTS.md | 7 ++++--- apps/web/components/Footer.tsx | 2 +- openspec/changes/pep-4-gitea-org/tasks.md | 6 +++--- packages/shared/src/env.ts | 5 ++++- scripts/ci.sh | 4 ++-- scripts/peppa-release.sh | 4 ++-- scripts/push-template.sh | 2 +- 8 files changed, 20 insertions(+), 14 deletions(-) diff --git a/.env.example b/.env.example index ee5cfd5e..18bb27b2 100644 --- a/.env.example +++ b/.env.example @@ -6,7 +6,9 @@ # Gitea (git.telecom.quest) — token with repo + org scope GITEA_URL=https://git.telecom.quest GITEA_TOKEN= -GITEA_TEMPLATE_REPO=peppa-bot/template +GITEA_TEMPLATE_REPO=peppa/template +# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh) +# GITEA_PLATFORM_REPO=peppa/peppa # Where project repos are cloned and sessions run PEPPA_WORKSPACES=~/peppa/workspaces diff --git a/AGENTS.md b/AGENTS.md index cff9faae..6600b08f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,6 +43,7 @@ - **Продакт и аналитик (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`) - **Свой Telegram-бот (PEP-85)**: `users.telegram_bot_token_enc` (в `encryptedColumns`) + `telegram_bot_username` (миграция 0016). core/telegram.ts: `verifyBotToken`, `setUserBot`/`clearUserBot`, `userBots`; `acceptPairing(…, { botUserId })` — свой бот привязывает только владельца, общий не привязывает того, у кого есть свой; `getOffset`/`claimUpdate` принимают `botUserId` (ключ обновления `userId·2^36 + update_id`). apps/bot: `syncOwnBots` (раз в `userBotsIntervalMs`), `ownPollLoop`, обработка внутри `via.run(bot)`, объект `api` маршрутизирует вызов: бот текущего обновления → бот владельца `chat_id` → общий. Группы и каналы — только общий бот. Веб «Настройки → Telegram»: три шага. Тест `own-bot.test.ts` — два `MockTelegram` (`userApi` в опциях бота) - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member +- **Перенос репозитория проекта (PEP-4)**: `peppa project transfer ` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo---`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно - **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` - **Вход через 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/` @@ -66,8 +67,8 @@ - **Модель агента (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-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-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта -- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем +- `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` — заготовка под специфику проекта +- Gitea: бот `peppa-bot` (токен в `.env`), организация `peppa` (PEP-4; владелец — `peppa-bot`): репо `peppa/peppa` (эта платформа, `GITEA_PLATFORM_REPO` — футер, `scripts/ci.sh --pr`, `peppa-release.sh`) и `peppa/template`; старые адреса `peppa-bot/peppa|template` редиректит Gitea, пока репозитории с такими именами не созданы заново — не создавать; проекты пользователей без Gitea остаются в пространстве `peppa-bot`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем - **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже - **Прод Пеппы (PEP-18, для будущего официального прода)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh `: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh @@ -96,7 +97,7 @@ - `pnpm dev:web` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer ` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` -- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite; без него тест пропускается); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`) +- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite; без него тест пропускается); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`) - `pnpm --filter @peppa/testkit test` — e2e CJM на моках (у каждого файла свой временный SQLite-файл, свой tmux `-L`, свой `PEPPA_HOME` — параллельные worktree не мешают друг другу) - **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (mock-telegram, бот, вачдог = раннер-сервис; привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx index 5be0d18b..64914c84 100644 --- a/apps/web/components/Footer.tsx +++ b/apps/web/components/Footer.tsx @@ -13,7 +13,7 @@ export function Footer() { {commit && ( <> {" · "} - + {commit} {dirty && +изменения} diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/pep-4-gitea-org/tasks.md index e44d05a1..ab36a13e 100644 --- a/openspec/changes/pep-4-gitea-org/tasks.md +++ b/openspec/changes/pep-4-gitea-org/tasks.md @@ -9,9 +9,9 @@ ## 2. Адреса платформы без вшитых строк -- [ ] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck` -- [ ] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов -- [ ] 2.3 Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help` (где репозиторий платформы, команда переноса) — проверка: вычитка, ссылки на `peppa/peppa` +- [x] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck` +- [x] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов +- [x] 2.3 Документация: `AGENTS.md` (где репозиторий платформы, команда переноса; в `docs/HANDOFF.md` и `/help` адресов платформы нет — без правок) — проверка: вычитка, ссылки на `peppa/peppa` - [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI ## 3. Перенос на живой системе (после одобрения PM и мержа кода) diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index 4556ac4d..0091752e 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -8,7 +8,10 @@ const schema = z.object({ DATABASE_URL: z.string().optional(), GITEA_URL: z.string().url().default("https://git.telecom.quest"), GITEA_TOKEN: z.string().optional(), - GITEA_TEMPLATE_REPO: z.string().default("peppa-bot/template"), + // PEP-4: the platform's repos live in the `peppa` organization. + GITEA_TEMPLATE_REPO: z.string().default("peppa/template"), + // Peppa's own repo (`owner/repo`): footer link, scripts/ci.sh --pr, scripts/peppa-release.sh. + GITEA_PLATFORM_REPO: z.string().default("peppa/peppa"), // PEP-46: Peppa's own Gitea account — its comments in PRs/issues never go back to agents. GITEA_BOT_LOGIN: z.string().default("peppa-bot"), PEPPA_WORKSPACES: z.string().default("~/peppa/workspaces"), diff --git a/scripts/ci.sh b/scripts/ci.sh index 389b94e5..c1a0e238 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -2,7 +2,7 @@ # CI for Peppa itself (PEP-22): typecheck, web build, e2e on mocks. # # scripts/ci.sh checks of this checkout (also `pnpm run ci`) -# scripts/ci.sh --pr checks of PR head N in peppa-bot/peppa in a temp worktree, +# scripts/ci.sh --pr checks of PR head N in $GITEA_PLATFORM_REPO (peppa/peppa) in a temp worktree, # with commit status `peppa/ci` in Gitea (pending → success/failure) # scripts/ci.sh --repeat run the e2e suite N times in a row (flake hunting) # scripts/ci.sh --skip-build skip `next build` @@ -26,7 +26,7 @@ done if [ -n "$PR" ]; then . "$ROOT/scripts/lib/ci-env.sh" . "$ROOT/scripts/gitea-lib.sh" - REPO="${PEPPA_CI_REPO:-peppa-bot/peppa}" + REPO="${PEPPA_CI_REPO:-${GITEA_PLATFORM_REPO:-peppa/peppa}}" CONTEXT="peppa/ci" SHA=$(gitea_api "$GITEA_URL/api/v1/repos/$REPO/pulls/$PR" 2>/dev/null | python3 -c 'import json,sys;print(json.load(sys.stdin)["head"]["sha"])' 2>/dev/null) \ || { echo "PR $PR not found in $REPO" >&2; exit 2; } diff --git a/scripts/peppa-release.sh b/scripts/peppa-release.sh index 40d79fb0..7108d1a2 100755 --- a/scripts/peppa-release.sh +++ b/scripts/peppa-release.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Releases Peppa itself (PEP-18) from its own release directory, apart from the development # checkout: -# ~/peppa/repo.git bare clone of peppa-bot/peppa +# ~/peppa/repo.git bare clone of $GITEA_PLATFORM_REPO (peppa/peppa) # ~/peppa/releases/ git worktree at the commit (.env → ~/peppa/shared/.env) # ~/peppa/current symlink to the release the services run (launchd, ~/.local/bin) # @@ -20,7 +20,7 @@ set -uo pipefail RELEASES="${PEPPA_RELEASES_DIR:-$HOME/peppa}" PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}" QUEUE="${PEPPA_RELEASE_QUEUE:-$PEPPA_HOME/release-queue}" -REMOTE="${PEPPA_RELEASE_REMOTE:-https://git.telecom.quest/peppa-bot/peppa.git}" +REMOTE="${PEPPA_RELEASE_REMOTE:-${GITEA_URL:-https://git.telecom.quest}/${GITEA_PLATFORM_REPO:-peppa/peppa}.git}" KEY="${PEPPA_PLATFORM_KEY:-PEP}" HEALTH_URL="${PEPPA_RELEASE_HEALTH_URL:-http://127.0.0.1:3100/api/health}" HEALTH_TIMEOUT="${PEPPA_RELEASE_HEALTH_TIMEOUT:-120}" diff --git a/scripts/push-template.sh b/scripts/push-template.sh index c35896ff..78178309 100755 --- a/scripts/push-template.sh +++ b/scripts/push-template.sh @@ -5,7 +5,7 @@ cd "$(dirname "$0")/.." ROOT="$PWD" [ -f .env ] && set -a && . ./.env && set +a . scripts/gitea-lib.sh -REPO="${GITEA_TEMPLATE_REPO:-peppa-bot/template}" +REPO="${GITEA_TEMPLATE_REPO:-peppa/template}" OWNER="${REPO%%/*}"; NAME="${REPO##*/}" gitea_create_repo "$OWNER" "$NAME" "Peppa project template" ',"template":true' -- 2.45.2 From 044d6b9bf687a91e36db03046897ab39ae1c4c77 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 00:13:03 +0500 Subject: [PATCH 007/404] =?UTF-8?q?PEP-89:=20=C2=AB=D0=90=D0=B3=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D1=8B=20=D0=B7=D0=B0=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D0=B9=C2=BB=20=E2=80=94=20the=20agent's=20name=20a?= =?UTF-8?q?nd=20story=20up=20front,=20run=20details=20folded?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/web/app/(app)/page.tsx | 6 +- apps/web/app/(app)/runners/page.tsx | 2 +- apps/web/components/Sidebar.tsx | 2 +- apps/web/components/cards.tsx | 58 ++++++++++++++++++- apps/web/lib/status.ts | 15 ++--- apps/web/next-env.d.ts | 4 +- .../proposal.md | 15 +++++ .../specs/web-workspace/spec.md | 15 +++++ .../2026-11-15-pep-89-agents-at-work/tasks.md | 4 ++ openspec/specs/web-workspace/spec.md | 14 +++++ 10 files changed, 119 insertions(+), 16 deletions(-) create mode 100644 openspec/changes/archive/2026-11-15-pep-89-agents-at-work/proposal.md create mode 100644 openspec/changes/archive/2026-11-15-pep-89-agents-at-work/specs/web-workspace/spec.md create mode 100644 openspec/changes/archive/2026-11-15-pep-89-agents-at-work/tasks.md diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 7d80470d..30387c78 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -4,7 +4,7 @@ import { OnboardingChecklist } from "@/components/Onboarding"; import { PugBanner } from "@/components/PugMascot"; import { LiveRefresh } from "@/components/LiveRefresh"; import { ActivityAside } from "@/components/ActivityAside"; -import { ProjectList, QuestionCard, SessionCard } from "@/components/cards"; +import { AgentAtWork, ProjectList, QuestionCard } from "@/components/cards"; import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; @@ -28,8 +28,8 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
-
все раннеры}> - {sessions.length === 0 ? Сейчас ничего не запущено. : sessions.map((s) => )} +
вся работа агентов}> + {sessions.length === 0 ? Сейчас никто не работает: напишите задачу — и агент возьмёт её. : sessions.map((s) => )}
все проекты}> diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx index 3e0a932a..55132c23 100644 --- a/apps/web/app/(app)/runners/page.tsx +++ b/apps/web/app/(app)/runners/page.tsx @@ -62,7 +62,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise< 0 && ( Новый терминал}> diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 3e1b6171..f2387bcc 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -24,7 +24,7 @@ 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: "/runners", label: "Работа агентов", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, { href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 84057da0..763f6805 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -6,7 +6,7 @@ import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } fr import { Button } from "@/components/ui/button"; import { AgentBadge } from "@/components/AgentBadge"; import { Input } from "@/components/ui/input"; -import { ago, Empty, Key, StatusBadge } from "@/components/common"; +import { ago, Disclosure, Empty, Key, StatusBadge } from "@/components/common"; import { AgentSteps } from "@/components/AgentSteps"; import { RunnerTerminal } from "@/components/RunnerTerminal"; import { SessionUsageLine } from "@/components/Accounting"; @@ -87,7 +87,7 @@ export function SessionActions({ s, back }: { s: SessionView; back: string }) { {alive && (
- + + )} + + + + ); +} + export function ProjectList({ projects, userId }: { projects: Array; userId: number }) { if (!projects.length) return ( diff --git a/apps/web/lib/status.ts b/apps/web/lib/status.ts index 19a42d1c..08475ead 100644 --- a/apps/web/lib/status.ts +++ b/apps/web/lib/status.ts @@ -11,15 +11,16 @@ export const TASK_STATUS: Record = { blocked: { label: "Блок", tone: "danger" }, }; +// PEP-89: said about an agent, in plain words — the reader is a product manager. export const SESSION_STATUS: Record = { - starting: { label: "запуск", tone: "info" }, + starting: { label: "запускается", tone: "info" }, running: { label: "работает", tone: "info" }, - waiting_input: { label: "ждёт тебя", tone: "primary" }, - idle: { label: "простаивает", tone: "muted" }, - stalled: { label: "зависла?", tone: "warn" }, - rate_limited: { label: "лимит", tone: "warn" }, - done: { label: "завершена", tone: "ok" }, - failed: { label: "упала", tone: "danger" }, + waiting_input: { label: "ждёт вашего ответа", tone: "primary" }, + idle: { label: "свободен", tone: "muted" }, + stalled: { label: "остановился — нужна помощь", tone: "warn" }, + rate_limited: { label: "ждёт сброса лимита", tone: "warn" }, + done: { label: "закончил", tone: "ok" }, + failed: { label: "остановился с ошибкой", tone: "danger" }, }; /** Text colour per tone, e.g. for status dots. */ diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts index ce4e94a6..a419cbe4 100644 --- a/apps/web/next-env.d.ts +++ b/apps/web/next-env.d.ts @@ -1,7 +1,7 @@ /// /// -import "./.next/types/routes.d.ts"; -import "./.next/types/root-params.d.ts"; +import "./.next/dev/types/routes.d.ts"; +import "./.next/dev/types/root-params.d.ts"; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/proposal.md b/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/proposal.md new file mode 100644 index 00000000..1c0b2d6a --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/proposal.md @@ -0,0 +1,15 @@ +# PEP-89: «Агенты за работой» вместо раннеров + +## Why +PM: «активные раннеры — это кто, агенты? мы договорились, что у них будут имена». Имена есть (PEP-75), но показаны +мелким значком, а заголовки и статусы — технические: «раннер», `tmux attach`, «ждёт тебя», «зависла?». + +## What Changes +- Главная: раздел «Агенты за работой», карточка `AgentAtWork` — крупно имя агента и «работает над <задача>», состояние словами; + номер запуска, провайдер, подписка, команда терминала и расход — под «Подробнее». +- Состояния запусков человеческими словами и на «вы»: «ждёт вашего ответа», «свободен», «остановился — нужна помощь», + «ждёт сброса лимита», «закончил», «остановился с ошибкой». +- Меню и заголовок страницы: «Работа агентов» вместо «Раннеры»; поле сообщения — «Написать агенту». +- Живым запускам без имени (стартовали до PEP-75) имя выдано разово через `ensureSessionAgent`. + +Вне scope: полный «простой вид» для продактов. Открытых вопросов нет. diff --git a/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/specs/web-workspace/spec.md new file mode 100644 index 00000000..4c00f717 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/specs/web-workspace/spec.md @@ -0,0 +1,15 @@ +## ADDED Requirements + +### Requirement: Агенты за работой +Главная SHALL показывать работающих агентов разделом «Агенты за работой»: в карточке — имя +агента, задача, над которой он работает, и состояние простыми словами. Технические сведения +о запуске SHALL быть скрыты под «Подробнее». + +#### Scenario: Агент работает +- **GIVEN** агент «Мадина» ведёт стори PEP-4 +- **WHEN** владелец проекта открывает Главную +- **THEN** он видит «Мадина», «работает над PEP-4» и название стори; номер запуска и команда терминала не видны, пока не раскрыто «Подробнее» + +#### Scenario: Агент ждёт ответа +- **WHEN** агент задал вопрос и ждёт +- **THEN** в карточке состояние «ждёт вашего ответа» diff --git a/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/tasks.md b/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/tasks.md new file mode 100644 index 00000000..70148517 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-89-agents-at-work/tasks.md @@ -0,0 +1,4 @@ +- [x] 1 Карточка `AgentAtWork`, раздел на Главной +- [x] 2 Состояния словами, «Работа агентов» в меню и заголовке +- [x] 3 Имена запускам без имени на живой базе +- [x] 4 Проверка в браузере (копия на порту 3111), `openspec validate` diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md index 12bfb664..aabb9187 100644 --- a/openspec/specs/web-workspace/spec.md +++ b/openspec/specs/web-workspace/spec.md @@ -416,3 +416,17 @@ PM SHALL уметь убрать стори в архив и вернуть её - **GIVEN** стори, не привязанная к эпику - **WHEN** участник открывает вкладку «Эпики» - **THEN** стори показана в блоке «Стори без эпика» + +### Requirement: Агенты за работой +Главная SHALL показывать работающих агентов разделом «Агенты за работой»: в карточке — имя +агента, задача, над которой он работает, и состояние простыми словами. Технические сведения +о запуске SHALL быть скрыты под «Подробнее». + +#### Scenario: Агент работает +- **GIVEN** агент «Мадина» ведёт стори PEP-4 +- **WHEN** владелец проекта открывает Главную +- **THEN** он видит «Мадина», «работает над PEP-4» и название стори; номер запуска и команда терминала не видны, пока не раскрыто «Подробнее» + +#### Scenario: Агент ждёт ответа +- **WHEN** агент задал вопрос и ждёт +- **THEN** в карточке состояние «ждёт вашего ответа» -- 2.45.2 From bc9f53fddc8cc7105e44e178842f42498ff39d3d 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 00:26:03 +0500 Subject: [PATCH 008/404] PEP-4: project memory and tasks after the live transfer to the peppa organization Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 3 +++ openspec/changes/pep-4-gitea-org/tasks.md | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.peppa/memory.md b/.peppa/memory.md index f1299459..f49a7a25 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -3,8 +3,11 @@ Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения. ## Грабли +- peppa-bot не может создавать организации в Gitea (403, флаг пользователя) — организацию создаёт админ Gitea и добавляет бота в Owners; после переноса раннер уровня peppa-bot репо не покрывает, нужен свой (`setupCi` / `peppa ci connect`). +- Общая рабочая копия может стоять на чужой ветке — работай в `git worktree`; CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `/packages/cli/bin/peppa …`. - Один файл e2e: `env -u NODE_TEST_CONTEXT node --test --test-reporter=spec test/.test.ts` (внутри сессии Claude без этого вывод бинарный); CLI из теста с моком в том же процессе — только async execFile, execFileSync вешает мок. - node --test из шелла Claude Code молча ничего не запускает («run() is being called recursively») — в env висит NODE_TEST_CONTEXT; запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test …` ## Решения +- Репозитории платформы — в организации 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. diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/pep-4-gitea-org/tasks.md index ab36a13e..55d8f69c 100644 --- a/openspec/changes/pep-4-gitea-org/tasks.md +++ b/openspec/changes/pep-4-gitea-org/tasks.md @@ -16,11 +16,11 @@ ## 3. Перенос на живой системе (после одобрения PM и мержа кода) -- [ ] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners -- [ ] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa` -- [ ] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит +- [x] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners +- [x] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa` +- [x] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит - [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa` -- [ ] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект) +- [x] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект) ## Workflow follow-up -- 2.45.2 From 36f67bc2f834df91681914449624c755464aa336 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 00:33:03 +0500 Subject: [PATCH 009/404] PEP-4: archive the OpenSpec change (project-provisioning: repo transfer; peppa-ci: peppa/peppa) Co-Authored-By: Claude Fable 5.2 --- .../.openspec.yaml | 0 .../2026-11-15-pep-4-gitea-org}/design.md | 0 .../2026-11-15-pep-4-gitea-org}/proposal.md | 0 .../specs/peppa-ci/spec.md | 0 .../specs/project-provisioning/spec.md | 0 .../2026-11-15-pep-4-gitea-org}/tasks.md | 4 +-- openspec/specs/peppa-ci/spec.md | 5 +-- openspec/specs/project-provisioning/spec.md | 35 +++++++++++++++++++ 8 files changed, 40 insertions(+), 4 deletions(-) rename openspec/changes/{pep-4-gitea-org => archive/2026-11-15-pep-4-gitea-org}/.openspec.yaml (100%) rename openspec/changes/{pep-4-gitea-org => archive/2026-11-15-pep-4-gitea-org}/design.md (100%) rename openspec/changes/{pep-4-gitea-org => archive/2026-11-15-pep-4-gitea-org}/proposal.md (100%) rename openspec/changes/{pep-4-gitea-org => archive/2026-11-15-pep-4-gitea-org}/specs/peppa-ci/spec.md (100%) rename openspec/changes/{pep-4-gitea-org => archive/2026-11-15-pep-4-gitea-org}/specs/project-provisioning/spec.md (100%) rename openspec/changes/{pep-4-gitea-org => archive/2026-11-15-pep-4-gitea-org}/tasks.md (96%) diff --git a/openspec/changes/pep-4-gitea-org/.openspec.yaml b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/.openspec.yaml similarity index 100% rename from openspec/changes/pep-4-gitea-org/.openspec.yaml rename to openspec/changes/archive/2026-11-15-pep-4-gitea-org/.openspec.yaml diff --git a/openspec/changes/pep-4-gitea-org/design.md b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/design.md similarity index 100% rename from openspec/changes/pep-4-gitea-org/design.md rename to openspec/changes/archive/2026-11-15-pep-4-gitea-org/design.md diff --git a/openspec/changes/pep-4-gitea-org/proposal.md b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/proposal.md similarity index 100% rename from openspec/changes/pep-4-gitea-org/proposal.md rename to openspec/changes/archive/2026-11-15-pep-4-gitea-org/proposal.md diff --git a/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/specs/peppa-ci/spec.md similarity index 100% rename from openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md rename to openspec/changes/archive/2026-11-15-pep-4-gitea-org/specs/peppa-ci/spec.md diff --git a/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/specs/project-provisioning/spec.md similarity index 100% rename from openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md rename to openspec/changes/archive/2026-11-15-pep-4-gitea-org/specs/project-provisioning/spec.md diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/tasks.md similarity index 96% rename from openspec/changes/pep-4-gitea-org/tasks.md rename to openspec/changes/archive/2026-11-15-pep-4-gitea-org/tasks.md index 55d8f69c..f7927480 100644 --- a/openspec/changes/pep-4-gitea-org/tasks.md +++ b/openspec/changes/archive/2026-11-15-pep-4-gitea-org/tasks.md @@ -12,14 +12,14 @@ - [x] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck` - [x] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов - [x] 2.3 Документация: `AGENTS.md` (где репозиторий платформы, команда переноса; в `docs/HANDOFF.md` и `/help` адресов платформы нет — без правок) — проверка: вычитка, ссылки на `peppa/peppa` -- [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI +- [x] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI ## 3. Перенос на живой системе (после одобрения PM и мержа кода) - [x] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners - [x] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa` - [x] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит -- [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa` +- [x] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa` - [x] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект) ## Workflow follow-up diff --git a/openspec/specs/peppa-ci/spec.md b/openspec/specs/peppa-ci/spec.md index 7ef8ce59..33300d74 100644 --- a/openspec/specs/peppa-ci/spec.md +++ b/openspec/specs/peppa-ci/spec.md @@ -28,7 +28,8 @@ - **THEN** e2e выполняется три раза подряд («ci: ok e2e 1/3» … «ci: ok e2e 3/3»), сборка веба пропущена ### Requirement: Статус проверки в PR -`scripts/ci.sh --pr ` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном +`scripts/ci.sh --pr ` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория платформы +(`GITEA_PLATFORM_REPO`, по умолчанию `peppa/peppa`) в отдельном временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем `success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. @@ -50,7 +51,7 @@ - **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 ### Requirement: Проверки на каждый PR в Gitea Actions -Workflow `.gitea/workflows/ci.yml` репозитория `peppa-bot/peppa` SHALL на каждый PR из ветки этого +Workflow `.gitea/workflows/ci.yml` репозитория `peppa/peppa` SHALL на каждый PR из ветки этого репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57), с тестовой БД `peppa_test_ci_r` на Postgres хоста, и выставлять статус коммита `peppa-ci / ci (pull_request)`; PR из форков не запускаются. diff --git a/openspec/specs/project-provisioning/spec.md b/openspec/specs/project-provisioning/spec.md index 20cba60b..218c561e 100644 --- a/openspec/specs/project-provisioning/spec.md +++ b/openspec/specs/project-provisioning/spec.md @@ -145,3 +145,38 @@ - **WHEN** админ выполняет `peppa project visibility --all public` - **THEN** оба репозитория публичные, по строке на проект - **AND** `peppa project visibility --all private` возвращает их обратно + +### Requirement: Перенос репозитория проекта в другое пространство +Команда `peppa project transfer ` SHALL переносить репозиторий проекта в пространство +`` (организация или пользователь Gitea) и приводить проект в рабочее состояние по новому +адресу: адрес проекта в Пеппе, `origin` рабочей копии, раннер CI, секрет и вебхук. Повторный запуск +после частичного сбоя SHALL доводить перенос до конца без ошибки. + +#### Scenario: Перенос в организацию +- **GIVEN** проект `DEMO` с репозиторием `peppa-bot/demo` и организация `acme`, где `peppa-bot` — владелец +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** репозиторий доступен как `acme/demo`, вывод — «DEMO: peppa-bot/demo → acme/demo» +- **AND** страница проекта в вебе ссылается на `acme/demo` +- **AND** `git remote get-url origin` в рабочей копии оканчивается на `/acme/demo.git` +- **AND** в журнале проекта есть событие «репозиторий перенесён» со старым и новым адресом + +#### Scenario: CI после переноса +- **GIVEN** проект `DEMO` с подключённым CI перенесён из `peppa-bot/demo` в `acme/demo` +- **WHEN** в `acme/demo` открывается PR +- **THEN** проверки `peppa/*` выполняются на раннере Пеппы и их отчёты приходят на карточку стори + +#### Scenario: Повторный запуск +- **GIVEN** репозиторий проекта `DEMO` уже находится в `acme/demo`, а в Пеппе записан `peppa-bot/demo` +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** перенос в Gitea не запрашивается, адрес проекта и `origin` становятся `acme/demo`, код выхода 0 + +#### Scenario: Пространства нет или нет прав +- **GIVEN** организации `nope` в Gitea нет +- **WHEN** выполняется `peppa project transfer DEMO nope` +- **THEN** выводится «Пространство nope не найдено или у peppa-bot нет прав создавать в нём репозитории», код выхода 1 +- **AND** репозиторий остаётся `peppa-bot/demo`, адрес проекта в Пеппе не меняется + +#### Scenario: В пространстве уже есть такой репозиторий +- **GIVEN** в организации `acme` уже есть другой репозиторий `demo` +- **WHEN** выполняется `peppa project transfer DEMO acme` +- **THEN** выводится «Репозиторий acme/demo уже существует», код выхода 1, ничего не меняется -- 2.45.2 From 6e54fc69a6e9086d510bd024727dc865d5421088 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 12:39:46 +0500 Subject: [PATCH 010/404] =?UTF-8?q?PEP-91:=20Peppa=20reports=20its=20own?= =?UTF-8?q?=20errors=20to=20Bugsink=20=E2=80=94=20backend=20to=20PEP-api,?= =?UTF-8?q?=20browser=20to=20PEP-web?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/bot/src/bot.ts | 2 + apps/bot/src/index.ts | 3 + apps/web/app/api/client-errors/route.ts | 42 ++++ apps/web/app/layout.tsx | 6 +- apps/web/components/ErrorReporter.tsx | 39 ++++ apps/web/instrumentation.ts | 18 +- .../pep-91-platform-errors/proposal.md | 32 +++ .../specs/error-tracking/spec.md | 22 ++ .../changes/pep-91-platform-errors/tasks.md | 15 ++ packages/cli/src/index.ts | 17 +- packages/core/src/error-report.ts | 211 ++++++++++++++++++ packages/core/src/index.ts | 1 + packages/runner/src/incidents.ts | 5 + packages/runner/src/watchdog.ts | 52 +++-- packages/testkit/src/mock-bugsink.ts | 26 +++ packages/testkit/test/platform-errors.test.ts | 108 +++++++++ 17 files changed, 575 insertions(+), 25 deletions(-) create mode 100644 apps/web/app/api/client-errors/route.ts create mode 100644 apps/web/components/ErrorReporter.tsx create mode 100644 openspec/changes/pep-91-platform-errors/proposal.md create mode 100644 openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md create mode 100644 openspec/changes/pep-91-platform-errors/tasks.md create mode 100644 packages/core/src/error-report.ts create mode 100644 packages/testkit/test/platform-errors.test.ts diff --git a/AGENTS.md b/AGENTS.md index 6600b08f..eeb48970 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,6 +46,7 @@ - **Перенос репозитория проекта (PEP-4)**: `peppa project transfer ` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo---`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно - **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` +- **Свои ошибки Пеппы (PEP-91)**: проект `PEP` подключён к Bugsink как любой (`peppa project errors ` = `connectErrorTrackingFromEnv`), бэк → `PEP-api`, фронт → `PEP-web`. Отправитель без SDK — `core/error-report.ts` (`reportPlatformError`: envelope `POST /api//envelope/`, DSN источников проекта `PEPPA_PLATFORM_KEY` из БД (кэш 5 мин) или `PEPPA_ERRORS_DSN_API`/`_WEB`, `release` = `peppaCommit()`, `environment` = `PEPPA_ENVIRONMENT` (live), теги `service`/`where`; не бросает, 3 с, одна ошибка раз в минуту, ≤30/мин, `PEPPA_ERRORS=off`). Кто шлёт: `onRequestError` в `instrumentation.ts`, вачдог (`failed(db, log, часть)` вместо голого `log`), бот (`handleUpdate`), падения процессов (`installCrashReporting`: отправить и `exit 1`); браузер — `components/ErrorReporter.tsx` → `POST /api/client-errors` (без входа, ≤16 КБ, 20/мин на IP). Мок — envelope в `mock-bugsink` (`ingested`), тест `platform-errors.test.ts` - **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ``, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` - **Вход только eGov (PEP-71)**: Gitea-вход и пароль убраны из веба (маршрутов `/auth/start|callback|password` нет). Неизвестный ИИН → `registerEgovUser` (core/egov.ts): учётка `gitea_id < 0` без пароля, логин `egovLoginBase` из имени сертификата («ИВАНОВА АЙГЕРИМ» → `aigerim.ivanova`, дубль `-2`, без имени `user-<4 цифры>`). Самозарегистрированный владелец (без Gitea и пароля, не админ/allowlist) без пула не получает вход машины для агентов — `mayUseMachineLogin` (core/access.ts) в `startSession`. Старым учёткам ИИН — «Настройки» (пока залогинен) или `peppa user egov`; аварийный вход — `peppa web login-link` - **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из stdin или сгенерированный) diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 419df6e8..0da94323 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -2,6 +2,7 @@ // alerts) to the paired chat and turns button presses / replies into answers delivered // back into the agent session. Telegram is an adapter over the DB, not a remote shell: // it can only answer a specific pending question or resume/stop the session it is about. +import { reportPlatformError } from "@peppa/core"; import { accountUsageForUser, describeUsage, @@ -701,6 +702,7 @@ export function createBot(o: BotOptions) { await finishUpdate(db, u.update_id, r, botUserId); } catch (e) { log(`update ${u.update_id}: ${(e as Error).stack ?? e}`); + void reportPlatformError(db, e, { service: "bot", where: u.message ? "message" : u.callback_query ? `button ${u.callback_query.data ?? ""}`.slice(0, 60) : "update" }); await finishUpdate(db, u.update_id, "failed", botUserId); } } diff --git a/apps/bot/src/index.ts b/apps/bot/src/index.ts index 594f6e49..64ef3cd4 100644 --- a/apps/bot/src/index.ts +++ b/apps/bot/src/index.ts @@ -2,6 +2,7 @@ import { createDb } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { setRunnerClient } from "@peppa/runner"; +import { installCrashReporting } from "@peppa/core"; import { createBot } from "./bot.ts"; import { TelegramApi } from "./telegram.ts"; @@ -13,6 +14,8 @@ if (!env.TELEGRAM_BOT_TOKEN) { const db = createDb(env.PEPPA_DB); // PEP-21: the bot only enqueues runner commands; the runner service (watchdog) runs them. setRunnerClient(true, db); +// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it. +installCrashReporting(db, "bot"); const bot = createBot({ db, api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL), diff --git a/apps/web/app/api/client-errors/route.ts b/apps/web/app/api/client-errors/route.ts new file mode 100644 index 00000000..8d929f49 --- /dev/null +++ b/apps/web/app/api/client-errors/route.ts @@ -0,0 +1,42 @@ +// PEP-91: errors from the browser (ErrorReporter) → Bugsink, source `web` of the platform project. +// No login needed (the login page breaks too): size cap and a per-IP limit instead. +import { reportPlatformError } from "@peppa/core"; +import { db } from "@/lib/db"; + +const MAX_BYTES = 16 * 1024; +const PER_IP_PER_MIN = 20; +const hits = new Map(); + +function limited(ip: string, now = Date.now()): boolean { + const h = hits.get(ip); + if (!h || now - h.at >= 60_000) { + if (hits.size > 5000) hits.clear(); + hits.set(ip, { at: now, n: 1 }); + return false; + } + return ++h.n > PER_IP_PER_MIN; +} + +const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max) : undefined); + +export async function POST(req: Request) { + const ip = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local"; + if (limited(ip)) return new Response(null, { status: 429 }); + const raw = await req.text(); + if (raw.length > MAX_BYTES) return new Response(null, { status: 413 }); + let b: Record; + try { + b = JSON.parse(raw) as Record; + } catch { + return new Response(null, { status: 400 }); + } + const message = str(b.message, 2000); + if (!message) return new Response(null, { status: 400 }); + const path = str(b.url, 500); + const sent = await reportPlatformError( + db, + { name: str(b.type, 100) || "Error", message, stack: str(b.stack, 8000) }, + { service: "browser", kind: "web", platform: "javascript", where: path?.split("?")[0], request: { url: path, method: "GET", userAgent: req.headers.get("user-agent") ?? undefined } }, + ); + return Response.json({ sent }); +} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 5259483f..71f6ad47 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -4,6 +4,7 @@ import { GeistSans } from "geist/font/sans"; import { GeistMono } from "geist/font/mono"; import { cn } from "@/lib/utils"; import { THEME_COOKIE } from "@/lib/theme"; +import { ErrorReporter } from "@/components/ErrorReporter"; import "./app.css"; export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты", icons: { icon: "/icon.svg" } }; @@ -13,7 +14,10 @@ export default async function RootLayout({ children }: { children: ReactNode }) const light = (await cookies()).get(THEME_COOKIE)?.value === "light"; return ( - {children} + + + {children} + ); } diff --git a/apps/web/components/ErrorReporter.tsx b/apps/web/components/ErrorReporter.tsx new file mode 100644 index 00000000..56d3d123 --- /dev/null +++ b/apps/web/components/ErrorReporter.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { useEffect } from "react"; + +const MAX_PER_PAGE = 10; + +/** PEP-91: browser errors of Peppa's own pages → /api/client-errors → Bugsink (PEP-web). */ +export function ErrorReporter() { + useEffect(() => { + let sent = 0; + const seen = new Set(); + const send = (type: string, message: string, stack?: string) => { + const key = `${type}|${message}`; + if (sent >= MAX_PER_PAGE || seen.has(key) || !message) return; + seen.add(key); + sent++; + const body = JSON.stringify({ type, message: message.slice(0, 2000), stack: stack?.slice(0, 8000), url: location.pathname + location.search }); + void fetch("/api/client-errors", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).catch(() => {}); + }; + const onError = (ev: ErrorEvent) => { + const e = ev.error as Error | undefined; + // "Script error." comes from cross-origin scripts without details: nothing to act on. + if (!e && (!ev.message || ev.message === "Script error.")) return; + send(e?.name ?? "Error", e?.message ?? ev.message, e?.stack ?? (ev.filename ? ` at ${ev.filename}:${ev.lineno}:${ev.colno}` : undefined)); + }; + const onRejection = (ev: PromiseRejectionEvent) => { + const r = ev.reason as Error | string | undefined; + if (r instanceof Error) send(r.name, r.message, r.stack); + else send("UnhandledRejection", typeof r === "string" ? r : JSON.stringify(r) ?? ""); + }; + window.addEventListener("error", onError); + window.addEventListener("unhandledrejection", onRejection); + return () => { + window.removeEventListener("error", onError); + window.removeEventListener("unhandledrejection", onRejection); + }; + }, []); + return null; +} diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts index 98b8e31e..79c32d4e 100644 --- a/apps/web/instrumentation.ts +++ b/apps/web/instrumentation.ts @@ -2,8 +2,10 @@ // and the runner-client mode (PEP-21): the web enqueues runner commands, the watchdog runs them. export async function register() { if (process.env.NEXT_RUNTIME !== "nodejs") return; - const { beat } = await import("@peppa/core"); + const { beat, installCrashReporting } = await import("@peppa/core"); const { db } = await import("@/lib/db"); + // PEP-91: a crash of the web goes to Bugsink before launchd restarts it. + installCrashReporting(db, "web"); const { setRunnerClient } = await import("@peppa/runner"); setRunnerClient(true, db); const version = process.env.NEXT_PUBLIC_PEPPA_VERSION; @@ -11,3 +13,17 @@ export async function register() { void tick(); setInterval(tick, 60_000).unref(); } + +/** PEP-91: an error while rendering or handling a request → Bugsink (PEP-api). */ +export async function onRequestError(err: unknown, request: { path: string; method: string; headers: Record }, context: { routerKind: string; routePath: string; routeType: string }) { + if (process.env.NEXT_RUNTIME !== "nodejs") return; + const { reportPlatformError } = await import("@peppa/core"); + const { db } = await import("@/lib/db"); + const ua = request.headers["user-agent"]; + await reportPlatformError(db, err, { + service: "web", + where: `${request.method} ${context.routePath}`, + request: { url: request.path, method: request.method, userAgent: typeof ua === "string" ? ua : undefined }, + tags: { route_type: context.routeType }, + }); +} diff --git a/openspec/changes/pep-91-platform-errors/proposal.md b/openspec/changes/pep-91-platform-errors/proposal.md new file mode 100644 index 00000000..b1442f63 --- /dev/null +++ b/openspec/changes/pep-91-platform-errors/proposal.md @@ -0,0 +1,32 @@ +# Proposal: PEP-91 — Пеппа ловит свои ошибки + +Задача Пеппы: **PEP-91**. + +## Why + +15.11 живой сайт отдавал 500 всем вошедшим (`no such column: "google_sub"`: схема из рабочей +копии опередила миграцию). Узнали об этом от PM. Bugsink (PEP-58) уже ловит ошибки проектов +на фабрике, но сама Пеппа к нему не подключена: её ошибки остаются в логах launchd. + +## What Changes + +- Проект `PEP` подключается к Bugsink как любой проект: источники `PEP-web` и `PEP-api`, + вебхук, цель «Стабильность», политика `backlog`. Новая команда CLI + `peppa project errors ` делает то же, что кнопка «Подключить отслеживание ошибок». +- Свой лёгкий отправитель по протоколу Sentry (`core/error-report.ts`, без внешнего SDK): + envelope `POST /api//envelope/`, `X-Sentry-Auth`, стек V8 → frames, `release` = коммит + процесса, `environment` = `PEPPA_ENVIRONMENT` (по умолчанию `live`), теги `service`, `where`. + DSN — источники платформенного проекта (`PEPPA_PLATFORM_KEY`) из БД (кэш 5 мин) или + `PEPPA_ERRORS_DSN_API`/`_WEB`; адрес приёма — `BUGSINK_URL` (внутренний), иначе хост DSN. + Никогда не бросает, тайм-аут 3 с, одна и та же ошибка не чаще раза в минуту на процесс, + не больше 30 в минуту. `PEPPA_ERRORS=off` выключает. +- Кто отправляет (`api`): сервер веба (`onRequestError` в `instrumentation.ts`), вачдог + (ошибки частей тика и сессий), бот (обработка обновлений), падения процессов веб/бот/вачдог + (`uncaughtException`/`unhandledRejection`: отправить и упасть, как раньше). +- Браузер (`web`): `ErrorReporter` в корневом layout ловит `error`/`unhandledrejection` и шлёт + в `POST /api/client-errors` (≤16 КБ, 20 в минуту на IP, не больше 10 со страницы); веб + пересылает в `PEP-web`. DSN в браузер не попадает. + +## Вне scope + +Source maps, трейсинг, ошибки агентов в tmux. diff --git a/openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md b/openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md new file mode 100644 index 00000000..fc9bf97c --- /dev/null +++ b/openspec/changes/pep-91-platform-errors/specs/error-tracking/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: Ошибки самой Пеппы уходят в Bugsink +Пеппа SHALL отправлять свои ошибки (сервер веба, браузер, бот, вачдог, падения процессов) в +источники Bugsink платформенного проекта по протоколу Sentry, без внешнего SDK и не ломая работу +при недоступном Bugsink. + +#### Scenario: Ошибка сервера веба +- **WHEN** запрос к вебу падает с исключением, а у проекта `PEP` есть источник `api` +- **THEN** в Bugsink уходит envelope с типом и текстом ошибки, стеком, `release` = коммит, тегом `service=web` и адресом запроса + +#### Scenario: Ошибка в браузере +- **WHEN** на странице Пеппы случается необработанная ошибка JS +- **THEN** браузер шлёт её в `/api/client-errors`, веб пересылает в источник `web`; DSN браузеру не выдаётся + +#### Scenario: Шум и недоступность +- **WHEN** одна и та же ошибка повторяется много раз в минуту или Bugsink не отвечает +- **THEN** отправляется не больше одной такой ошибки в минуту, а вызывающий код не получает исключения и не ждёт дольше 3 секунд + +#### Scenario: Не подключено +- **WHEN** у платформенного проекта нет источников и env DSN не задан, или `PEPPA_ERRORS=off` +- **THEN** ничего не отправляется diff --git a/openspec/changes/pep-91-platform-errors/tasks.md b/openspec/changes/pep-91-platform-errors/tasks.md new file mode 100644 index 00000000..efe6ff73 --- /dev/null +++ b/openspec/changes/pep-91-platform-errors/tasks.md @@ -0,0 +1,15 @@ +## 1. Отправитель +- [x] 1.1 `core/error-report.ts`: `parseDsn`, `errorEvent` (стек V8 → frames), `bugsinkEnvelope`, `reportPlatformError` (DSN из env/БД, троттлинг, тайм-аут, выключатель) +- [x] 1.2 `installCrashReporting(db, service)` — падение процесса: отправить и выйти с кодом 1 + +## 2. Кто отправляет +- [x] 2.1 Веб: `onRequestError` в `instrumentation.ts`, `installCrashReporting` в `register` +- [x] 2.2 Браузер: `components/ErrorReporter.tsx` + `POST /api/client-errors` (лимиты) +- [x] 2.3 Вачдог: ошибки частей тика и сессий; `installCrashReporting` в `peppa watchdog` +- [x] 2.4 Бот: ошибки обработки обновлений; `installCrashReporting` + +## 3. Подключение +- [x] 3.1 CLI `peppa project errors ` (= `connectErrorTracking`) +- [x] 3.2 `mock-bugsink`: приём envelope (`events`), e2e `platform-errors.test.ts` +- [x] 3.3 AGENTS.md +- [ ] 3.4 На живой системе: `peppa project errors PEP` (координатор после мержа) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index badc4571..e9ab527d 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -74,6 +74,8 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core"; import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core"; import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core"; +import { connectErrorTrackingFromEnv } from "@peppa/runner"; +import { installCrashReporting } from "@peppa/core"; import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; @@ -88,6 +90,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project agent [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit) peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) peppa project transfer (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook) + peppa project errors (PEP-58/91: connect to Bugsink — -web and -api, webhook, goal «Стабильность») peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back) peppa project list peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) @@ -293,6 +296,14 @@ async function main(): Promise { console.log(`${p.key} owner → ${u?.login ?? "none"}`); break; } + case "project errors": { + if (!args[0]) throw new PeppaError("usage: peppa project errors "); + const p = await getProject(db, args[0]); + const r = await connectErrorTrackingFromEnv(db, p); + for (const s of r.sources) console.log(`${s.kind}: Bugsink project #${s.bugsinkProjectId}`); + console.log(`webhook: ${r.settings.webhookAuto ? "set automatically" : `add a Custom webhook in Bugsink → ${r.webhookUrl}`}`); + break; + } case "project import-issues": { if (!args[0]) throw new PeppaError("usage: peppa project import-issues "); const p = await getProject(db, args[0]); @@ -832,7 +843,11 @@ async function main(): Promise { log: (m: string) => console.log(`${new Date().toISOString()} ${m}`), }; if (opts.once) await tick(db, wopts); - else await runWatchdog(db, wopts); + else { + // PEP-91: a crash of the watchdog goes to Bugsink before launchd restarts it. + installCrashReporting(db, "watchdog"); + await runWatchdog(db, wopts); + } break; } default: diff --git a/packages/core/src/error-report.ts b/packages/core/src/error-report.ts new file mode 100644 index 00000000..7186e847 --- /dev/null +++ b/packages/core/src/error-report.ts @@ -0,0 +1,211 @@ +// PEP-91: Peppa reports its own errors to Bugsink — the Sentry envelope protocol without an SDK. +// DSNs are the error sources of the platform project (PEPPA_PLATFORM_KEY, connected like any +// project, PEP-58) or PEPPA_ERRORS_DSN_API / _WEB. Never throws, never waits longer than 3 s. +import { randomBytes } from "node:crypto"; +import { hostname } from "node:os"; +import { and, eq } from "drizzle-orm"; +import { errorSources, projects, type Db } from "@peppa/db"; +import { peppaCommit, peppaVersion } from "./monitor.ts"; + +export type ErrorSourceKind = "api" | "web"; + +export interface ParsedDsn { + key: string; + origin: string; + projectId: string; +} + +/** `https://@host/` → parts; null for anything else. */ +export function parseDsn(dsn: string): ParsedDsn | null { + try { + const u = new URL(dsn); + const projectId = u.pathname.replace(/^\/+|\/+$/g, ""); + if (!u.username || !/^\d+$/.test(projectId)) return null; + return { key: decodeURIComponent(u.username), origin: u.origin, projectId }; + } catch { + return null; + } +} + +export interface StackFrame { + function?: string; + filename: string; + lineno?: number; + colno?: number; + in_app: boolean; +} + +const FRAME_RE = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/; + +/** V8 stack (`at fn (file:1:2)`) → Sentry frames, outermost first. */ +export function stackFrames(stack: string | undefined): StackFrame[] { + const frames: StackFrame[] = []; + for (const line of (stack ?? "").split("\n")) { + const m = FRAME_RE.exec(line); + if (!m) continue; + const filename = m[2]!.replace(/^file:\/\//, ""); + frames.push({ + function: m[1] || undefined, + filename, + lineno: Number(m[3]), + colno: Number(m[4]), + in_app: !/node_modules|^node:|^internal\//.test(filename), + }); + } + return frames.reverse().slice(-50); +} + +export interface ErrorContext { + service: string; + /** Which part failed: "tick: autonomy", "session #12", "GET /p/PEP"… */ + where?: string; + kind?: ErrorSourceKind; + platform?: "node" | "javascript"; + request?: { url?: string; method?: string; userAgent?: string }; + tags?: Record; + /** Overrides for tests. */ + release?: string | null; + environment?: string; +} + +export interface ErrorLike { + name?: string; + message?: string; + stack?: string; +} + +function asError(e: unknown): ErrorLike { + if (e instanceof Error) return e; + if (e && typeof e === "object" && "message" in e) return e as ErrorLike; + return { name: "Error", message: typeof e === "string" ? e : JSON.stringify(e) ?? String(e) }; +} + +/** A Sentry event for an error. */ +export function errorEvent(e: unknown, ctx: ErrorContext, at = new Date()) { + const err = asError(e); + const frames = stackFrames(err.stack); + const tags: Record = { service: ctx.service, ...(ctx.where ? { where: ctx.where.slice(0, 200) } : {}), ...ctx.tags }; + return { + event_id: randomBytes(16).toString("hex"), + timestamp: at.getTime() / 1000, + platform: ctx.platform ?? "node", + level: "error", + logger: ctx.service, + server_name: hostname(), + release: (ctx.release !== undefined ? ctx.release : peppaCommit()) ?? `peppa@${peppaVersion()}`, + environment: ctx.environment ?? process.env.PEPPA_ENVIRONMENT ?? "live", + tags, + ...(ctx.request ? { request: { url: ctx.request.url, method: ctx.request.method, headers: ctx.request.userAgent ? { "User-Agent": ctx.request.userAgent } : undefined } } : {}), + exception: { + values: [{ type: err.name || "Error", value: (err.message ?? "").slice(0, 2000), ...(frames.length ? { stacktrace: { frames } } : {}) }], + }, + }; +} +export type ErrorEvent = ReturnType; + +/** The envelope body for one event. */ +export function bugsinkEnvelope(dsn: string, event: ErrorEvent): string { + return [JSON.stringify({ event_id: event.event_id, dsn, sent_at: new Date().toISOString() }), JSON.stringify({ type: "event" }), JSON.stringify(event)].join("\n") + "\n"; +} + +/** POST one event; `ingestBase` (BUGSINK_URL on the same host) beats the DSN's public host. */ +export async function sendEvent(dsn: string, event: ErrorEvent, o: { ingestBase?: string; timeoutMs?: number } = {}): Promise { + const d = parseDsn(dsn); + if (!d) return false; + const base = (o.ingestBase || d.origin).replace(/\/$/, ""); + try { + const res = await fetch(`${base}/api/${d.projectId}/envelope/`, { + method: "POST", + headers: { "Content-Type": "application/x-sentry-envelope", "X-Sentry-Auth": `Sentry sentry_version=7, sentry_key=${d.key}, sentry_client=peppa/${peppaVersion()}` }, + body: bugsinkEnvelope(dsn, event), + signal: AbortSignal.timeout(o.timeoutMs ?? 3000), + }); + return res.ok; + } catch { + return false; + } +} + +const DSN_TTL = 5 * 60_000; +const dsnCache = new Map(); + +/** DSN of the platform project's source: env first, then the DB (cached 5 min). */ +export async function platformDsn(db: Db, kind: ErrorSourceKind, now = Date.now()): Promise { + const env = process.env[kind === "web" ? "PEPPA_ERRORS_DSN_WEB" : "PEPPA_ERRORS_DSN_API"]; + if (env) return env; + const hit = dsnCache.get(kind); + if (hit && now - hit.at < DSN_TTL) return hit.dsn; + const key = process.env.PEPPA_PLATFORM_KEY || "PEP"; + const [row] = await db + .select({ dsn: errorSources.dsn }) + .from(errorSources) + .innerJoin(projects, eq(projects.id, errorSources.projectId)) + .where(and(eq(projects.key, key), eq(errorSources.kind, kind))); + const dsn = row?.dsn ?? null; + dsnCache.set(kind, { dsn, at: now }); + return dsn; +} + +const SAME_ERROR_MS = 60_000; +const MAX_PER_MINUTE = 30; +const seen = new Map(); +let windowStart = 0; +let windowCount = 0; + +/** Throttle: one per fingerprint per minute, 30 a minute overall. Exported for tests. */ +export function shouldSend(fingerprint: string, now = Date.now()): boolean { + if (now - windowStart >= 60_000) { + windowStart = now; + windowCount = 0; + for (const [k, t] of seen) if (now - t >= SAME_ERROR_MS) seen.delete(k); + } + const last = seen.get(fingerprint); + if (last !== undefined && now - last < SAME_ERROR_MS) return false; + if (windowCount >= MAX_PER_MINUTE) return false; + seen.set(fingerprint, now); + windowCount++; + return true; +} + +export function resetErrorReporting() { + seen.clear(); + dsnCache.clear(); + windowStart = 0; + windowCount = 0; +} + +/** + * Report one of Peppa's own errors. Never throws; resolves to whether Bugsink took it + * (false when not connected, throttled, switched off or unreachable). + */ +export async function reportPlatformError(db: Db, e: unknown, ctx: ErrorContext): Promise { + try { + if (process.env.PEPPA_ERRORS === "off") return false; + const kind = ctx.kind ?? "api"; + const event = errorEvent(e, ctx); + const ex = event.exception.values[0]!; + const top = ex.stacktrace?.frames.at(-1); + if (!shouldSend(`${kind}|${ctx.service}|${ex.type}|${ex.value.slice(0, 200)}|${top?.filename ?? ""}:${top?.lineno ?? ""}`)) return false; + const dsn = await platformDsn(db, kind); + if (!dsn) return false; + return await sendEvent(dsn, event, { ingestBase: process.env.BUGSINK_URL }); + } catch { + return false; + } +} + +let crashInstalled = false; + +/** A process crash (uncaught exception / unhandled rejection) goes to Bugsink, then exit 1 as before. */ +export function installCrashReporting(db: Db, service: string, log: (m: string) => void = (m) => console.error(m)): void { + if (crashInstalled) return; + crashInstalled = true; + const crash = (kind: string) => (e: unknown) => { + log(`${service} ${kind}: ${(e as Error)?.stack ?? String(e)}`); + const done = () => process.exit(1); + setTimeout(done, 3500).unref(); + void reportPlatformError(db, e, { service, where: kind }).finally(done); + }; + process.on("uncaughtException", crash("uncaughtException")); + process.on("unhandledRejection", crash("unhandledRejection")); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e8663891..74d495ea 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,6 +15,7 @@ export * from "./users.ts"; export * from "./oauth.ts"; export * from "./access.ts"; export * from "./monitor.ts"; +export * from "./error-report.ts"; export * from "./backup.ts"; export * from "./repo-info.ts"; export * from "./incidents.ts"; diff --git a/packages/runner/src/incidents.ts b/packages/runner/src/incidents.ts index d47e965d..1cb8c269 100644 --- a/packages/runner/src/incidents.ts +++ b/packages/runner/src/incidents.ts @@ -292,6 +292,11 @@ export async function connectErrorTracking(db: Db, project: Project, client: Bug return { settings, sources: await listErrorSources(db, project.id), webhookUrl }; } +/** `peppa project errors ` (PEP-91): connect with the Bugsink configured in env. */ +export function connectErrorTrackingFromEnv(db: Db, project: Project): Promise { + return connectErrorTracking(db, project, bugsinkFromEnv(), bugsinkWebhookBase()); +} + /** Where Bugsink (in docker) reaches Peppa's web; PEPPA_WEB_URL by default. */ export function bugsinkWebhookBase(): string { return process.env.BUGSINK_WEBHOOK_BASE ?? process.env.PEPPA_WEB_URL ?? "http://localhost:3100"; diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 2d820d20..0eb62c77 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -24,7 +24,7 @@ import * as tmux from "./tmux.ts"; import { recordLimit } from "./limits.ts"; import { killRunner, resumeSession } from "./sessions.ts"; import { hostTick } from "./hosts.ts"; -import { getSubscription, isUsable } from "@peppa/core"; +import { getSubscription, isUsable, reportPlatformError } from "@peppa/core"; import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts"; import { monitorTick } from "./monitor.ts"; import { platformBuildTick } from "./platform-build.ts"; @@ -70,42 +70,50 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { try { await checkSession(db, s, opts, cfg, log); } catch (e) { - log(`session #${s.id}: ${(e as Error).message}`); + failed(db, log, `session #${s.id}`)(e); } } // PEP-28: planned automatic restarts, reminders/escalation, runners waiting for nobody. - await restartTick(db, { now, cfg, log }).catch((e) => log(`restarts: ${(e as Error).message}`)); - await remindTick(db, { now, cfg, log }).catch((e) => log(`reminders: ${(e as Error).message}`)); - await idleStopTick(db, { now, cfg, log }).catch((e) => log(`idle: ${(e as Error).message}`)); + await restartTick(db, { now, cfg, log }).catch(failed(db, log, "restarts")); + await remindTick(db, { now, cfg, log }).catch(failed(db, log, "reminders")); + await idleStopTick(db, { now, cfg, log }).catch(failed(db, log, "idle")); // Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup. - await runnerTick(db, { log }).catch((e) => log(`runners: ${(e as Error).message}`)); + await runnerTick(db, { log }).catch(failed(db, log, "runners")); // PEP-40: runner hosts — online/offline, load, versions (once a minute each). - await hostTick(db, { now: opts.now, log }).catch((e) => log(`hosts: ${(e as Error).message}`)); + await hostTick(db, { now: opts.now, log }).catch(failed(db, log, "hosts")); // Story budgets (PEP-43): over the limit → pause and ask the PM. - await budgetTick(db, { now: opts.now, log }).catch((e) => log(`budgets: ${(e as Error).message}`)); + await budgetTick(db, { now: opts.now, log }).catch(failed(db, log, "budgets")); // Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher. // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them. - await intakeTick(db, { now: opts.now, log }).catch((e) => log(`intake: ${(e as Error).message}`)); - await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`)); + await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake")); + await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy")); // Errors of running products (PEP-58): Bugsink poll + incident policies. - await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`)); + await incidentTick(db, { now: opts.now, log }).catch(failed(db, log, "incidents")); // Daily digest at each user's time (PEP-29); a no-op outside their window. - await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`)); + await digestTick(db, { now: opts.now, log }).catch(failed(db, log, "digest")); // PEP-60: platform channel — re-check a channel that isn't working yet, new builds, the // platform digest at its time. - await recheckPlatformChannel(db, { now: opts.now, log }).catch((e) => log(`platform channel: ${(e as Error).message}`)); - await platformBuildTick(db, { now: opts.now, log }).catch((e) => log(`platform build: ${(e as Error).message}`)); - await platformDigestTick(db, { now: opts.now, log }).catch((e) => log(`platform digest: ${(e as Error).message}`)); + await recheckPlatformChannel(db, { now: opts.now, log }).catch(failed(db, log, "platform channel")); + await platformBuildTick(db, { now: opts.now, log }).catch(failed(db, log, "platform build")); + await platformDigestTick(db, { now: opts.now, log }).catch(failed(db, log, "platform digest")); // PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour. - await syncChats(db, { now: opts.now }).catch((e) => log(`chats: ${(e as Error).message}`)); + await syncChats(db, { now: opts.now }).catch(failed(db, log, "chats")); const nowMs = (opts.now ?? new Date()).getTime(); if (nowMs - lastChatPrune >= 3600_000) { lastChatPrune = nowMs; - await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch((e) => log(`chats prune: ${(e as Error).message}`)); + await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch(failed(db, log, "chats prune")); } } let lastChatPrune = 0; +/** A part of the watchdog failed: log it and send it to Bugsink (PEP-91). */ +function failed(db: Db, log: (m: string) => void, where: string) { + return (e: unknown) => { + log(`${where}: ${(e as Error)?.message ?? e}`); + void reportPlatformError(db, e, { service: "watchdog", where }); + }; +} + async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) { if (s.tmuxName.startsWith("pending-")) return; const nowDate = opts.now ?? new Date(); @@ -219,18 +227,18 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS }); } while (!signal?.aborted) { - await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); + await tick(db, opts).catch(failed(db, log, "tick failed")); // Heartbeat and the check on the bot and the web (PEP-20). - await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`)); + await monitorTick(db, { log }).catch(failed(db, log, "monitor failed")); // CI results lost on the way (PEP-57): poll commit statuses about once a minute. if (Date.now() - lastCiPoll >= 60_000) { lastCiPoll = Date.now(); - await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`)); + await pollChecks(db).catch(failed(db, log, "ci poll failed")); // Reviews whose MCP process died before running them (PEP-26). - await reviewTick(db, log).catch((e) => log(`review tick failed: ${(e as Error).message}`)); + await reviewTick(db, log).catch(failed(db, log, "review tick failed")); } // Daily copy of the SQLite database (PEP-36); a no-op until a day has passed. - await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`)); + await backupDb(db, { log }).catch(failed(db, log, "backup failed")); await new Promise((r) => setTimeout(r, opts.intervalMs)); } await service?.stop(); diff --git a/packages/testkit/src/mock-bugsink.ts b/packages/testkit/src/mock-bugsink.ts index 9319f448..c1335d7b 100644 --- a/packages/testkit/src/mock-bugsink.ts +++ b/packages/testkit/src/mock-bugsink.ts @@ -69,6 +69,14 @@ export class MockBugsink { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { + const ingest = /^\/api\/(\d+)\/envelope\/$/.exec(req.url!.split("?")[0]!); + if (req.method === "POST" && ingest) { + void this.ingestEnvelope(Number(ingest[1]), String(req.headers["x-sentry-auth"] ?? ""), body).then((r) => { + res.writeHead(r.status, { "Content-Type": "application/json" }); + res.end(JSON.stringify(r.body)); + }); + return; + } const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {}); res.writeHead(r.status, { "Content-Type": "application/json" }); res.end(JSON.stringify(r.body ?? {})); @@ -157,6 +165,24 @@ export class MockBugsink { return issue.id; } + /** Envelopes taken by the ingest endpoint (PEP-91): the raw event as the SDK sent it. */ + readonly ingested: Array<{ projectId: number; event: Record }> = []; + + /** `POST /api//envelope/` like Bugsink's ingest: sentry_key must match the project's DSN. */ + async ingestEnvelope(projectId: number, auth: string, body: string): Promise<{ status: number; body: unknown }> { + const p = this.projects.get(projectId); + const key = /sentry_key=([^,\s]+)/.exec(auth)?.[1]; + if (!p || key !== p.key) return { status: 403, body: { error: "invalid sentry_key" } }; + const lines = body.split("\n").filter(Boolean); + const item = lines.findIndex((l, n) => n > 0 && (JSON.parse(l) as { type?: string }).type === "event"); + if (item < 0 || !lines[item + 1]) return { status: 400, body: { error: "no event item" } }; + const event = JSON.parse(lines[item + 1]!) as Record; + this.ingested.push({ projectId, event }); + const ex = event.exception?.values?.[0] ?? { type: "Error", value: String(event.message ?? "") }; + await this.capture(projectId, { type: ex.type, value: ex.value, frames: ex.stacktrace?.frames, environment: event.environment, release: event.release, level: event.level }); + return { status: 200, body: { id: event.event_id } }; + } + private async alert(i: Issue, reason: string) { const p = this.projects.get(i.project)!; if (!p.webhook) return; diff --git a/packages/testkit/test/platform-errors.test.ts b/packages/testkit/test/platform-errors.test.ts new file mode 100644 index 00000000..caa6c887 --- /dev/null +++ b/packages/testkit/test/platform-errors.test.ts @@ -0,0 +1,108 @@ +// PEP-91: Peppa's own errors → Bugsink (envelope protocol, no SDK): the platform project is +// connected like any project; server errors go to -api, browser errors to -web, +// the watchdog's failing parts too; throttled, never throwing, silent when not connected. +import assert from "node:assert/strict"; +import { after, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); + +const bugsink = await new MockBugsink().start(); +const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); +// Ingest goes to BUGSINK_URL (same host), not to the DSN's public host. +process.env.BUGSINK_URL = bugsink.url; + +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-91: Peppa reports its own errors to Bugsink", () => { + test("not connected → nothing is sent and nothing throws", async () => { + process.env.PEPPA_PLATFORM_KEY = "NOPE"; + core.resetErrorReporting(); + assert.equal(await core.reportPlatformError(db, new Error("boom"), { service: "web" }), false); + assert.equal(bugsink.ingested.length, 0); + }); + + test("parseDsn and V8 stack → frames (outermost first)", () => { + assert.deepEqual(core.parseDsn("https://abc123@bugsink.telecom.quest/4"), { key: "abc123", origin: "https://bugsink.telecom.quest", projectId: "4" }); + assert.equal(core.parseDsn("not a dsn"), null); + const frames = core.stackFrames("Error: x\n at inner (/app/packages/core/src/users.ts:43:17)\n at async outer (/app/node_modules/next/x.js:1:2)\n at node:internal/process:3:4"); + assert.equal(frames.length, 3); + assert.equal(frames.at(-1)!.function, "inner"); + assert.equal(frames.at(-1)!.in_app, true); + assert.equal(frames[1]!.in_app, false); + }); + + test("connected platform project: server error → -api with release, service and request", async () => { + const p = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = p.key; + core.resetErrorReporting(); + const r = await runner.connectErrorTracking(db, await core.getProject(db, p.key), client, "http://peppa.test"); + const api = r.sources.find((s) => s.kind === "api")!.bugsinkProjectId; + const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId; + + const err = new Error('no such column: "google_sub"'); + const ok = await core.reportPlatformError(db, err, { service: "web", where: "GET /", request: { url: "/", method: "GET" }, release: "abc1234", environment: "live" }); + assert.equal(ok, true); + const got = bugsink.ingested.at(-1)!; + assert.equal(got.projectId, api); + const ev = got.event as ReturnType; + assert.equal(ev.release, "abc1234"); + assert.equal(ev.environment, "live"); + assert.equal(ev.tags.service, "web"); + assert.equal(ev.tags.where, "GET /"); + assert.equal(ev.request?.url, "/"); + assert.equal(ev.exception.values[0]!.value, 'no such column: "google_sub"'); + assert.ok(ev.exception.values[0]!.stacktrace!.frames.length > 0); + // Bugsink grouped it into an issue — Peppa's own poll turns it into an incident of the project. + const issues = await client.listIssues(api); + assert.equal(issues.length, 1); + assert.equal(await runner.pollBugsink(db, client), 1); + const incidents = await core.listIncidents(db, (await core.getProject(db, p.key)).id); + assert.equal(incidents.length, 1); + + // Same error again within a minute: throttled, not sent. + assert.equal(await core.reportPlatformError(db, err, { service: "web", where: "GET /", release: "abc1234" }), false); + assert.equal(bugsink.ingested.filter((i) => i.projectId === api).length, 1); + + // Browser errors go to -web. + assert.equal(await core.reportPlatformError(db, { name: "TypeError", message: "x is undefined", stack: "TypeError: x\n at f (https://peppa.test/_next/static/a.js:1:2)" }, { service: "browser", kind: "web", platform: "javascript" }), true); + assert.equal(bugsink.ingested.at(-1)!.projectId, web); + }); + + test("a failing watchdog part is reported (service=watchdog, where=)", async () => { + core.resetErrorReporting(); + const before = bugsink.ingested.length; + // A part of the tick blows up: hide the incidents table for one tick. + db.run(sql`ALTER TABLE incidents RENAME TO incidents_x`); + try { + await runner.tick(db, { intervalMs: 1000, stallMs: 60_000 }); + } finally { + db.run(sql`ALTER TABLE incidents_x RENAME TO incidents`); + } + // Sent in the background: the tick doesn't wait for Bugsink. + const tags = () => bugsink.ingested.slice(before).map((i) => (i.event as ReturnType).tags); + await waitFor("watchdog error in Bugsink", async () => tags().some((t) => t.service === "watchdog" && t.where === "incidents"), 5000); + }); + + test("Bugsink down → false within the timeout, no exception", async () => { + core.resetErrorReporting(); + process.env.BUGSINK_URL = "http://127.0.0.1:9"; + const t0 = Date.now(); + assert.equal(await core.reportPlatformError(db, new Error("unreachable"), { service: "bot" }), false); + assert.ok(Date.now() - t0 < 3500); + process.env.BUGSINK_URL = bugsink.url; + }); + + test("PEPPA_ERRORS=off switches it off", async () => { + core.resetErrorReporting(); + process.env.PEPPA_ERRORS = "off"; + assert.equal(await core.reportPlatformError(db, new Error("quiet"), { service: "web" }), false); + delete process.env.PEPPA_ERRORS; + }); +}); -- 2.45.2 From 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 011/404] 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 012/404] 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 013/404] 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 014/404] =?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 027/404] =?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 028/404] =?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 029/404] 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 030/404] =?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 031/404] =?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 032/404] =?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("Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.")} -