From b3766d200d80d30a95a185c2fa8917e3ad7b8f09 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 19:02:55 +0500
Subject: [PATCH 001/428] PEP-62: chats model, projection of events into
project chats, master feed, post to chat
Co-Authored-By: Claude Opus 5.5
---
openspec/changes/pep-62-chats/design.md | 84 +
openspec/changes/pep-62-chats/proposal.md | 50 +
.../pep-62-chats/specs/project-chats/spec.md | 96 +
openspec/changes/pep-62-chats/tasks.md | 21 +
packages/core/src/chats.ts | 544 +++
packages/core/src/index.ts | 1 +
packages/core/src/notifications.ts | 19 +
packages/core/src/notify.ts | 3 +-
packages/core/src/projects.ts | 4 +-
packages/core/src/tasks.ts | 4 +-
packages/db/migrations/0015_chats.sql | 48 +
.../db/migrations/meta/0015_snapshot.json | 4106 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 48 +
packages/runner/src/chats.ts | 184 +
packages/runner/src/index.ts | 1 +
16 files changed, 5216 insertions(+), 4 deletions(-)
create mode 100644 openspec/changes/pep-62-chats/design.md
create mode 100644 openspec/changes/pep-62-chats/proposal.md
create mode 100644 openspec/changes/pep-62-chats/specs/project-chats/spec.md
create mode 100644 openspec/changes/pep-62-chats/tasks.md
create mode 100644 packages/core/src/chats.ts
create mode 100644 packages/db/migrations/0015_chats.sql
create mode 100644 packages/db/migrations/meta/0015_snapshot.json
create mode 100644 packages/runner/src/chats.ts
diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/pep-62-chats/design.md
new file mode 100644
index 00000000..eb2c3412
--- /dev/null
+++ b/openspec/changes/pep-62-chats/design.md
@@ -0,0 +1,84 @@
+# Design: PEP-62 — чаты
+
+## Решения PM (2026-11-13)
+- Telegram: обычная группа на проект, треды = цепочки реплаев (без тем форума).
+- Мастер-чат: лента событий и команды, без LLM.
+- Чаты рядом с Главной; вопросы видны и в треде, и на Главной.
+- Переписку чатов храним недолго (TTL); задачи/вопросы/события — в своих таблицах.
+
+## Модель данных
+- `chats`: `kind` (`master`|`project`), `user_id` (master, уникален), `project_id` (project,
+ уникален), Telegram-группа `tg_chat_id` (уникальна: одна группа — один чат), `tg_title`,
+ `tg_linked_at`, `tg_linked_by`.
+- `chat_messages`: `chat_id`, `thread_key` (`task:` / `incident:` / `release:`;
+ null = общий канал), `thread_title` (снимок, чтобы тред читался и после удаления сущности),
+ `kind` (`event`|`question`|`user`|`system`), `important` (попадает в мастер-ленту),
+ автор (`author_kind` system/agent/user, `author_user_id`, `author_login`, `via` web/telegram),
+ `text`, `question_id`, `task_id`, `url`, `dedupe_key` (уникален — проекция идемпотентна),
+ `tg_chat_id`/`tg_message_id` (сообщение пришло из Telegram — по нему находим тред реплая).
+- `telegram_outbox.chat_message_id` — какое сообщение чата ушло в группу; по нему
+ реплай в группе находит тред, а бот при отправке находит «якорь» треда.
+- Тредов как таблицы нет: тред = `thread_key` в сообщениях; список тредов — group by.
+
+## Откуда берутся сообщения — проекция
+`syncChats(db)` (core) идемпотентно переносит в чаты:
+- `events` по курсору `chat.cursor.events` (id): `task_updated` со сменой статуса, `progress`,
+ `pm_comment`, `question_answered`, `pr_merged_in_gitea`, сбои раннера (`stalled`,
+ `stop_failure`, `exited`, `usage_limit`, `auto_restarted`, `restart_failed`,
+ `budget_paused`, `subscription_switched`, `model_escalated`), `started`/`stopped`;
+- `questions` по курсору `chat.cursor.questions` → сообщение-вопрос (состояние ответа
+ читается из `questions` при показе, кнопки — те же, что на Главной);
+- `releases` и `incidents` по `updated_at` (окно с запасом) → сообщение на каждую пару
+ (id, статус): `dedupe_key = release::`.
+Первый запуск без курсора берёт только последние сутки — не заливаем историю.
+Вызывают: бот (вместе с `reconcile`, т.е. ≤1 с после записи), вачдог (`tick`) и веб при
+рендере страницы чатов — кто первый, тот и перенёс, дубли отсекает `dedupe_key`.
+Почему проекция, а не вызовы в каждом месте: источников десятки (хуки, вачдог, CI, деплой),
+проекция не трогает их код и переживает падение любого процесса.
+
+Мастер-лента не копирует сообщения: это собственные сообщения мастер-чата (команды,
+ответы, мониторинг и дайджест из `deliverToUser`) ∪ `important` сообщения чатов доступных
+проектов (кроме выключенных в настройках уведомлений).
+
+## Ответ в треде (runner/chats.ts `postToChat`)
+- Проверка доступа: проект — `projectForUser`; мастер — только его владелец.
+- Текст с `/` — команда (`/help`, `/status`, `/task KEY-N`, `/move KEY-N <колонка>`), ответ —
+ системное сообщение в тот же тред.
+- Тред стори: конкретный вопрос (реплай в Telegram на вопрос) или последний открытый вопрос
+ стори → `answerAndDeliver`; иначе `addStoryComment` + `sendToSession`, если раннер жив.
+ Итог («Ответ ушёл агенту ✅» / «Комментарий сохранён…») — системное сообщение.
+- Тред инцидента/релиза и общий канал — заметка в чате (агенту ничего не уходит).
+Функции жизненного цикла (`answerAndDeliver`, `sendToSession`, `moveTask`) у клиентов
+PEP-21 сами уходят в раннер-сервис.
+
+## Telegram
+- **Связка**: веб «Связать с Telegram» → код (HMAC в `settings` `chat.link:`, 10 мин) →
+ ссылка `https://t.me/?startgroup=<код>` (Telegram добавит бота и пришлёт
+ `/start <код>`) или `/link <код>` в группе. Группа, связанная с другим чатом,
+ перепривязывается. `migrate_to_chat_id` (группа стала супергруппой) переносит связку.
+ «Отвязать» — в вебе.
+- **Зеркало** (бот, курсор `chat.mirror.cursor`): новое сообщение чата → `sendMessage` в
+ группу чата; `important` сообщение проекта — ещё и в мастер-группы участников проекта.
+ Сообщение, пришедшее из этой же группы, обратно не шлётся. Тред: первое сообщение треда в
+ группе — с заголовком «🧵 PEP-42 · название», остальные — реплаем на него (якорь ищется при
+ отправке, `allow_sending_without_reply`). Вопрос — с кнопками (`questionId` в outbox, так
+ что существующая правка «отвечено» и `questionByTelegramMessage` работают и в группе).
+- **Приём**: сообщение в связанной группе → пользователь по `users.telegram_user_id`
+ (личная привязка PEP-2) и не отключён → доступ к проекту / владелец мастер-чата.
+ Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); иначе — общий
+ канал. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает
+ привязать Telegram. Privacy mode бота оставляем: он видит команды и реплаи на свои
+ сообщения — этого достаточно для тредов.
+- Личные уведомления в личку не меняются (их можно выключить по проекту в «Уведомлениях»).
+
+## TTL
+`PEPPA_CHAT_TTL_DAYS` (14) — `pruneChats` в вачдоге раз в час удаляет старые сообщения
+(outbox теряет ссылку — `ON DELETE SET NULL`; реплай на такое сообщение уходит в общий канал).
+
+## Живое обновление
+Область `chats` у `/api/live`: отпечаток — max id сообщений чатов, вопросов и событий без
+шагов; страница при обновлении снова вызывает `syncChats`.
+
+## Вне scope
+- Темы форума Telegram, LLM-ассистент, слияние Главной с чатами (решения PM).
+- Push по сообщениям чатов (уведомления остаются как в PEP-35).
diff --git a/openspec/changes/pep-62-chats/proposal.md b/openspec/changes/pep-62-chats/proposal.md
new file mode 100644
index 00000000..a6853e73
--- /dev/null
+++ b/openspec/changes/pep-62-chats/proposal.md
@@ -0,0 +1,50 @@
+# Proposal: PEP-62 — чаты: мастер-чат и чат проекта с тредами, связка с Telegram-группой
+
+Стори Пеппы: **PEP-62** · эпик «Удобство для PM» · связано с PEP-2, PEP-35, PEP-37, PEP-45, PEP-60, PEP-61.
+
+## Why
+
+Уведомления и диалоги с агентами разбросаны: вопросы — на Главной и в личке бота, прогресс и
+сбои — в журнале стори, релизы и ошибки — по своим вкладкам. PM хочет одно место, как
+каналы в Slack: чат проекта с тредами по стори, инцидентам и релизам и мастер-чат со всем
+важным, — и чтобы проект можно было вести из своей Telegram-группы.
+
+## What Changes
+
+- **Раздел «Чаты»** в меню веба (рядом с Главной; Главная и вопросы на ней не меняются).
+- **Чат проекта** создаётся вместе с проектом (у старых проектов — при первом обращении).
+ Треды: стори (`task:` — вопросы агента, смена статуса, прогресс, комментарии,
+ ревью, сбои раннера), инцидент (`incident:`), релиз (`release:`); общий канал —
+ то, что не про конкретную вещь.
+- **Мастер-чат** — у каждого пользователя свой: лента важного по всем его проектам (вопросы,
+ «готово к ревью», сбои, лимиты, релизы, ошибки из прода), мониторинг и дайджест, плюс
+ команды `/status`, `/task KEY-N`, `/move KEY-N <колонка>`, `/help`. Без LLM (решение PM).
+- **Ответ в треде = ответ агенту**: есть открытый вопрос стори — ответ на него
+ (`answerAndDeliver`); нет — комментарий PM к стори (агент видит в `get_task`) и, если раннер
+ жив, текст уходит в сессию.
+- **Telegram-группа**: любой чат (проект или мастер) связывается с обычной группой по
+ одноразовому коду (кнопка «Связать» → ссылка `t.me/?startgroup=<код>` или `/link <код>`
+ в группе). Сообщения чата дублируются в группу, тред = цепочка реплаев на первое сообщение
+ треда (без тем форума — решение PM). Ответ реплаем в группе виден в вебе и уходит агенту;
+ кнопки вопросов работают и в группе. Отвечать могут только люди Пеппы с привязанным
+ Telegram (PEP-2) и доступом к проекту; в мастер-группе — только владелец мастер-чата.
+ Личная привязка и личные уведомления (PEP-2/35) не меняются.
+- **Короткое хранение**: сообщения чатов живут `PEPPA_CHAT_TTL_DAYS` (по умолчанию 14) дней и
+ удаляются вачдогом; стори, вопросы, события, релизы и инциденты остаются в своих таблицах.
+
+## Capabilities
+
+### New Capabilities
+- `project-chats`: чаты проектов и мастер-чат, треды, ответы агентам, связка с Telegram-группой, TTL.
+
+### Modified Capabilities
+
+## Impact
+
+- **Модель данных** (решено PM: отдельная сущность с коротким сроком): таблицы `chats`,
+ `chat_messages`, колонка `telegram_outbox.chat_message_id`; миграция.
+- `packages/core/src/chats.ts` — проекция событий в сообщения, ленты, коды связки, TTL.
+- `packages/runner/src/chats.ts` — сообщение в тред/канал (ответ агенту, команды).
+- `apps/bot` — зеркало сообщений в группы, приём реплаев/команд/кнопок из групп, `/link`.
+- `apps/web` — `/chats/[chat]`, пункт меню «Чаты», живое обновление (область `chats`).
+- Вачдог — проекция и чистка по TTL.
diff --git a/openspec/changes/pep-62-chats/specs/project-chats/spec.md b/openspec/changes/pep-62-chats/specs/project-chats/spec.md
new file mode 100644
index 00000000..d75ef5e8
--- /dev/null
+++ b/openspec/changes/pep-62-chats/specs/project-chats/spec.md
@@ -0,0 +1,96 @@
+## ADDED Requirements
+
+### Requirement: Чат проекта с тредами
+У каждого проекта SHALL быть чат. События проекта SHALL попадать в чат: про стори — в тред
+стори, про инцидент — в тред инцидента, про релиз — в тред релиза, остальное — в общий
+канал. Перенос событий SHALL быть идемпотентным: повторный запуск не создаёт дублей.
+
+#### Scenario: Вопрос агента в треде стори
+- **GIVEN** проект PAY со стори PAY-7 «Экспорт в CSV»
+- **WHEN** агент PAY-7 задаёт вопрос «Какой разделитель?»
+- **THEN** в чате PAY появляется тред «PAY-7 · Экспорт в CSV» с этим вопросом и кнопками ответа
+- **AND** вопрос по-прежнему виден на Главной
+
+#### Scenario: Повторный перенос
+- **GIVEN** вопрос PAY-7 уже перенесён в чат
+- **WHEN** перенос запускается ещё раз из бота и из веба
+- **THEN** в треде PAY-7 одно сообщение с этим вопросом
+
+### Requirement: Ответ в треде уходит агенту
+Сообщение участника в треде стори SHALL отвечать на открытый вопрос стори, а без открытого
+вопроса — становиться комментарием PM к стори и уходить в живой раннер. Сообщение в треде
+инцидента, релиза или в общем канале SHALL оставаться заметкой. Писать в чат проекта SHALL
+могут только владелец и участники проекта.
+
+#### Scenario: Ответ на вопрос
+- **GIVEN** у PAY-7 открыт вопрос «Какой разделитель?»
+- **WHEN** участник пишет в тред PAY-7 «точка с запятой»
+- **THEN** вопрос отвечен «точка с запятой», ответ ушёл в сессию агента
+- **AND** в треде видно сообщение участника и отметку «Ответ ушёл агенту»
+
+#### Scenario: Комментарий без вопроса
+- **GIVEN** у PAY-7 нет открытых вопросов и раннер не запущен
+- **WHEN** участник пишет в тред PAY-7 «не забудь заголовки»
+- **THEN** у стори появляется комментарий PM «не забудь заголовки», агент увидит его в get_task
+
+#### Scenario: Чужой проект
+- **GIVEN** пользователь «bob» не участник проекта PAY
+- **WHEN** он пытается написать в чат PAY
+- **THEN** запрос отклонён как «не найдено», сообщения в чате нет
+
+### Requirement: Мастер-чат
+У каждого пользователя SHALL быть мастер-чат: важные события всех его проектов (вопросы,
+готово к ревью, сбои и лимиты раннеров, релизы, ошибки из прода), мониторинг и дайджест.
+Мастер-чат SHALL выполнять команды `/help`, `/status`, `/task KEY-N`, `/move KEY-N <колонка>`
+без LLM; писать в мастер-чат SHALL может только его владелец.
+
+#### Scenario: Сбой раннера в мастер-чате
+- **GIVEN** пользователь «anna» владеет проектом PAY
+- **WHEN** раннер PAY-7 зависает
+- **THEN** в мастер-чате «anna» видно сообщение о зависании PAY-7 со ссылкой на тред
+
+#### Scenario: Команда перемещения
+- **GIVEN** стори PAY-8 в бэклоге проекта «anna»
+- **WHEN** «anna» пишет в мастер-чат `/move PAY-8 in_progress`
+- **THEN** стори PAY-8 в работе, агент запущен, в мастер-чате ответ «PAY-8 → В работе»
+
+#### Scenario: Неизвестная команда
+- **WHEN** «anna» пишет в мастер-чат `/deploy всё`
+- **THEN** в ответ — «Не знаю такую команду» и список команд, ничего не выполнено
+
+### Requirement: Связка чата с Telegram-группой
+Чат проекта и мастер-чат SHALL связываться с обычной Telegram-группой по одноразовому коду
+(10 минут). Сообщения связанного чата SHALL дублироваться в группу, тред — цепочкой реплаев
+на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и обрабатываться как
+сообщение из веба; принимать его SHALL только от пользователя Пеппы с привязанным Telegram и
+доступом к проекту (в мастер-группе — от владельца мастер-чата).
+
+#### Scenario: Связать группу
+- **GIVEN** участник открыл чат PAY и нажал «Связать с Telegram»
+- **WHEN** в группе «PAY team» отправлено `/link <код>` до истечения кода
+- **THEN** чат PAY связан с «PAY team», бот подтверждает это в группе, веб показывает название группы
+
+#### Scenario: Просроченный код
+- **GIVEN** код связки выдан 11 минут назад
+- **WHEN** в группе отправлено `/link <код>`
+- **THEN** бот отвечает, что код неверный или истёк, чат не связан
+
+#### Scenario: Ответ реплаем из группы
+- **GIVEN** чат PAY связан с группой, вопрос PAY-7 пришёл в группу
+- **AND** «anna» привязала Telegram и участник PAY
+- **WHEN** «anna» отвечает реплаем на вопрос «точка с запятой»
+- **THEN** вопрос отвечен, в веб-треде PAY-7 видно её сообщение с пометкой Telegram
+
+#### Scenario: Посторонний в группе
+- **GIVEN** в группе PAY есть человек без привязки Telegram в Пеппе
+- **WHEN** он отвечает реплаем на вопрос PAY-7
+- **THEN** вопрос не отвечен, сообщения в чате нет, бот подсказывает привязать Telegram
+
+### Requirement: Короткое хранение переписки
+Сообщения чатов SHALL удаляться через `PEPPA_CHAT_TTL_DAYS` дней (по умолчанию 14); стори,
+вопросы, события, релизы и инциденты при этом SHALL оставаться.
+
+#### Scenario: Старые сообщения удалены
+- **GIVEN** сообщение в треде PAY-7 от 15 дней назад и вопрос PAY-7, к которому оно относится
+- **WHEN** вачдог чистит чаты
+- **THEN** сообщения в чате нет, вопрос PAY-7 остаётся в стори
diff --git a/openspec/changes/pep-62-chats/tasks.md b/openspec/changes/pep-62-chats/tasks.md
new file mode 100644
index 00000000..cbf0dcdf
--- /dev/null
+++ b/openspec/changes/pep-62-chats/tasks.md
@@ -0,0 +1,21 @@
+## 1. Модель и ядро
+- [ ] 1.1 Схема `chats`, `chat_messages`, `telegram_outbox.chat_message_id`, миграция
+- [ ] 1.2 core/chats.ts: чаты (ensure), проекция `syncChats`, ленты/треды, коды связки, TTL
+- [ ] 1.3 Мастер-чат: мониторинг и дайджест из `deliverToUser`
+
+## 2. Ответы и команды
+- [ ] 2.1 runner/chats.ts `postToChat`: ответ агенту / комментарий / заметка, команды
+
+## 3. Telegram
+- [ ] 3.1 Бот: связка группы (`/start <код>`, `/link`), миграция в супергруппу
+- [ ] 3.2 Бот: зеркало сообщений в группы, треды реплаями, кнопки вопросов
+- [ ] 3.3 Бот: приём реплаев, команд и кнопок из групп с проверкой доступа
+
+## 4. Веб и вачдог
+- [ ] 4.1 `/chats/[chat]`: список чатов, треды, лента, композер, связка с Telegram; меню
+- [ ] 4.2 Живое обновление (`chats`), вызовы проекции и TTL в вачдоге, создание чата с проектом
+- [ ] 4.3 Справка `/help`, AGENTS.md
+
+## 5. Проверка
+- [ ] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
+- [ ] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
new file mode 100644
index 00000000..1422ed20
--- /dev/null
+++ b/packages/core/src/chats.ts
@@ -0,0 +1,544 @@
+// PEP-62: chats — a channel per project with threads (story / incident / release) and a master
+// chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events,
+// questions, releases and incidents, which stay in their own tables; people's messages are
+// stored here too. Telegram groups linked to chats are the bot's business (apps/bot).
+import { createHmac, randomBytes } from "node:crypto";
+import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+import { getNotifyPrefs, projectAudience } from "./notifications.ts";
+import { notify } from "./notify.ts";
+import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+import { projectForUser, userProjectIds, type User } from "./users.ts";
+import type { OutboxRow } from "./telegram.ts";
+
+export type Chat = typeof chats.$inferSelect;
+export type ChatMessage = typeof chatMessages.$inferSelect;
+export type NewChatMessage = typeof chatMessages.$inferInsert;
+
+const DAY = 24 * 3600_000;
+export const chatTtlMs = () => Math.max(1, Number(process.env.PEPPA_CHAT_TTL_DAYS ?? 14) || 14) * DAY;
+
+// ── chats ──────────────────────────────────────────────────────────────────────────
+
+export async function ensureProjectChat(db: Db, projectId: number): Promise {
+ await db.insert(chats).values({ kind: "project", projectId }).onConflictDoNothing();
+ const [c] = await db.select().from(chats).where(eq(chats.projectId, projectId));
+ return c!;
+}
+
+export async function ensureMasterChat(db: Db, userId: number): Promise {
+ await db.insert(chats).values({ kind: "master", userId }).onConflictDoNothing();
+ const [c] = await db.select().from(chats).where(eq(chats.userId, userId));
+ return c!;
+}
+
+export async function getChat(db: Db, id: number): Promise {
+ const [c] = await db.select().from(chats).where(eq(chats.id, id));
+ if (!c) throw new PeppaError("Чат не найден");
+ return c;
+}
+
+/** The chat if this user may read and write it: project chat — owner/members, master — its owner. */
+export async function chatForUser(db: Db, user: Pick, chatId: number): Promise {
+ const c = await getChat(db, chatId);
+ if (c.kind === "master") {
+ if (c.userId !== user.id) throw new PeppaError("Чат не найден");
+ } else await projectForUser(db, user.id, c.projectId!).catch(() => {
+ throw new PeppaError("Чат не найден");
+ });
+ return c;
+}
+
+export async function chatByTelegram(db: Db, tgChatId: number): Promise {
+ const [c] = await db.select().from(chats).where(eq(chats.tgChatId, tgChatId));
+ return c ?? null;
+}
+
+export interface ChatListItem {
+ id: number;
+ kind: Chat["kind"];
+ /** "master" or the project key — the URL segment of /chats/. */
+ slug: string;
+ title: string;
+ projectId: number | null;
+ tgTitle: string | null;
+ lastAt: Date | null;
+ /** Open agent questions of the project (the master chat: all of the user's). */
+ open: number;
+}
+
+/** The master chat and the chats of the user's projects (created on first look). */
+export async function listChats(db: Db, user: Pick): Promise {
+ const master = await ensureMasterChat(db, user.id);
+ const ids = await userProjectIds(db, user.id);
+ const ps = ids.length ? await db.select().from(projects).where(inArray(projects.id, ids)).orderBy(asc(projects.key)) : [];
+ const projectChats = new Map();
+ for (const p of ps) projectChats.set(p.id, await ensureProjectChat(db, p.id));
+ const chatIds = [master.id, ...[...projectChats.values()].map((c) => c.id)];
+ const last = new Map(
+ (await db.select({ chatId: chatMessages.chatId, at: sql`max(${chatMessages.createdAt})` }).from(chatMessages).where(inArray(chatMessages.chatId, chatIds)).groupBy(chatMessages.chatId)).map((r) => [r.chatId, r.at ? new Date(Number(r.at)) : null]),
+ );
+ const open = new Map(
+ ids.length
+ ? (await db.select({ p: questions.projectId, n: sql`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)])
+ : [],
+ );
+ const masterAt = [...last.values()].reduce((a, b) => (b && (!a || b > a) ? b : a), null);
+ return [
+ { id: master.id, kind: "master", slug: "master", title: "Мастер-чат", projectId: null, tgTitle: master.tgTitle, lastAt: masterAt, open: [...open.values()].reduce((a, b) => a + b, 0) },
+ ...ps.map((p) => {
+ const c = projectChats.get(p.id)!;
+ return { id: c.id, kind: "project" as const, slug: p.key, title: `${p.key} · ${p.name}`, projectId: p.id, tgTitle: c.tgTitle, lastAt: last.get(c.id) ?? null, open: open.get(p.id) ?? 0 };
+ }),
+ ];
+}
+
+// ── messages ───────────────────────────────────────────────────────────────────────
+
+/** Adds a message; with a `dedupeKey` seen before it is a no-op and returns null. */
+export async function addChatMessage(db: Db, m: NewChatMessage): Promise {
+ if (m.threadKey && m.threadTitle == null) {
+ const [prev] = await db
+ .select({ t: chatMessages.threadTitle })
+ .from(chatMessages)
+ .where(and(eq(chatMessages.chatId, m.chatId), eq(chatMessages.threadKey, m.threadKey), isNotNull(chatMessages.threadTitle)))
+ .orderBy(desc(chatMessages.id))
+ .limit(1);
+ m = { ...m, threadTitle: prev?.t ?? (await threadTitle(db, m.threadKey)) };
+ }
+ const [row] = await db.insert(chatMessages).values(m).onConflictDoNothing().returning();
+ return row ?? null;
+}
+
+/** A message in the user's master chat (monitoring, digest, command replies). */
+export async function addMasterMessage(db: Db, userId: number, m: Omit): Promise {
+ const chat = await ensureMasterChat(db, userId);
+ const row = await addChatMessage(db, { ...m, chatId: chat.id });
+ if (row) await notify(db, { type: "chat_message", messageId: row.id });
+ return row;
+}
+
+/** Current title of a thread: "PAY-7 · Экспорт", "Ошибка: …", "Релиз staging abc1234". */
+export async function threadTitle(db: Db, key: string): Promise {
+ const [kind, raw] = key.split(":");
+ const id = Number(raw);
+ if (kind === "task") {
+ const [t] = await db.select({ key: projects.key, n: tasks.number, title: tasks.title }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, id));
+ return t ? `${formatTaskKey(t.key, t.n)} · ${t.title}` : null;
+ }
+ if (kind === "incident") {
+ const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id));
+ return i ? `Ошибка: ${i.title}` : null;
+ }
+ if (kind === "release") {
+ const [r] = await db.select({ env: releases.env, sha: releases.sha }).from(releases).where(eq(releases.id, id));
+ return r ? `Релиз ${r.env} ${r.sha.slice(0, 7)}` : null;
+ }
+ return null;
+}
+
+export const THREAD_KEY = /^(task|incident|release):[1-9]\d{0,9}$/;
+
+export interface ChatMessageView {
+ id: number;
+ chatId: number;
+ /** Project of the chat the message lives in (master feed mixes projects). */
+ projectKey: string | null;
+ threadKey: string | null;
+ threadTitle: string | null;
+ kind: ChatMessage["kind"];
+ important: boolean;
+ authorKind: ChatMessage["authorKind"];
+ authorLogin: string | null;
+ via: ChatMessage["via"];
+ text: string;
+ url: string | null;
+ createdAt: Date;
+ /** A question message: its live state (answered elsewhere shows here too). */
+ question: { id: number; kind: string; options: string[] | null; answer: string | null; answeredVia: string | null; answeredAt: Date | null } | null;
+}
+
+async function views(db: Db, where: SQL, limit: number, before?: number): Promise {
+ const rows = await db
+ .select({ m: chatMessages, projectKey: projects.key, q: questions })
+ .from(chatMessages)
+ .innerJoin(chats, eq(chatMessages.chatId, chats.id))
+ .leftJoin(projects, eq(chats.projectId, projects.id))
+ .leftJoin(questions, eq(chatMessages.questionId, questions.id))
+ .where(before ? and(where, lt(chatMessages.id, before)) : where)
+ .orderBy(desc(chatMessages.id))
+ .limit(Math.min(limit, 500));
+ return rows.reverse().map(({ m, projectKey, q }) => ({
+ id: m.id,
+ chatId: m.chatId,
+ projectKey,
+ threadKey: m.threadKey,
+ threadTitle: m.threadTitle,
+ kind: m.kind,
+ important: m.important,
+ authorKind: m.authorKind,
+ authorLogin: m.authorLogin,
+ via: m.via,
+ text: m.text,
+ url: m.url,
+ createdAt: m.createdAt,
+ question: q ? { id: q.id, kind: q.kind, options: q.options ?? null, answer: q.answer, answeredVia: q.answeredVia, answeredAt: q.answeredAt } : null,
+ }));
+}
+
+/** Messages of a chat: the whole stream, or one thread (`threadKey`), or the channel only (null). */
+export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?: string | null; limit?: number; before?: number } = {}): Promise {
+ const w: SQL[] = [eq(chatMessages.chatId, chatId)];
+ if (o.threadKey === null) w.push(isNull(chatMessages.threadKey));
+ else if (o.threadKey) w.push(eq(chatMessages.threadKey, o.threadKey));
+ return views(db, and(...w)!, o.limit ?? 100, o.before);
+}
+
+/**
+ * The master feed: the user's own master messages and the important messages of the chats
+ * of their projects (muted projects left out). `threadKey` narrows it to one project thread.
+ */
+export async function masterFeed(db: Db, user: Pick, o: { limit?: number; threadKey?: string; before?: number } = {}): Promise {
+ const master = await ensureMasterChat(db, user.id);
+ const muted = new Set((await getNotifyPrefs(db, user.id)).mutedProjects);
+ const ids = (await userProjectIds(db, user.id)).filter((id) => !muted.has(id));
+ const projectChats = ids.length ? (await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids))).map((c) => c.id) : [];
+ const fromProjects = projectChats.length ? and(inArray(chatMessages.chatId, projectChats), eq(chatMessages.important, true)) : undefined;
+ let where: SQL = fromProjects ? or(eq(chatMessages.chatId, master.id), fromProjects)! : eq(chatMessages.chatId, master.id);
+ if (o.threadKey) where = and(where, eq(chatMessages.threadKey, o.threadKey))!;
+ return views(db, where, o.limit ?? 100, o.before);
+}
+
+export interface ThreadView {
+ key: string;
+ title: string;
+ count: number;
+ lastAt: Date;
+ /** Unanswered questions in the thread. */
+ open: number;
+}
+
+/** Threads of a project chat, most recently active first. */
+export async function chatThreads(db: Db, chatId: number, limit = 50): Promise {
+ const rows = await db
+ .select({
+ key: chatMessages.threadKey,
+ title: sql`max(${chatMessages.threadTitle})`,
+ count: sql`count(*)`,
+ lastId: sql`max(${chatMessages.id})`,
+ lastAt: sql`max(${chatMessages.createdAt})`,
+ open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`,
+ })
+ .from(chatMessages)
+ .leftJoin(questions, eq(chatMessages.questionId, questions.id))
+ .where(and(eq(chatMessages.chatId, chatId), isNotNull(chatMessages.threadKey)))
+ .groupBy(chatMessages.threadKey)
+ .orderBy(desc(sql`max(${chatMessages.id})`))
+ .limit(limit);
+ return rows.map((r) => ({ key: r.key!, title: r.title ?? r.key!, count: Number(r.count), lastAt: new Date(Number(r.lastAt)), open: Number(r.open) || 0 }));
+}
+
+// ── projection ─────────────────────────────────────────────────────────────────────
+
+const CURSOR_EVENTS = "chat.cursor.events";
+const CURSOR_QUESTIONS = "chat.cursor.questions";
+const CURSOR_OBJECTS = "chat.cursor.objects";
+const BATCH = 500;
+
+const STATUS_RU: Record = {
+ backlog: "бэклог",
+ proposing: "proposal",
+ awaiting_approval: "ждёт одобрения",
+ in_progress: "в работе",
+ review: "ревью",
+ done: "готово",
+ blocked: "заблокирована",
+};
+export const statusRu = (s: string) => STATUS_RU[s] ?? s;
+
+type P = Record;
+const s = (v: unknown) => (v == null ? "" : String(v));
+const cut = (t: string, n = 600) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);
+
+/** Event types that become chat messages: text, and whether the master chat shows it. */
+const EVENT_TEXT: Record { text: string; important?: boolean; author?: "agent" } | null> = {
+ task_updated: (p) => {
+ const from = (p.from as P | undefined)?.status;
+ const to = (p.to as P | undefined)?.status;
+ if (!to || from === to) return null;
+ const icon = to === "review" ? "👀" : to === "done" ? "✅" : to === "in_progress" ? "▶️" : to === "blocked" ? "⛔" : "•";
+ const tail = to === "review" ? " — готово к ревью" : "";
+ return { text: `${icon} Статус: ${from ? `${statusRu(String(from))} → ` : ""}${statusRu(String(to))}${tail}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
+ },
+ progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
+ pm_comment: () => null, // handled separately: a person's message
+ pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
+ started: () => ({ text: "▶️ Агент запущен" }),
+ resumed: () => ({ text: "🔁 Агент продолжает работу" }),
+ stopped: () => ({ text: "⏹ Агент остановлен" }),
+ stalled: (p) => ({ text: `⚠️ Агент молчит${p.idleMinutes ? ` ${s(p.idleMinutes)} мин` : ""}`, important: true }),
+ stop_failure: (p) => ({ text: `❌ Ход агента прерван: ${s(p.error) || "ошибка"}`, important: true }),
+ exited: (p) => ({ text: `💀 Процесс агента завершился${p.exitStatus != null ? ` (код ${s(p.exitStatus)})` : ""}`, important: true }),
+ usage_limit: (p) => ({ text: `⏳ Лимит подписки${p.line ? `: ${cut(s(p.line), 200)}` : ""}`, important: true }),
+ auto_restarted: (p) => ({ text: `🔁 Перезапуск после сбоя${p.attempt ? ` (${s(p.attempt)} из ${s(p.of)})` : ""}`, important: true }),
+ restart_failed: (p) => ({ text: `❌ Перезапуск не удался${p.error ? `: ${cut(s(p.error), 200)}` : ""}`, important: true }),
+ budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе", important: true }),
+ subscription_switched: (p) => ({ text: `🔀 Подписка переключена${p.to ? ` на ${s(p.to)}` : ""}`, important: true }),
+ model_escalated: (p) => ({ text: `⬆️ Модель усилена${p.model ? `: ${s(p.model)}` : ""}` }),
+};
+
+const RELEASE_ICON: Record = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
+const RELEASE_RU: Record = { deploying: "выкатывается", healthy: "здоров", rolled_back: "откатан", failed: "не выкатился", removed: "убран" };
+const INCIDENT_RU: Record = { new: "новая", open: "открыта", pending: "ждёт решения", task: "заведена стори", ignored: "игнорируем", resolved: "исправлена", regressed: "вернулась" };
+
+/** First id of rows newer than a day (a fresh install doesn't import the whole history). */
+async function initialCursor(db: Db, table: typeof events | typeof questions, now: Date): Promise {
+ const since = new Date(now.getTime() - DAY);
+ const [r] = await db.select({ min: sql`min(${table.id})`, max: sql`max(${table.id})` }).from(table).where(gt(table.createdAt, since));
+ if (r?.min != null) return Number(r.min) - 1;
+ const [all] = await db.select({ max: sql`max(${table.id})` }).from(table);
+ return Number(all?.max ?? 0);
+}
+
+/**
+ * Moves new events, questions, releases and incidents into the project chats. Idempotent
+ * (every message has a dedupe key), so the bot, the watchdog and the web may all call it.
+ * Returns the number of new messages.
+ */
+export async function syncChats(db: Db, o: { now?: Date } = {}): Promise {
+ const now = o.now ?? new Date();
+ const chatOf = new Map();
+ const chatId = async (projectId: number) => {
+ if (!chatOf.has(projectId)) chatOf.set(projectId, (await ensureProjectChat(db, projectId)).id);
+ return chatOf.get(projectId)!;
+ };
+ const titles = new Map();
+ const titleOf = async (key: string) => {
+ if (!titles.has(key)) titles.set(key, await threadTitle(db, key));
+ return titles.get(key) ?? null;
+ };
+ let added = 0;
+ const add = async (m: NewChatMessage) => {
+ if (m.threadKey) m.threadTitle = await titleOf(m.threadKey);
+ if (await addChatMessage(db, m)) added++;
+ };
+
+ // events
+ let cursor = (await getSetting(db, CURSOR_EVENTS)) ?? (await initialCursor(db, events, now));
+ for (;;) {
+ // Read the newest id first: a row committed after it is picked up by the next call.
+ const [top] = await db.select({ max: sql`max(${events.id})` }).from(events);
+ const upTo = Number(top?.max ?? cursor);
+ const rows = await db
+ .select({ e: events, login: users.login })
+ .from(events)
+ .leftJoin(users, eq(events.actorUserId, users.id))
+ .where(and(gt(events.id, cursor), lte(events.id, upTo), inArray(events.type, Object.keys(EVENT_TEXT))))
+ .orderBy(asc(events.id))
+ .limit(BATCH);
+ for (const { e, login } of rows) {
+ const p = (e.payload ?? {}) as P;
+ const base = { chatId: await chatId(e.projectId), threadKey: e.taskId ? `task:${e.taskId}` : null, taskId: e.taskId, dedupeKey: `event:${e.id}`, createdAt: e.createdAt };
+ if (e.type === "pm_comment") {
+ if (p.chatMessageId) continue; // written in a chat: already there
+ await add({ ...base, kind: "user", authorKind: "user", authorUserId: (p.userId as number) ?? e.actorUserId, authorLogin: s(p.login) || login, via: e.actorChannel === "telegram" ? "telegram" : "web", text: s(p.text) });
+ continue;
+ }
+ const t = EVENT_TEXT[e.type]?.(p);
+ if (!t) continue;
+ const authorKind = t.author ?? (e.actorKind === "user" ? "user" : e.actorKind === "agent" ? "agent" : "system");
+ await add({ ...base, kind: "event", important: !!t.important, authorKind, authorUserId: e.actorUserId, authorLogin: authorKind === "user" ? login : null, text: t.text });
+ }
+ // The cursor moves past filtered-out events too.
+ cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo);
+ if (rows.length < BATCH) break;
+ }
+ await setSetting(db, CURSOR_EVENTS, cursor);
+
+ // questions
+ let qCursor = (await getSetting(db, CURSOR_QUESTIONS)) ?? (await initialCursor(db, questions, now));
+ for (;;) {
+ const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH);
+ for (const q of rows) {
+ const head = q.kind === "approval" ? "🟡 Нужно одобрение" : q.kind === "permission" ? "🔐 Нужно разрешение" : q.kind === "question" ? "❓ Вопрос агента" : "🔔";
+ await add({
+ chatId: await chatId(q.projectId),
+ threadKey: q.taskId ? `task:${q.taskId}` : null,
+ taskId: q.taskId,
+ kind: "question",
+ important: true,
+ authorKind: q.sessionId ? "agent" : "system",
+ text: `${head}\n${cut(q.text, 3000)}`,
+ questionId: q.id,
+ dedupeKey: `question:${q.id}`,
+ createdAt: q.createdAt,
+ });
+ qCursor = q.id;
+ }
+ if (rows.length < BATCH) break;
+ }
+ await setSetting(db, CURSOR_QUESTIONS, qCursor);
+
+ // releases and incidents: one message per (id, status); the window overlaps a little.
+ const since = new Date(((await getSetting(db, CURSOR_OBJECTS)) ?? now.getTime() - DAY) - 60_000);
+ for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
+ const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
+ await add({
+ chatId: await chatId(r.projectId),
+ threadKey: `release:${r.id}`,
+ kind: "event",
+ important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back",
+ text: `${RELEASE_ICON[r.status] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
+ url: r.host ? `https://${r.host}` : r.runUrl,
+ dedupeKey: `release:${r.id}:${r.status}`,
+ });
+ }
+ for (const i of await db.select().from(incidents).where(gt(incidents.updatedAt, since)).orderBy(asc(incidents.id))) {
+ await add({
+ chatId: await chatId(i.projectId),
+ threadKey: `incident:${i.id}`,
+ taskId: i.taskId,
+ kind: "event",
+ important: i.status === "new" || i.status === "regressed" || i.status === "pending",
+ text: `🐞 ${INCIDENT_RU[i.status] ?? i.status}: ${cut(i.title, 300)}${i.culprit ? `\n${cut(i.culprit, 200)}` : ""}${i.environment ? ` · ${i.environment}` : ""}${i.events > 1 ? ` · ${i.events} раз` : ""}`,
+ url: i.url,
+ dedupeKey: `incident:${i.id}:${i.status}`,
+ });
+ }
+ await setSetting(db, CURSOR_OBJECTS, now.getTime());
+ if (added) await notify(db, { type: "chat_message", messageId: 0 });
+ return added;
+}
+
+/** Deletes chat messages older than the TTL (the stories, questions and events stay). */
+export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise {
+ const before = new Date((o.now ?? new Date()).getTime() - chatTtlMs());
+ const old = db.select({ id: chatMessages.id }).from(chatMessages).where(lt(chatMessages.createdAt, before));
+ await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old));
+ const rows = await db.delete(chatMessages).where(lt(chatMessages.createdAt, before)).returning({ id: chatMessages.id });
+ return rows.length;
+}
+
+// ── Telegram groups ────────────────────────────────────────────────────────────────
+
+const LINK_TTL_MS = 10 * 60_000;
+const linkKey = (code: string, secret: string) => `chat.link:${createHmac("sha256", secret).update(`chat:${code}`).digest("hex")}`;
+
+/** One-time code (10 minutes) that links a Telegram group to this chat. */
+export async function createChatLinkCode(db: Db, secret: string, user: Pick, chatId: number): Promise {
+ await chatForUser(db, user, chatId);
+ const code = `c${randomBytes(12).toString("base64url")}`;
+ await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, expiresAt: Date.now() + LINK_TTL_MS });
+ return code;
+}
+
+/** Codes of chat links start with "c"; the personal pairing codes of PEP-2 never collide with them. */
+export const isChatLinkCode = (code: string) => /^c[\w-]{16}$/.test(code);
+
+/** Links the group the code was sent from. A group linked to another chat moves to this one. */
+export async function acceptChatLink(db: Db, secret: string, code: string, group: { tgChatId: number; title: string | null }, now = Date.now()): Promise {
+ const key = linkKey(code, secret);
+ const saved = await getSetting<{ chatId: number; userId: number; expiresAt: number }>(db, key);
+ if (!saved) return null;
+ await deleteSetting(db, key);
+ if (now >= saved.expiresAt) return null;
+ return db.transaction((tx) => {
+ tx.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null }).where(eq(chats.tgChatId, group.tgChatId)).run();
+ return tx.update(chats).set({ tgChatId: group.tgChatId, tgTitle: group.title, tgLinkedAt: new Date(now), tgLinkedBy: saved.userId }).where(eq(chats.id, saved.chatId)).returning().get() ?? null;
+ });
+}
+
+export async function unlinkChat(db: Db, user: Pick, chatId: number): Promise {
+ await chatForUser(db, user, chatId);
+ await db.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null }).where(eq(chats.id, chatId));
+}
+
+/** A group became a supergroup: Telegram gives it a new id. */
+export async function migrateChatGroup(db: Db, from: number, to: number): Promise {
+ await db.update(chats).set({ tgChatId: to }).where(eq(chats.tgChatId, from));
+}
+
+/** The person writing in a linked group: a Peppa user with this personal Telegram account (PEP-2). */
+export async function telegramAccountUser(db: Db, fromId: number): Promise {
+ const rows = await db.select().from(users).where(eq(users.telegramUserId, fromId));
+ return rows.find((u) => !u.disabledAt) ?? null;
+}
+
+/** May this user write into the chat from Telegram (project access / the master chat's owner)? */
+export async function mayWriteChat(db: Db, user: Pick, chat: Chat): Promise {
+ return chatForUser(db, user, chat.id).then(
+ () => true,
+ () => false,
+ );
+}
+
+export interface MirrorTarget {
+ tgChatId: number;
+ /** The group of a master chat (a project's message reached it as an important one). */
+ master: boolean;
+}
+
+/** Messages after `afterId` with the chat they belong to (the bot mirrors them). */
+export async function chatMessagesAfter(db: Db, afterId: number, limit = 100) {
+ return db.select({ m: chatMessages, chat: chats }).from(chatMessages).innerJoin(chats, eq(chatMessages.chatId, chats.id)).where(gt(chatMessages.id, afterId)).orderBy(asc(chatMessages.id)).limit(limit);
+}
+
+export async function lastChatMessageId(db: Db): Promise {
+ const [r] = await db.select({ max: sql`max(${chatMessages.id})` }).from(chatMessages);
+ return Number(r?.max ?? 0);
+}
+
+/** Linked groups a message goes to: its chat's group, and for an important project message the master groups of the project's people. */
+export async function mirrorTargets(db: Db, m: ChatMessage, chat: Chat): Promise {
+ const out: MirrorTarget[] = [];
+ if (chat.tgChatId && chat.tgChatId !== m.tgChatId) out.push({ tgChatId: chat.tgChatId, master: chat.kind === "master" });
+ if (chat.kind === "project" && m.important) {
+ for (const u of await projectAudience(db, chat.projectId!)) {
+ const [mc] = await db.select().from(chats).where(and(eq(chats.userId, u.id), isNotNull(chats.tgChatId)));
+ if (!mc?.tgChatId || mc.tgChatId === m.tgChatId || out.some((t) => t.tgChatId === mc.tgChatId)) continue;
+ if ((await getNotifyPrefs(db, u.id)).mutedProjects.includes(chat.projectId!)) continue;
+ out.push({ tgChatId: mc.tgChatId, master: true });
+ }
+ }
+ return out;
+}
+
+/** The chat message a Telegram message in this group stands for (sent by the bot, or written there). */
+export async function chatMessageByTelegram(db: Db, tgChatId: number, tgMessageId: number): Promise {
+ const [sent] = await db
+ .select({ m: chatMessages })
+ .from(telegramOutbox)
+ .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id))
+ .where(and(eq(telegramOutbox.telegramMessageId, tgMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(tgChatId)}`));
+ if (sent) return sent.m;
+ const [own] = await db.select().from(chatMessages).where(and(eq(chatMessages.tgChatId, tgChatId), eq(chatMessages.tgMessageId, tgMessageId)));
+ return own ?? null;
+}
+
+/**
+ * The Telegram message a thread hangs on in this group: the first message of the thread
+ * that reached the group (sent by the bot or written there). Null — this is the thread's first.
+ */
+export async function threadAnchor(db: Db, row: Pick): Promise {
+ if (!row.chatMessageId) return null;
+ const [m] = await db.select({ threadKey: chatMessages.threadKey }).from(chatMessages).where(eq(chatMessages.id, row.chatMessageId));
+ if (!m?.threadKey) return null;
+ const group = String(row.params.chat_id);
+ const [sent] = await db
+ .select({ id: telegramOutbox.telegramMessageId })
+ .from(telegramOutbox)
+ .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id))
+ .where(and(eq(chatMessages.threadKey, m.threadKey), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${group}`))
+ .orderBy(asc(telegramOutbox.id))
+ .limit(1);
+ if (sent?.id) return sent.id;
+ const [own] = await db
+ .select({ id: chatMessages.tgMessageId })
+ .from(chatMessages)
+ .where(and(eq(chatMessages.threadKey, m.threadKey), eq(chatMessages.tgChatId, Number(group)), isNotNull(chatMessages.tgMessageId)))
+ .orderBy(asc(chatMessages.id))
+ .limit(1);
+ return own?.id ?? null;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f06b1ada..a7e18ba0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -44,3 +44,4 @@ export * from "./secrets-audit.ts";
export * from "./memory.ts";
export * from "./agent-model.ts";
export * from "./onboarding.ts";
+export * from "./chats.ts";
diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts
index 9774da6a..3c3540b3 100644
--- a/packages/core/src/notifications.ts
+++ b/packages/core/src/notifications.ts
@@ -7,6 +7,20 @@ import { enqueueTelegram, type OutboxRow } from "./telegram.ts";
import type { Question } from "./tasks.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
+import { addMasterMessage } from "./chats.ts";
+
+/** Telegram HTML → plain text for the web chat. */
+export function htmlToText(html: string): string {
+ return html
+ .replace(/ /gi, "\n")
+ .replace(/]*>([^<]*)<\/a>/gi, (_m, href: string, t: string) => (t && t !== href ? `${t} (${href})` : href))
+ .replace(/<[^>]+>/g, "")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/&/g, "&");
+}
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
@@ -154,6 +168,11 @@ export interface Delivered {
/** Routes one notification to one user by their preferences. */
export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: NotifyPrefs): Promise {
+ // PEP-62: monitoring and the digest also land in the user's master chat (a feed, not a channel).
+ if (d.projectId == null && (d.event === "monitoring" || d.event === "digest") && typeof d.telegram?.params.text === "string") {
+ const text = htmlToText(d.telegram.params.text);
+ await addMasterMessage(db, user.id, { kind: "event", important: true, text, dedupeKey: `master:u${user.id}:${d.dedupeKey}`, url: d.push?.url ?? null }).catch(() => null);
+ }
const p = prefs ?? (await getNotifyPrefs(db, user.id));
const out: Delivered = { telegram: false, push: 0, muted: false };
if (d.projectId != null && p.mutedProjects.includes(d.projectId)) return { ...out, muted: true };
diff --git a/packages/core/src/notify.ts b/packages/core/src/notify.ts
index 9b9d91c8..ca816d39 100644
--- a/packages/core/src/notify.ts
+++ b/packages/core/src/notify.ts
@@ -10,7 +10,8 @@ export type PeppaNotification =
| { type: "task_updated"; taskId: number }
| { type: "progress"; eventId: number }
| { type: "session_updated"; sessionId: number }
- | { type: "incident"; incidentId: number };
+ | { type: "incident"; incidentId: number }
+ | { type: "chat_message"; messageId: number };
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME (web: PEP-37). */
export const SUBSCRIBERS = ["bot", "web"] as const;
diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts
index eeb4918a..8bd03813 100644
--- a/packages/core/src/projects.ts
+++ b/packages/core/src/projects.ts
@@ -1,4 +1,4 @@
-import { goals, projects, type Db } from "@peppa/db";
+import { chats, goals, projects, type Db } from "@peppa/db";
import { and, asc, eq, or } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
@@ -24,6 +24,8 @@ export async function createProject(db: Db, p: NewProject): Promise {
.insert(projects)
.values({ ...p, key, giteaRepo: p.giteaRepo ?? p.slug })
.returning();
+ // PEP-62: every project gets its chat (a channel with threads) right away.
+ await db.insert(chats).values({ kind: "project", projectId: row!.id }).onConflictDoNothing();
return row!;
}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 8e048805..1958bb6d 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -256,13 +256,13 @@ export interface StoryComment {
}
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
-export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string): Promise {
+export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string, extra: { chatMessageId?: number } = {}): Promise {
const body = text.trim();
if (!body) throw new PeppaError("Пустой комментарий");
if (body.length > 8000) throw new PeppaError("Комментарий длиннее 8000 символов");
const [row] = await db
.insert(events)
- .values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body }, ...actorColumns() })
+ .values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body, ...extra }, ...actorColumns() })
.returning();
await notify(db, { type: "task_updated", taskId: ref.task.id });
return { id: row!.id, login: author.login, text: body, createdAt: row!.createdAt };
diff --git a/packages/db/migrations/0015_chats.sql b/packages/db/migrations/0015_chats.sql
new file mode 100644
index 00000000..c57421c4
--- /dev/null
+++ b/packages/db/migrations/0015_chats.sql
@@ -0,0 +1,48 @@
+CREATE TABLE `chat_messages` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `chat_id` integer NOT NULL,
+ `thread_key` text,
+ `thread_title` text,
+ `kind` text NOT NULL,
+ `important` integer DEFAULT false NOT NULL,
+ `author_kind` text DEFAULT 'system' NOT NULL,
+ `author_user_id` integer,
+ `author_login` text,
+ `via` text,
+ `text` text NOT NULL,
+ `question_id` integer,
+ `task_id` integer,
+ `url` text,
+ `dedupe_key` text,
+ `tg_chat_id` integer,
+ `tg_message_id` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`author_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `chat_messages_dedupe_key_unique` ON `chat_messages` (`dedupe_key`);--> statement-breakpoint
+CREATE INDEX `chat_messages_chat` ON `chat_messages` (`chat_id`,`id`);--> statement-breakpoint
+CREATE INDEX `chat_messages_created_at` ON `chat_messages` (`created_at`);--> statement-breakpoint
+CREATE INDEX `chat_messages_tg` ON `chat_messages` (`tg_chat_id`,`tg_message_id`);--> statement-breakpoint
+CREATE TABLE `chats` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `kind` text NOT NULL,
+ `user_id` integer,
+ `project_id` integer,
+ `tg_chat_id` integer,
+ `tg_title` text,
+ `tg_linked_at` integer,
+ `tg_linked_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`tg_linked_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_user_id_unique` ON `chats` (`user_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_project_id_unique` ON `chats` (`project_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_tg_chat_id_unique` ON `chats` (`tg_chat_id`);--> statement-breakpoint
+ALTER TABLE `telegram_outbox` ADD `chat_message_id` integer REFERENCES chat_messages(id) ON DELETE set null;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0015_snapshot.json b/packages/db/migrations/meta/0015_snapshot.json
new file mode 100644
index 00000000..0b659949
--- /dev/null
+++ b/packages/db/migrations/meta/0015_snapshot.json
@@ -0,0 +1,4106 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "a95c0441-3ac0-47f1-a36d-b0caea076cbd",
+ "prevId": "c884cc4d-c58b-4874-ab39-9a1b9ce9718e",
+ "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
+ },
+ "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
+ },
+ "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
+ }
+ },
+ "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 09e80588..cc8db5f4 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -106,6 +106,13 @@
"when": 1794663938633,
"tag": "0014_agent_team",
"breakpoints": true
+ },
+ {
+ "idx": 15,
+ "version": "6",
+ "when": 1794665444878,
+ "tag": "0015_chats",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index bad12eee..cdbc71d2 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -481,6 +481,8 @@ export const telegramOutbox = sqliteTable("telegram_outbox", {
method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(),
params: text("params", { mode: "json" }).$type>().notNull(),
questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
+ // PEP-62: the chat message mirrored into a linked Telegram group (finds the thread of a reply).
+ chatMessageId: integer("chat_message_id").references((): AnySQLiteColumn => chatMessages.id, { onDelete: "set null" }),
status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"),
attempts: integer("attempts").notNull().default(0),
nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs),
@@ -490,6 +492,52 @@ export const telegramOutbox = sqliteTable("telegram_outbox", {
sentAt: integer("sent_at", { mode: "timestamp_ms" }),
});
+/** PEP-62: a chat — one per project (a channel with threads) and one per user (the master chat). */
+export const chats = sqliteTable("chats", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ kind: text("kind", { enum: ["master", "project"] }).notNull(),
+ userId: integer("user_id").unique().references(() => users.id, { onDelete: "cascade" }),
+ projectId: integer("project_id").unique().references(() => projects.id, { onDelete: "cascade" }),
+ // Linked Telegram group: messages are mirrored there, replies come back (one group — one chat).
+ tgChatId: integer("tg_chat_id").unique(),
+ tgTitle: text("tg_title"),
+ tgLinkedAt: integer("tg_linked_at", { mode: "timestamp_ms" }),
+ tgLinkedBy: integer("tg_linked_by").references(() => users.id, { onDelete: "set null" }),
+ createdAt: createdAt(),
+});
+
+/**
+ * PEP-62: a chat message, kept for PEPPA_CHAT_TTL_DAYS only. A thread is `thread_key`
+ * (task: / incident: / release:; null = the channel); events, questions,
+ * releases and incidents are projected here and stay in their own tables.
+ */
+export const chatMessages = sqliteTable(
+ "chat_messages",
+ {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ chatId: integer("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }),
+ threadKey: text("thread_key"),
+ threadTitle: text("thread_title"),
+ kind: text("kind", { enum: ["event", "question", "user", "system"] }).notNull(),
+ // Shown in the master chats of the project's people.
+ important: integer("important", { mode: "boolean" }).notNull().default(false),
+ authorKind: text("author_kind", { enum: ["system", "agent", "user"] }).notNull().default("system"),
+ authorUserId: integer("author_user_id").references(() => users.id, { onDelete: "set null" }),
+ authorLogin: text("author_login"),
+ via: text("via", { enum: ["web", "telegram"] }),
+ text: text("text").notNull(),
+ questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
+ url: text("url"),
+ dedupeKey: text("dedupe_key").unique(),
+ // Came from a Telegram group: a reply to this message finds its thread.
+ tgChatId: integer("tg_chat_id"),
+ tgMessageId: integer("tg_message_id"),
+ createdAt: createdAt(),
+ },
+ (t) => [index("chat_messages_chat").on(t.chatId, t.id), index("chat_messages_created_at").on(t.createdAt), index("chat_messages_tg").on(t.tgChatId, t.tgMessageId)],
+);
+
/** Telegram updates already taken: recorded before acting, so a restart never replays one. */
export const telegramUpdates = sqliteTable("telegram_updates", {
updateId: integer("update_id").primaryKey(),
diff --git a/packages/runner/src/chats.ts b/packages/runner/src/chats.ts
new file mode 100644
index 00000000..5dde50e5
--- /dev/null
+++ b/packages/runner/src/chats.ts
@@ -0,0 +1,184 @@
+// PEP-62: a person's message in a chat (web or a linked Telegram group). In a story thread it
+// answers the story's open question or becomes a PM comment typed into the live runner; in
+// other threads and the channel it is a note; a text starting with "/" is a command.
+import {
+ addChatMessage,
+ addStoryComment,
+ chatForUser,
+ listSessions,
+ notify,
+ pendingQuestions,
+ projectForUser,
+ resolveTask,
+ statusRu,
+ THREAD_KEY,
+ userProjectIds,
+ type Chat,
+ type ChatMessage,
+ type User,
+ PeppaError,
+} from "@peppa/core";
+import { projects, questions, tasks, type Db } from "@peppa/db";
+import { and, desc, eq, isNull, ne } from "drizzle-orm";
+import { moveTask, type BoardColumn } from "./flow.ts";
+import { answerAndDeliver, sendToSession } from "./sessions.ts";
+
+export interface ChatPost {
+ chatId: number;
+ /** null = the channel. */
+ threadKey: string | null;
+ text: string;
+ via: "web" | "telegram";
+ /** A reply to this question's message (Telegram): answer exactly it. */
+ questionId?: number | null;
+ /** Where it was written in Telegram (a reply to it finds the thread). */
+ tg?: { chatId: number; messageId: number };
+}
+
+export interface ChatPostResult {
+ message: ChatMessage;
+ /** Peppa's reply in the same thread (what happened), if any. */
+ reply: ChatMessage | null;
+}
+
+const MAX_TEXT = 8000;
+
+export const CHAT_HELP = [
+ "Команды:",
+ "/status — активные агенты и открытые вопросы",
+ "/task KEY-N — где стори и что она ждёт",
+ "/move KEY-N — передвинуть стори (in_progress запускает агента)",
+ "/help — эта справка",
+ "",
+ "В треде стори обычный текст — ответ агенту: на открытый вопрос, иначе комментарий, который агент увидит сразу.",
+].join("\n");
+
+const COLUMNS: Record = {
+ backlog: "backlog",
+ бэклог: "backlog",
+ in_progress: "in_progress",
+ work: "in_progress",
+ работа: "in_progress",
+ "в работу": "in_progress",
+ review: "review",
+ ревью: "review",
+ done: "done",
+ готово: "done",
+};
+const COLUMN_RU: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
+
+/** Posts a person's message and does what it means. Access: chatForUser (project people / master owner). */
+export async function postToChat(db: Db, user: User, p: ChatPost): Promise {
+ const chat = await chatForUser(db, user, p.chatId);
+ const text = p.text.trim();
+ if (!text) throw new PeppaError("Пустое сообщение");
+ if (text.length > MAX_TEXT) throw new PeppaError(`Сообщение длиннее ${MAX_TEXT} символов`);
+ if (p.threadKey && !THREAD_KEY.test(p.threadKey)) throw new PeppaError("Неизвестный тред");
+ if (chat.kind === "master" && p.threadKey) throw new PeppaError("В мастер-чате нет своих тредов — ответь в чате проекта");
+ const taskId = p.threadKey?.startsWith("task:") ? Number(p.threadKey.slice(5)) : null;
+ if (taskId) await assertTaskInChat(db, chat, taskId);
+
+ const message = (await addChatMessage(db, {
+ chatId: chat.id,
+ threadKey: p.threadKey,
+ taskId,
+ kind: "user",
+ authorKind: "user",
+ authorUserId: user.id,
+ authorLogin: user.login,
+ via: p.via,
+ text,
+ tgChatId: p.tg?.chatId ?? null,
+ tgMessageId: p.tg?.messageId ?? null,
+ }))!;
+ const say = async (t: string) => {
+ const r = await addChatMessage(db, { chatId: chat.id, threadKey: p.threadKey, taskId, kind: "system", text: t });
+ return r;
+ };
+
+ let replyText: string | null;
+ try {
+ if (text.startsWith("/")) replyText = await runCommand(db, user, chat, text);
+ else if (taskId) replyText = await toAgent(db, user, message, taskId, text, p);
+ else replyText = chat.kind === "master" ? `Здесь работают команды.\n${CHAT_HELP}` : null;
+ } catch (e) {
+ replyText = `⚠️ ${(e as Error).message}`;
+ }
+ const reply = replyText ? await say(replyText) : null;
+ await notify(db, { type: "chat_message", messageId: message.id });
+ return { message, reply };
+}
+
+async function assertTaskInChat(db: Db, chat: Chat, taskId: number) {
+ const ref = await resolveTaskById(db, taskId);
+ if (chat.kind !== "project" || ref.project.id !== chat.projectId) throw new PeppaError("Тред не из этого чата");
+ return ref;
+}
+
+async function resolveTaskById(db: Db, taskId: number) {
+ const [row] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, taskId));
+ if (!row) throw new PeppaError("Стори не найдена");
+ return resolveTask(db, `${row.key}-${row.number}`);
+}
+
+/** Story thread: answer its open question, or comment and type into the live runner. */
+async function toAgent(db: Db, user: User, message: ChatMessage, taskId: number, text: string, p: ChatPost): Promise {
+ let q = p.questionId ? (await db.select().from(questions).where(and(eq(questions.id, p.questionId), eq(questions.taskId, taskId))))[0] : undefined;
+ if (q?.answeredAt) return `Этот вопрос уже закрыт${q.answeredVia && q.answeredVia !== "system" ? ` (${q.answeredVia})` : ""}: ${q.answer ?? ""}`;
+ // The latest open real question first; «ждёт тебя» (attention) only when nothing else is open.
+ q ??=
+ (await db.select().from(questions).where(and(eq(questions.taskId, taskId), isNull(questions.answeredAt), ne(questions.kind, "attention"))).orderBy(desc(questions.id)).limit(1))[0] ??
+ (await db.select().from(questions).where(and(eq(questions.taskId, taskId), isNull(questions.answeredAt))).orderBy(desc(questions.id)).limit(1))[0];
+ if (q) {
+ const { delivered } = await answerAndDeliver(db, q.id, text, p.via);
+ return delivered ? "Ответ ушёл агенту ✅" : "Ответ сохранён; сессия не запущена — агент увидит его в истории стори.";
+ }
+ const ref = await resolveTaskById(db, taskId);
+ // The comment event carries this message's id: the projection doesn't repeat it in the thread.
+ const c = await addStoryComment(db, ref, user, text, { chatMessageId: message.id });
+ const [live] = await listSessions(db, { active: true, taskId });
+ if (!live) return "Комментарий сохранён — агент увидит его в get_task, когда возьмётся за стори.";
+ await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
+ return "Комментарий ушёл агенту ✅";
+}
+
+/** /status, /task, /move, /help — no LLM (PM's decision). */
+export async function runCommand(db: Db, user: User, chat: Chat, text: string): Promise {
+ const [cmd0, ...args] = text.trim().split(/\s+/);
+ const cmd = cmd0!.toLowerCase().replace(/@\w+$/, "");
+ if (cmd === "/help" || cmd === "/start") return CHAT_HELP;
+ if (cmd === "/status") return status(db, user, chat);
+ if (cmd === "/task" || cmd === "/move") {
+ if (!args[0]) throw new PeppaError(`Укажи стори: ${cmd} KEY-N${cmd === "/move" ? " in_progress" : ""}`);
+ const defaultKey = chat.kind === "project" ? await projectKey(db, chat.projectId!) : undefined;
+ const ref = await resolveTask(db, args[0], defaultKey);
+ await projectForUser(db, user.id, ref.project.id).catch(() => {
+ throw new PeppaError(`Стори ${args[0]} не найдена`);
+ });
+ if (cmd === "/task") {
+ const open = (await pendingQuestions(db)).filter((q) => q.taskId === ref.task.id);
+ const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
+ return [`${ref.key}: ${ref.task.title}`, `Статус: ${statusRu(ref.task.status)}`, live ? `Агент: ${live.status}` : "Агент не запущен", open.length ? `Ждёт ответа: ${open.length}` : "Открытых вопросов нет"].join("\n");
+ }
+ const col = COLUMNS[args.slice(1).join(" ").toLowerCase()];
+ if (!col) throw new PeppaError("Колонка: backlog, in_progress, review или done");
+ await moveTask(db, ref, col);
+ return `${ref.key} → ${COLUMN_RU[col]}${col === "in_progress" ? " (агент взялся)" : ""}`;
+ }
+ throw new PeppaError(`Не знаю такую команду: ${cmd}\n${CHAT_HELP}`);
+}
+
+async function projectKey(db: Db, projectId: number) {
+ const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
+ return p?.key;
+}
+
+async function status(db: Db, user: User, chat: Chat): Promise {
+ const ids = new Set(chat.kind === "project" ? [chat.projectId!] : 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}`];
+ for (const s of sessions.slice(0, 20)) lines.push(`• ${s.taskKey ?? s.name ?? `#${s.id}`} — ${s.status}`);
+ lines.push(`Открытых вопросов: ${open.length}`);
+ return lines.join("\n");
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d8956b45..27da7158 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -39,3 +39,4 @@ export * from "./exec.ts";
export * from "./sandbox.ts";
export * from "./hosts.ts";
export * from "./agent-relay.ts";
+export * from "./chats.ts";
--
2.45.2
From 46840ffef57cdbda1f8520675360a17d8d3e242f 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 19:04:18 +0500
Subject: [PATCH 002/428] =?UTF-8?q?PEP-62:=20bot=20=E2=80=94=20link=20grou?=
=?UTF-8?q?ps=20by=20code,=20mirror=20chat=20messages=20with=20reply=20thr?=
=?UTF-8?q?eads,=20replies=20and=20buttons=20from=20groups?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/bot/src/bot.ts | 125 +++++++++++++++++++++++-
apps/bot/src/telegram.ts | 4 +-
openspec/changes/pep-62-chats/design.md | 5 +-
packages/core/src/telegram.ts | 2 +-
4 files changed, 129 insertions(+), 7 deletions(-)
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 435ab96a..50b3a401 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -47,10 +47,25 @@ import {
type OutboxRow,
type Question,
type SessionView,
+ acceptChatLink,
+ chatByTelegram,
+ chatMessageByTelegram,
+ chatMessagesAfter,
+ getSetting,
+ isChatLinkCode,
+ lastChatMessageId,
+ mayWriteChat,
+ migrateChatGroup,
+ mirrorTargets,
+ syncChats,
+ telegramAccountUser,
+ threadAnchor,
+ type Chat,
+ type ChatMessage,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
-import { acceptTask, answerAndDeliver, decideIncident, moveTask, resumeSession, stopSession } from "@peppa/runner";
+import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
@@ -161,6 +176,7 @@ export function createBot(o: BotOptions) {
});
}
}
+ await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`));
for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) {
await enqueueTelegram(db, {
dedupeKey: `qa:${q.id}:${sent.params.chat_id}`,
@@ -178,6 +194,52 @@ export function createBot(o: BotOptions) {
wakeOutbox?.();
}
+ // ── chats → linked Telegram groups (PEP-62) ────────────────────────────────────
+ const MIRROR_CURSOR = "chat.mirror.cursor";
+
+ /** Projects new events into chats and queues new chat messages for the linked groups. */
+ async function mirrorChats(): Promise {
+ await syncChats(db);
+ let cursor = await getSetting(db, MIRROR_CURSOR);
+ // First start: only what comes from now on (a newly linked group doesn't get the backlog).
+ if (cursor == null) return setSetting(db, MIRROR_CURSOR, await lastChatMessageId(db));
+ for (;;) {
+ const rows = await chatMessagesAfter(db, cursor);
+ for (const { m, chat } of rows) {
+ for (const t of await mirrorTargets(db, m, chat)) await mirrorOne(m, chat, t.tgChatId, t.master);
+ cursor = m.id;
+ }
+ await setSetting(db, MIRROR_CURSOR, cursor);
+ if (rows.length < 100) break;
+ }
+ }
+
+ async function mirrorOne(m: ChatMessage, chat: Chat, tgChatId: number, master: boolean): Promise {
+ const key = chat.projectId ? await projectKey(chat.projectId) : "";
+ const where = [master && key ? `[${esc(key)}]` : null, m.threadTitle ? `🧵 ${esc(m.threadTitle)} ` : null].filter(Boolean).join(" ");
+ let text: string;
+ let buttons: InlineButton[][] = [];
+ let questionId: number | undefined;
+ if (m.kind === "question" && m.questionId) {
+ const q = await getQuestion(db, m.questionId).catch(() => null);
+ if (!q || q.answeredAt) return;
+ const r = renderQuestion(q, await context(q));
+ text = r.text;
+ 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)}` : ""}`;
+ }
+ await enqueueTelegram(db, {
+ dedupeKey: `cm:${m.id}:${tgChatId}`,
+ method: "sendMessage",
+ questionId,
+ chatMessageId: m.id,
+ params: { chat_id: tgChatId, text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(buttons.length ? { reply_markup: { inline_keyboard: buttons } } : {}) },
+ });
+ }
+
async function projectKey(projectId: number): Promise {
const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
return p?.key ?? "";
@@ -199,8 +261,14 @@ export function createBot(o: BotOptions) {
const q = await getQuestion(db, row.questionId).catch(() => null);
if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null);
}
+ let params = row.params;
+ if (row.method === "sendMessage" && row.chatMessageId && !params.reply_parameters) {
+ // PEP-62: a thread in a group = a chain of replies to its first message.
+ const anchor = await threadAnchor(db, row);
+ if (anchor) params = { ...params, reply_parameters: { message_id: anchor, allow_sending_without_reply: true } };
+ }
try {
- const res = await api.call(row.method, row.params);
+ const res = await api.call(row.method, params);
await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null);
} catch (e) {
if (!(e instanceof TelegramError)) throw e;
@@ -377,7 +445,52 @@ export function createBot(o: BotOptions) {
return "Неизвестная кнопка";
}
+ /** A message in a group (PEP-62): linking by code, then replies and commands of the linked chat. */
+ async function onGroupMessage(m: TgMessage): Promise<"done" | "ignored"> {
+ 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");
+ 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 — команды.`);
+ return "done";
+ }
+ const chat = await chatByTelegram(db, m.chat.id);
+ if (!chat || !m.from || !text) return "ignored";
+ // Group chatter stays in Telegram: only replies and commands reach the chat.
+ 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);
+ return "done";
+ }
+ enterActor({ kind: "user", userId: user.id, channel: "telegram" });
+ // A reply finds its thread (and chat: the master group holds project threads too).
+ const target = m.reply_to_message ? await chatMessageByTelegram(db, m.chat.id, m.reply_to_message.message_id) : null;
+ try {
+ await postToChat(db, user, {
+ chatId: target?.chatId ?? chat.id,
+ threadKey: target?.threadKey ?? null,
+ text,
+ via: "telegram",
+ questionId: target?.kind === "question" ? target.questionId : null,
+ tg: { chatId: m.chat.id, messageId: m.message_id },
+ });
+ } catch (e) {
+ await reply(m.chat.id, esc((e as Error).message), m.message_id);
+ }
+ scheduleReconcile();
+ return "done";
+ }
+
async function onMessage(m: TgMessage): Promise<"done" | "ignored"> {
+ if (m.migrate_to_chat_id) {
+ await migrateChatGroup(db, m.chat.id, m.migrate_to_chat_id);
+ return "done";
+ }
+ if (m.chat.type !== "private") return onGroupMessage(m);
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
@@ -426,7 +539,13 @@ export function createBot(o: BotOptions) {
}
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
- const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
+ let user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
+ if (!user && c.message && c.message.chat.type !== "private") {
+ // PEP-62: buttons in a linked group — the presser's own account and access to the chat.
+ const chat = await chatByTelegram(db, c.message.chat.id);
+ const who = chat ? await telegramAccountUser(db, c.from.id) : null;
+ if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who;
+ }
if (!user) {
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
return "ignored";
diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts
index b8039146..2e734cff 100644
--- a/apps/bot/src/telegram.ts
+++ b/apps/bot/src/telegram.ts
@@ -8,9 +8,11 @@ export interface TgUser {
}
export interface TgMessage {
message_id: number;
- chat: { id: number; type: string };
+ chat: { id: number; type: string; title?: string };
from?: TgUser;
text?: string;
+ /** PEP-62: a group became a supergroup (new chat id). */
+ migrate_to_chat_id?: number;
reply_to_message?: TgMessage;
/** PEP-45: voice notes and audio files become stories after transcription. */
voice?: TgFileRef;
diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/pep-62-chats/design.md
index eb2c3412..c59eb13e 100644
--- a/openspec/changes/pep-62-chats/design.md
+++ b/openspec/changes/pep-62-chats/design.md
@@ -65,8 +65,9 @@ PEP-21 сами уходят в раннер-сервис.
что существующая правка «отвечено» и `questionByTelegramMessage` работают и в группе).
- **Приём**: сообщение в связанной группе → пользователь по `users.telegram_user_id`
(личная привязка PEP-2) и не отключён → доступ к проекту / владелец мастер-чата.
- Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); иначе — общий
- канал. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает
+ Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); команда без
+ реплая — общий канал. Обычная болтовня в группе (не реплай и не команда) остаётся в Telegram
+ и в чат не попадает — даже если privacy mode бота выключен. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает
привязать Telegram. Privacy mode бота оставляем: он видит команды и реплаи на свои
сообщения — этого достаточно для тредов.
- Личные уведомления в личку не меняются (их можно выключить по проекту в «Уведомлениях»).
diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts
index 72dbe607..f14ef30e 100644
--- a/packages/core/src/telegram.ts
+++ b/packages/core/src/telegram.ts
@@ -85,7 +85,7 @@ export async function finishUpdate(db: Db, updateId: number, status: "done" | "i
/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */
export async function enqueueTelegram(
db: Db,
- m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number },
+ m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number; chatMessageId?: number },
): Promise {
const rows = await db.insert(telegramOutbox).values(m).onConflictDoNothing().returning();
return rows.length > 0;
--
2.45.2
From a0d1097e376b4ace82221513f7186d8216834f25 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 19:09:32 +0500
Subject: [PATCH 003/428] =?UTF-8?q?PEP-62:=20web=20=C2=AB=D0=A7=D0=B0?=
=?UTF-8?q?=D1=82=D1=8B=C2=BB=20(master=20+=20project=20chats,=20threads,?=
=?UTF-8?q?=20composer,=20Telegram=20link),=20live=20scope,=20watchdog=20s?=
=?UTF-8?q?ync/TTL,=20e2e?=
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)/chats/[chat]/page.tsx | 248 ++++++++++++++++++++++
apps/web/app/(app)/chats/actions.ts | 54 +++++
apps/web/app/(app)/chats/page.tsx | 5 +
apps/web/components/Sidebar.tsx | 11 +-
packages/runner/src/live.ts | 17 +-
packages/runner/src/watchdog.ts | 10 +
packages/testkit/src/mock-telegram.ts | 21 +-
packages/testkit/test/chats.test.ts | 253 +++++++++++++++++++++++
8 files changed, 611 insertions(+), 8 deletions(-)
create mode 100644 apps/web/app/(app)/chats/[chat]/page.tsx
create mode 100644 apps/web/app/(app)/chats/actions.ts
create mode 100644 apps/web/app/(app)/chats/page.tsx
create mode 100644 packages/testkit/test/chats.test.ts
diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx
new file mode 100644
index 00000000..8b915adf
--- /dev/null
+++ b/apps/web/app/(app)/chats/[chat]/page.tsx
@@ -0,0 +1,248 @@
+import Link from "next/link";
+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";
+import { projects, questions, tasks } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { eq, inArray } from "drizzle-orm";
+import { LiveRefresh } from "@/components/LiveRefresh";
+import { ago, Empty, Flash, PageHeader } from "@/components/common";
+import { Hidden, QuestionCard } from "@/components/cards";
+import { Workspace } from "@/components/Workspace";
+import { Button } from "@/components/ui/button";
+import { Textarea } from "@/components/ui/input";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { cn } from "@/lib/utils";
+import { linkChatAction, postChatAction, unlinkChatAction } from "../actions";
+
+type Params = { error?: string; thread?: string; link?: string };
+
+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 { 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).
+ await syncChats(db).catch((e) => console.error("syncChats", e));
+ const list = await listChats(db, user);
+ const chat = list.find((c) => c.slug.toLowerCase() === slug.toLowerCase());
+ if (!chat) notFound();
+ const master = chat.kind === "master";
+ const thread = rawThread === CHANNEL ? null : rawThread && THREAD_KEY.test(rawThread) ? rawThread : undefined;
+
+ 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;
+
+ // 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);
+ const qs = qIds.length
+ ? await db.select({ q: questions, status: tasks.status, key: projects.key, number: tasks.number }).from(questions).innerJoin(projects, eq(questions.projectId, projects.id)).leftJoin(tasks, eq(questions.taskId, tasks.id)).where(inArray(questions.id, qIds))
+ : [];
+ const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }]));
+
+ const url = (p: { thread?: string | null }) => {
+ const base = `/chats/${chat.slug}`;
+ return p.thread ? `${base}?thread=${encodeURIComponent(p.thread)}` : base;
+ };
+ const here = url({ thread: thread === null ? CHANNEL : thread });
+ const bot = (await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null;
+ const ttlDays = Math.round(chatTtlMs() / 86_400_000);
+ const taskThread = thread?.startsWith("task:");
+ const placeholder = master
+ ? "/status, /task KEY-N, /move KEY-N in_progress, /help"
+ : taskThread
+ ? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
+ : thread
+ ? "Заметка в тред или команда /help"
+ : "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
+
+ const aside = (
+
+
+ Telegram
+ {chat.tgTitle ? (
+ <>
+
+ Связан с группой {chat.tgTitle} . Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}.
+
+
+ >
+ ) : link ? (
+
+ ) : (
+ <>
+ {master ? "Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам." : "Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}
+
+ >
+ )}
+ Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только ты)" : "проекту"}.
+
+
+ Как это устроено
+ {master ? "Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM." : "Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной."}
+ Переписка хранится {ttlDays} дн.; стори, вопросы и события остаются на своих страницах.
+
+
+ );
+
+ return (
+
+
+
+ Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.
+
+
+ {list.map((c) => (
+
+ {c.kind === "master" ? : }
+ {c.kind === "master" ? "Мастер-чат" : c.slug}
+ {c.tgTitle && }
+ {c.open > 0 && {c.open} }
+
+ ))}
+
+
+
+ {!master && (
+
+
+
+ {threads.length > 0 &&
}
+ {threads.map((t) => (
+
+ ))}
+ {threads.length === 0 && Тредов пока нет.
}
+
+ )}
+
+
+ {current && (
+
+ 🧵 {current}
+ {taskThread && }
+
+ )}
+ {messages.length === 0 ? (
+ {master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}
+ ) : (
+
+ {messages.map((m) => (
+
+
+
+ ))}
+
+ )}
+
+
+
+
+ );
+}
+
+function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) {
+ return (
+
+
+ {title}
+ {open > 0 && {open} }
+
+ {meta && {meta} }
+
+ );
+}
+
+function TaskLink({ messages }: { messages: ChatMessageView[] }) {
+ const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
+ return key ? открыть стори → : null;
+}
+
+function threadHref(m: ChatMessageView) {
+ return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
+}
+
+function MessageItem({ m, q, back, showThread, masterView }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean }) {
+ const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
+ const href = threadHref(m);
+ const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle].filter(Boolean).join(" · ");
+ const head = (
+
+ {m.authorKind === "user" ? : m.authorKind === "agent" ? : }
+ {m.authorKind === "user" ? (m.authorLogin ?? "?") : m.authorKind === "agent" ? "агент" : "Пеппа"}
+ {m.via === "telegram" && · Telegram }
+ {where && href && (
+
+ 🧵 {label}
+
+ )}
+ {ago(m.createdAt)}
+
+ );
+ if (q) {
+ return (
+
+ {head}
+
+
+ );
+ }
+ return (
+
+ {head}
+ {m.text}
+ {m.url && (
+
+ {m.url}
+
+ )}
+
+ );
+}
diff --git a/apps/web/app/(app)/chats/actions.ts b/apps/web/app/(app)/chats/actions.ts
new file mode 100644
index 00000000..019d2c91
--- /dev/null
+++ b/apps/web/app/(app)/chats/actions.ts
@@ -0,0 +1,54 @@
+"use server";
+// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
+
+import { chatForUser, createChatLinkCode, PeppaError, unlinkChat } from "@peppa/core";
+import { postToChat } from "@peppa/runner";
+import { loadEnv } from "@peppa/shared";
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { asWebActor, requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+
+const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
+
+/** Runs an action; errors come back as ?error=… (redirect stays outside try). */
+async function attempt(f: FormData, fn: () => Promise): Promise {
+ let target = str(f, "back") || "/chats";
+ try {
+ target = (await fn()) || target;
+ } catch (e) {
+ const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
+ const [path, query] = target.split("?");
+ const params = new URLSearchParams(query);
+ params.set("error", msg.slice(0, 300));
+ target = `${path}?${params}`;
+ }
+ revalidatePath("/chats", "layout");
+ redirect(target);
+}
+
+export async function postChatAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const thread = str(f, "thread");
+ await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web" });
+ });
+}
+
+/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link that sends it. */
+export async function linkChatAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const token = loadEnv().TELEGRAM_BOT_TOKEN;
+ if (!token) throw new PeppaError("Telegram-бот Пеппы не настроен");
+ const chat = await chatForUser(db, user, Number(str(f, "chatId")));
+ const code = await createChatLinkCode(db, token, user, chat.id);
+ const back = str(f, "back") || "/chats";
+ return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`;
+ });
+}
+
+export async function unlinkChatAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId"))));
+}
diff --git a/apps/web/app/(app)/chats/page.tsx b/apps/web/app/(app)/chats/page.tsx
new file mode 100644
index 00000000..3e0aa8cf
--- /dev/null
+++ b/apps/web/app/(app)/chats/page.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "next/navigation";
+
+export default function Chats() {
+ redirect("/chats/master");
+}
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 0cd5a95d..10260786 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, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
+import { Bot, Contact, FolderKanban, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@@ -16,13 +16,16 @@ interface Item {
count?: "questions" | "waitingRunners";
/** Superadmin only (PEP-68, PEP-67; others get 404 on the URL too); desktop panel only — on phones it is linked from Settings. */
admin?: boolean;
+ /** Not in the phone tab bar (six tabs fit; PEP-62 added «Чаты»). */
+ desktopOnly?: boolean;
}
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") },
+ { 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 },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
@@ -55,7 +58,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
{ITEMS.filter((i) => !i.admin || superadmin).map((i) => {
const active = i.match(path);
@@ -66,7 +69,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
href={i.href}
aria-current={active ? "page" : undefined}
className={cn(
- i.admin && "max-md:hidden",
+ (i.admin || i.desktopOnly) && "max-md:hidden",
"relative flex flex-col items-center gap-0.5 px-1 pt-2 pb-1.5 text-[10px] text-muted-foreground transition-colors hover:text-foreground hover:no-underline md:flex-row md:gap-2 md:rounded-md md:px-2.5 md:py-1.5 md:text-sm md:hover:bg-accent",
active && "font-medium text-foreground md:bg-accent md:before:absolute md:before:inset-y-1.5 md:before:-left-3 md:before:w-0.5 md:before:rounded-full md:before:bg-primary",
)}
diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts
index b042192e..1f1211b1 100644
--- a/packages/runner/src/live.ts
+++ b/packages/runner/src/live.ts
@@ -9,7 +9,7 @@ import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type
import { events, sessions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
-export type LiveScope = "home" | "runners" | `project:${number}` | `task:${number}` | `steps:${number}`;
+export type LiveScope = "home" | "runners" | "chats" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
type Listener = (e: LiveEvent) => void;
@@ -29,7 +29,7 @@ const WAKE_DEBOUNCE_MS = 250;
export function parseScopes(raw: string | null): LiveScope[] {
const out = new Set();
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
- if (part === "home" || part === "runners") out.add(part);
+ if (part === "home" || part === "runners" || part === "chats") out.add(part);
else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
else throw new LiveError(`Неизвестная область: ${part}`, 400);
}
@@ -99,6 +99,19 @@ function fingerprint(db: Db, scope: LiveScope): string {
.get(id) as Record;
return Object.values(row).join("|");
}
+ if (kind === "chats") {
+ // PEP-62: a new chat message (projected or written) or a question answered anywhere.
+ const row = c
+ .prepare(
+ `SELECT
+ (SELECT coalesce(max(id),0) FROM chat_messages) AS m,
+ (SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
+ (SELECT coalesce(max(id),0) FROM events WHERE type <> 'step') AS e,
+ (SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`,
+ )
+ .get() as Record;
+ return Object.values(row).join("|");
+ }
// home / runners: across projects (only wakes the page — data stays behind access checks).
const row = c
.prepare(
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 3175e7a0..3a1bf448 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
+ pruneChats,
+ syncChats,
getBudgetState,
runAsActor,
expireSessionQuestions,
@@ -83,7 +85,15 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise {
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
// 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}`));
+ // 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}`));
+ 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}`));
+ }
}
+let lastChatPrune = 0;
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
if (s.tmuxName.startsWith("pending-")) return;
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 9b177f04..d415bf6f 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -18,6 +18,9 @@ export interface MockTgUser {
username?: string;
}
+/** Groups have negative ids in Telegram. */
+const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
+
export class MockTelegram {
readonly token = "mock-123:TOKEN";
readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
@@ -104,7 +107,7 @@ export class MockTelegram {
reply_to: (p.reply_parameters as { message_id?: number } | undefined)?.message_id,
};
this.messages.set(m.message_id, m);
- return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: "private" }, text: m.text } };
+ return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: chatType(m.chat_id) }, text: m.text } };
}
case "editMessageText": {
const m = this.messages.get(Number(p.message_id));
@@ -148,6 +151,20 @@ export class MockTelegram {
});
}
+ /** PEP-62: a user writes in a group (negative chat id, as in Telegram), optionally as a reply. */
+ userSendsInGroup(user: MockTgUser, group: { id: number; title: string }, text: string, replyTo?: number) {
+ const chat = { id: group.id, type: "group", title: group.title };
+ return this.push({
+ message: {
+ message_id: this.nextMessageId++,
+ chat,
+ from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
+ text,
+ ...(replyTo ? { reply_to_message: { message_id: replyTo, chat } } : {}),
+ },
+ });
+ }
+
/** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */
userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) {
const fileId = `mock-voice-${this.nextMessageId}`;
@@ -170,7 +187,7 @@ export class MockTelegram {
callback_query: {
id,
from: { id: user.id, username: user.username },
- message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: "private" }, text: m?.text },
+ message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: chatType(m?.chat_id ?? user.chatId) }, text: m?.text },
data,
},
});
diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts
new file mode 100644
index 00000000..7b7a0c60
--- /dev/null
+++ b/packages/testkit/test/chats.test.ts
@@ -0,0 +1,253 @@
+// PEP-62: chats — events projected into project chats with threads, a reply in a story thread
+// goes to the agent, the master feed and its commands, a linked Telegram group (the real bot
+// against mock-telegram), and the short TTL.
+import assert from "node:assert/strict";
+import { after, before, describe, test } from "node:test";
+// helpers must load first: it sets the isolated test env that runner modules read on load.
+import { core, db, runner, teardown, waitFor } from "./helpers.ts";
+import { MockTelegram } from "../src/mock-telegram.ts";
+import { chatMessages, users } from "@peppa/db";
+import { eq } from "drizzle-orm";
+import type { Bot } from "@peppa/bot";
+
+const { createBot } = await import("@peppa/bot");
+const { TelegramApi } = await import("@peppa/bot/telegram");
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const tg = await new MockTelegram().start();
+const PM = { id: 701, chatId: 701, username: "pm" };
+const BOB = { id: 702, chatId: 702, username: "bob" };
+const STRANGER = { id: 709, chatId: 709, username: "stranger" };
+const GROUP = { id: -100500, title: "PAY team" };
+let bot: Bot;
+let pm: Awaited>;
+let bob: typeof pm;
+let eve: typeof pm;
+let seq = 0;
+
+async function newProject() {
+ const key = `C${String.fromCharCode(65 + seq++)}`;
+ const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
+ await core.addMember(db, p, bob.login, pm.id);
+ return p;
+}
+async function newTask(p: { id: number }, title = "Экспорт в CSV") {
+ const ref = await core.createTask(db, { projectId: p.id, title });
+ return core.resolveTask(db, ref.key);
+}
+const threadOf = (taskId: number) => `task:${taskId}`;
+const groupMessages = () => tg.botMessages(GROUP.id);
+
+before(async () => {
+ pm = await core.upsertUserFromGitea(db, { id: 81, login: "mock-pm" }, { access_token: "x" });
+ bob = await core.upsertUserFromGitea(db, { id: 82, login: "mock-bob" }, { access_token: "y" });
+ eve = await core.upsertUserFromGitea(db, { id: 83, login: "mock-eve" }, { access_token: "z" });
+ await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
+ await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
+ pm = (await core.getUser(db, pm.id))!;
+ bob = (await core.getUser(db, bob.id))!;
+});
+after(async () => {
+ await bot?.stop();
+ await tg.stop();
+ await teardown();
+});
+
+describe("project chat", () => {
+ test("Вопрос агента в треде стори; повторный перенос без дублей", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
+ await core.syncChats(db);
+ await core.syncChats(db);
+ const msgs = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ const qs = msgs.filter((m) => m.question?.id === q.id);
+ assert.equal(qs.length, 1);
+ assert.equal(qs[0]!.threadTitle, `${ref.key} · Экспорт в CSV`);
+ const threads = await core.chatThreads(db, chat.id);
+ assert.equal(threads[0]!.key, threadOf(ref.task.id));
+ assert.equal(threads[0]!.open, 1);
+ // The question is still on the home page (pending questions).
+ assert.ok((await core.pendingQuestions(db)).some((x) => x.id === q.id));
+ });
+
+ test("Ответ на вопрос из треда уходит агенту", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?" });
+ const r = await runner.postToChat(db, bob, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "точка с запятой", via: "web" });
+ const fresh = await core.getQuestion(db, q.id);
+ assert.equal(fresh.answer, "точка с запятой");
+ assert.equal(fresh.answeredVia, "web");
+ assert.match(r.reply!.text, /сохранён|ушёл агенту/);
+ const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ assert.ok(thread.some((m) => m.kind === "user" && m.authorLogin === bob.login && m.text === "точка с запятой"));
+ });
+
+ test("Комментарий без вопроса: у стори комментарий, в треде одно сообщение", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const r = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "не забудь заголовки", via: "web" });
+ assert.match(r.reply!.text, /Комментарий сохранён/);
+ const comments = await core.storyComments(db, ref.task.id);
+ assert.deepEqual(comments.map((c) => c.text), ["не забудь заголовки"]);
+ await core.syncChats(db);
+ const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ assert.equal(thread.filter((m) => m.text === "не забудь заголовки").length, 1);
+ });
+
+ test("Чужой проект: запрос отклонён, сообщения нет", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ await assert.rejects(runner.postToChat(db, eve, { chatId: chat.id, threadKey: null, text: "привет", via: "web" }), /не найден/);
+ assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
+ assert.equal((await core.listChats(db, eve)).filter((c) => c.kind === "project").length, 0);
+ });
+
+ test("Тред чужого проекта нельзя подставить", async () => {
+ const a = await newProject();
+ const b = await newProject();
+ const ref = await newTask(b);
+ const chat = await core.ensureProjectChat(db, a.id);
+ await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "x", via: "web" }), /не из этого чата/);
+ });
+
+ test("Релиз и инцидент — свои треды", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const { releases } = await import("@peppa/db");
+ const [rel] = await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "abcdef1234567", status: "healthy", tasks: ["CX-1"] }).returning();
+ await core.syncChats(db);
+ const threads = await core.chatThreads(db, chat.id);
+ assert.ok(threads.some((t) => t.key === `release:${rel!.id}` && t.title === "Релиз staging abcdef1"));
+ });
+});
+
+describe("master chat", () => {
+ test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => {
+ const p = await newProject();
+ const ref = await newTask(p, "Платежи");
+ await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "stalled", payload: { idleMinutes: 15 } });
+ await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "progress", payload: { text: "половина готова" } });
+ await core.syncChats(db);
+ const feed = await core.masterFeed(db, pm);
+ assert.ok(feed.some((m) => /Агент молчит 15 мин/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
+ assert.ok(!feed.some((m) => /половина готова/.test(m.text)), "progress is not important");
+
+ const master = await core.ensureMasterChat(db, pm.id);
+ const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/task ${ref.key}`, via: "web" });
+ assert.match(r.reply!.text, new RegExp(`${ref.key}: Платежи[\\s\\S]*бэклог`));
+ const bad = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: "/deploy всё", via: "web" });
+ assert.match(bad.reply!.text, /Не знаю такую команду[\s\S]*\/move/);
+ // Bob's master chat is his own.
+ await assert.rejects(runner.postToChat(db, bob, { chatId: master.id, threadKey: null, text: "/status", via: "web" }), /не найден/);
+ });
+
+ test("Команда перемещения", async () => {
+ const p = await newProject();
+ const ref = await newTask(p);
+ const master = await core.ensureMasterChat(db, pm.id);
+ const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/move ${ref.key} done`, via: "web" });
+ assert.match(r.reply!.text, new RegExp(`${ref.key} → Готово`));
+ assert.equal((await core.resolveTask(db, ref.key)).task.status, "done");
+ });
+});
+
+describe("Telegram group", () => {
+ let p: Awaited>;
+ let chat: Awaited>;
+
+ before(async () => {
+ p = await newProject();
+ chat = await core.ensureProjectChat(db, p.id);
+ bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, changesIntervalMs: 200, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
+ await bot.start();
+ await bot.reconcile(); // first start: mirroring begins from here
+ });
+
+ test("Просроченный код и связка группы", async () => {
+ const code = await core.createChatLinkCode(db, tg.token, pm, chat.id);
+ // A stale code: accepted 11 minutes later.
+ const stale = await core.createChatLinkCode(db, tg.token, pm, chat.id);
+ assert.equal(await core.acceptChatLink(db, tg.token, stale, { tgChatId: -1, title: "x" }, Date.now() + 11 * 60_000), null);
+ tg.userSendsInGroup(PM, GROUP, `/link ${stale}`);
+ await waitFor("stale code reply", async () => groupMessages().some((m) => /неверный или истёк/.test(m.text)));
+ tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${code}`);
+ await waitFor("linked", async () => groupMessages().some((m) => /Группа связана с чатом проекта/.test(m.text)));
+ const linked = await core.getChat(db, chat.id);
+ assert.equal(linked.tgChatId, GROUP.id);
+ assert.equal(linked.tgTitle, GROUP.title);
+ });
+
+ test("Вопрос в группе, ответ реплаем, тред — цепочка ответов", async () => {
+ const ref = await newTask(p, "Экспорт отчёта");
+ const q = await core.askPm(db, ref, { kind: "question", text: "Какой формат даты?", options: ["ISO", "ДД.ММ.ГГГГ"] });
+ const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Какой формат даты?")));
+ assert.ok(qMsg.reply_markup?.inline_keyboard.flat().some((b) => b.callback_data === `q:${q.id}:o0`));
+
+ // Somebody without a Peppa account replies: ignored with a hint.
+ tg.userSendsInGroup(STRANGER, GROUP, "ISO конечно", qMsg.message_id);
+ await waitFor("stranger hint", async () => groupMessages().some((m) => /Не знаю тебя в Пеппе/.test(m.text)));
+ assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
+
+ tg.userSendsInGroup(BOB, GROUP, "ДД.ММ.ГГГГ", qMsg.message_id);
+ const answered = await waitFor("answered from the group", async () => {
+ const x = await core.getQuestion(db, q.id);
+ return x.answeredAt ? x : null;
+ });
+ assert.equal(answered.answer, "ДД.ММ.ГГГГ");
+ assert.equal(answered.answeredVia, "telegram");
+ const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ assert.ok(thread.some((m) => m.kind === "user" && m.via === "telegram" && m.authorLogin === bob.login));
+ // Peppa's note about it hangs on the thread's first message; Bob's own message isn't echoed.
+ const note = await waitFor("reply note in the thread", async () => groupMessages().find((m) => /Ответ (ушёл агенту|сохранён)/.test(m.text)));
+ assert.equal(note.reply_to, qMsg.message_id);
+ assert.ok(!groupMessages().some((m) => m.text.includes("mock-bob") && m.text.includes("ДД.ММ.ГГГГ") && !m.text.includes("Какой формат")));
+
+ // A web message in the same thread reaches the group as a reply too.
+ await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "и время в UTC", via: "web" });
+ const web = await waitFor("web message in the group", async () => groupMessages().find((m) => m.text.includes("и время в UTC")));
+ assert.equal(web.reply_to, qMsg.message_id);
+ assert.match(web.text, /mock-pm.*\(веб\)/);
+ });
+
+ test("Кнопка вопроса в группе", async () => {
+ const ref = await newTask(p, "Кнопки");
+ const q = await core.askPm(db, ref, { kind: "question", text: "Кнопкой?", options: ["да", "нет"] });
+ const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Кнопкой?")));
+ tg.userClicks(STRANGER, qMsg.message_id, `q:${q.id}:o0`);
+ await waitFor("stranger refused", async () => tg.callbackAnswers.some((c) => /Нет доступа/.test(c.text ?? "")));
+ tg.userClicks(BOB, qMsg.message_id, `q:${q.id}:o1`);
+ const x = await waitFor("answered by button", async () => {
+ const r = await core.getQuestion(db, q.id);
+ return r.answeredAt ? r : null;
+ });
+ assert.equal(x.answer, "нет");
+ });
+
+ test("Супергруппа сохраняет связку", async () => {
+ // Telegram sends migrate_to_chat_id when a group is upgraded.
+ await core.migrateChatGroup(db, GROUP.id, -1009999);
+ assert.equal((await core.getChat(db, chat.id)).tgChatId, -1009999);
+ await core.migrateChatGroup(db, -1009999, GROUP.id);
+ });
+});
+
+describe("TTL", () => {
+ test("Старые сообщения удалены, вопрос остаётся", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const q = await core.askPm(db, ref, { kind: "question", text: "Старый вопрос" });
+ await core.syncChats(db);
+ const old = new Date(Date.now() - 15 * 86_400_000);
+ await db.update(chatMessages).set({ createdAt: old }).where(eq(chatMessages.chatId, chat.id));
+ const n = await core.pruneChats(db);
+ assert.ok(n >= 1);
+ assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
+ assert.equal((await core.getQuestion(db, q.id)).text, "Старый вопрос");
+ });
+});
--
2.45.2
From c751291bb9aab4d2a5f83410575e1748736236f8 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 19:10:12 +0500
Subject: [PATCH 004/428] PEP-62: help and AGENTS.md for chats
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
apps/web/app/(app)/help/page.tsx | 16 ++++++++++++++++
openspec/changes/pep-62-chats/tasks.md | 22 +++++++++++-----------
3 files changed, 28 insertions(+), 11 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 6ba94b29..e02aefcd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,6 +34,7 @@
- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
+- **Чаты (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-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (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`
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 049e478e..dc1ebc3b 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -204,6 +204,22 @@ export default async function Help() {
+
+
+ Чаты — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы,
+ прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый
+ вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам
+ (вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N,
+ /move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней.
+
+
+ Любой чат можно связать с группой Telegram: «Связать с Telegram» в чате → добавьте бота в группу по ссылке (или
+ отправьте в группе /link код ). Сообщения чата придут в группу, тред — цепочкой
+ ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в
+ Настройках и имеет доступ к проекту (в мастер-группе — только владелец).
+
+
+
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
diff --git a/openspec/changes/pep-62-chats/tasks.md b/openspec/changes/pep-62-chats/tasks.md
index cbf0dcdf..1e389b73 100644
--- a/openspec/changes/pep-62-chats/tasks.md
+++ b/openspec/changes/pep-62-chats/tasks.md
@@ -1,21 +1,21 @@
## 1. Модель и ядро
-- [ ] 1.1 Схема `chats`, `chat_messages`, `telegram_outbox.chat_message_id`, миграция
-- [ ] 1.2 core/chats.ts: чаты (ensure), проекция `syncChats`, ленты/треды, коды связки, TTL
-- [ ] 1.3 Мастер-чат: мониторинг и дайджест из `deliverToUser`
+- [x] 1.1 Схема `chats`, `chat_messages`, `telegram_outbox.chat_message_id`, миграция
+- [x] 1.2 core/chats.ts: чаты (ensure), проекция `syncChats`, ленты/треды, коды связки, TTL
+- [x] 1.3 Мастер-чат: мониторинг и дайджест из `deliverToUser`
## 2. Ответы и команды
-- [ ] 2.1 runner/chats.ts `postToChat`: ответ агенту / комментарий / заметка, команды
+- [x] 2.1 runner/chats.ts `postToChat`: ответ агенту / комментарий / заметка, команды
## 3. Telegram
-- [ ] 3.1 Бот: связка группы (`/start <код>`, `/link`), миграция в супергруппу
-- [ ] 3.2 Бот: зеркало сообщений в группы, треды реплаями, кнопки вопросов
-- [ ] 3.3 Бот: приём реплаев, команд и кнопок из групп с проверкой доступа
+- [x] 3.1 Бот: связка группы (`/start <код>`, `/link`), миграция в супергруппу
+- [x] 3.2 Бот: зеркало сообщений в группы, треды реплаями, кнопки вопросов
+- [x] 3.3 Бот: приём реплаев, команд и кнопок из групп с проверкой доступа
## 4. Веб и вачдог
-- [ ] 4.1 `/chats/[chat]`: список чатов, треды, лента, композер, связка с Telegram; меню
-- [ ] 4.2 Живое обновление (`chats`), вызовы проекции и TTL в вачдоге, создание чата с проектом
-- [ ] 4.3 Справка `/help`, AGENTS.md
+- [x] 4.1 `/chats/[chat]`: список чатов, треды, лента, композер, связка с Telegram; меню
+- [x] 4.2 Живое обновление (`chats`), вызовы проекции и TTL в вачдоге, создание чата с проектом
+- [x] 4.3 Справка `/help`, AGENTS.md
## 5. Проверка
-- [ ] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
+- [x] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
- [ ] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
--
2.45.2
From 5cfc2cb269f5572d0517b947405392ece154a109 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 19:12:57 +0500
Subject: [PATCH 005/428] PEP-62: archive change pep-62-chats, project memory
Co-Authored-By: Claude Opus 5.5
---
.peppa/memory.md | 9 ++
.../2026-11-14-pep-62-chats}/design.md | 0
.../2026-11-14-pep-62-chats}/proposal.md | 0
.../specs/project-chats/spec.md | 0
.../2026-11-14-pep-62-chats}/tasks.md | 2 +-
openspec/specs/project-chats/spec.md | 101 ++++++++++++++++++
6 files changed, 111 insertions(+), 1 deletion(-)
create mode 100644 .peppa/memory.md
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/design.md (100%)
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/proposal.md (100%)
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/specs/project-chats/spec.md (100%)
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/tasks.md (95%)
create mode 100644 openspec/specs/project-chats/spec.md
diff --git a/.peppa/memory.md b/.peppa/memory.md
new file mode 100644
index 00000000..d53119c3
--- /dev/null
+++ b/.peppa/memory.md
@@ -0,0 +1,9 @@
+# Память проекта
+
+Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.
+
+## Грабли
+- 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 …`
+
+## Решения
+- Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents.
diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/archive/2026-11-14-pep-62-chats/design.md
similarity index 100%
rename from openspec/changes/pep-62-chats/design.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/design.md
diff --git a/openspec/changes/pep-62-chats/proposal.md b/openspec/changes/archive/2026-11-14-pep-62-chats/proposal.md
similarity index 100%
rename from openspec/changes/pep-62-chats/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/proposal.md
diff --git a/openspec/changes/pep-62-chats/specs/project-chats/spec.md b/openspec/changes/archive/2026-11-14-pep-62-chats/specs/project-chats/spec.md
similarity index 100%
rename from openspec/changes/pep-62-chats/specs/project-chats/spec.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/specs/project-chats/spec.md
diff --git a/openspec/changes/pep-62-chats/tasks.md b/openspec/changes/archive/2026-11-14-pep-62-chats/tasks.md
similarity index 95%
rename from openspec/changes/pep-62-chats/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/tasks.md
index 1e389b73..0d8f7aab 100644
--- a/openspec/changes/pep-62-chats/tasks.md
+++ b/openspec/changes/archive/2026-11-14-pep-62-chats/tasks.md
@@ -18,4 +18,4 @@
## 5. Проверка
- [x] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
-- [ ] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
+- [x] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/project-chats/spec.md b/openspec/specs/project-chats/spec.md
new file mode 100644
index 00000000..10c091dd
--- /dev/null
+++ b/openspec/specs/project-chats/spec.md
@@ -0,0 +1,101 @@
+# project-chats Specification
+
+## Purpose
+TBD - created by archiving change pep-62-chats. Update Purpose after archive.
+
+## Requirements
+
+### Requirement: Чат проекта с тредами
+У каждого проекта SHALL быть чат. События проекта SHALL попадать в чат: про стори — в тред
+стори, про инцидент — в тред инцидента, про релиз — в тред релиза, остальное — в общий
+канал. Перенос событий SHALL быть идемпотентным: повторный запуск не создаёт дублей.
+
+#### Scenario: Вопрос агента в треде стори
+- **GIVEN** проект PAY со стори PAY-7 «Экспорт в CSV»
+- **WHEN** агент PAY-7 задаёт вопрос «Какой разделитель?»
+- **THEN** в чате PAY появляется тред «PAY-7 · Экспорт в CSV» с этим вопросом и кнопками ответа
+- **AND** вопрос по-прежнему виден на Главной
+
+#### Scenario: Повторный перенос
+- **GIVEN** вопрос PAY-7 уже перенесён в чат
+- **WHEN** перенос запускается ещё раз из бота и из веба
+- **THEN** в треде PAY-7 одно сообщение с этим вопросом
+
+### Requirement: Ответ в треде уходит агенту
+Сообщение участника в треде стори SHALL отвечать на открытый вопрос стори, а без открытого
+вопроса — становиться комментарием PM к стори и уходить в живой раннер. Сообщение в треде
+инцидента, релиза или в общем канале SHALL оставаться заметкой. Писать в чат проекта SHALL
+могут только владелец и участники проекта.
+
+#### Scenario: Ответ на вопрос
+- **GIVEN** у PAY-7 открыт вопрос «Какой разделитель?»
+- **WHEN** участник пишет в тред PAY-7 «точка с запятой»
+- **THEN** вопрос отвечен «точка с запятой», ответ ушёл в сессию агента
+- **AND** в треде видно сообщение участника и отметку «Ответ ушёл агенту»
+
+#### Scenario: Комментарий без вопроса
+- **GIVEN** у PAY-7 нет открытых вопросов и раннер не запущен
+- **WHEN** участник пишет в тред PAY-7 «не забудь заголовки»
+- **THEN** у стори появляется комментарий PM «не забудь заголовки», агент увидит его в get_task
+
+#### Scenario: Чужой проект
+- **GIVEN** пользователь «bob» не участник проекта PAY
+- **WHEN** он пытается написать в чат PAY
+- **THEN** запрос отклонён как «не найдено», сообщения в чате нет
+
+### Requirement: Мастер-чат
+У каждого пользователя SHALL быть мастер-чат: важные события всех его проектов (вопросы,
+готово к ревью, сбои и лимиты раннеров, релизы, ошибки из прода), мониторинг и дайджест.
+Мастер-чат SHALL выполнять команды `/help`, `/status`, `/task KEY-N`, `/move KEY-N <колонка>`
+без LLM; писать в мастер-чат SHALL может только его владелец.
+
+#### Scenario: Сбой раннера в мастер-чате
+- **GIVEN** пользователь «anna» владеет проектом PAY
+- **WHEN** раннер PAY-7 зависает
+- **THEN** в мастер-чате «anna» видно сообщение о зависании PAY-7 со ссылкой на тред
+
+#### Scenario: Команда перемещения
+- **GIVEN** стори PAY-8 в бэклоге проекта «anna»
+- **WHEN** «anna» пишет в мастер-чат `/move PAY-8 in_progress`
+- **THEN** стори PAY-8 в работе, агент запущен, в мастер-чате ответ «PAY-8 → В работе»
+
+#### Scenario: Неизвестная команда
+- **WHEN** «anna» пишет в мастер-чат `/deploy всё`
+- **THEN** в ответ — «Не знаю такую команду» и список команд, ничего не выполнено
+
+### Requirement: Связка чата с Telegram-группой
+Чат проекта и мастер-чат SHALL связываться с обычной Telegram-группой по одноразовому коду
+(10 минут). Сообщения связанного чата SHALL дублироваться в группу, тред — цепочкой реплаев
+на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и обрабатываться как
+сообщение из веба; принимать его SHALL только от пользователя Пеппы с привязанным Telegram и
+доступом к проекту (в мастер-группе — от владельца мастер-чата).
+
+#### Scenario: Связать группу
+- **GIVEN** участник открыл чат PAY и нажал «Связать с Telegram»
+- **WHEN** в группе «PAY team» отправлено `/link <код>` до истечения кода
+- **THEN** чат PAY связан с «PAY team», бот подтверждает это в группе, веб показывает название группы
+
+#### Scenario: Просроченный код
+- **GIVEN** код связки выдан 11 минут назад
+- **WHEN** в группе отправлено `/link <код>`
+- **THEN** бот отвечает, что код неверный или истёк, чат не связан
+
+#### Scenario: Ответ реплаем из группы
+- **GIVEN** чат PAY связан с группой, вопрос PAY-7 пришёл в группу
+- **AND** «anna» привязала Telegram и участник PAY
+- **WHEN** «anna» отвечает реплаем на вопрос «точка с запятой»
+- **THEN** вопрос отвечен, в веб-треде PAY-7 видно её сообщение с пометкой Telegram
+
+#### Scenario: Посторонний в группе
+- **GIVEN** в группе PAY есть человек без привязки Telegram в Пеппе
+- **WHEN** он отвечает реплаем на вопрос PAY-7
+- **THEN** вопрос не отвечен, сообщения в чате нет, бот подсказывает привязать Telegram
+
+### Requirement: Короткое хранение переписки
+Сообщения чатов SHALL удаляться через `PEPPA_CHAT_TTL_DAYS` дней (по умолчанию 14); стори,
+вопросы, события, релизы и инциденты при этом SHALL оставаться.
+
+#### Scenario: Старые сообщения удалены
+- **GIVEN** сообщение в треде PAY-7 от 15 дней назад и вопрос PAY-7, к которому оно относится
+- **WHEN** вачдог чистит чаты
+- **THEN** сообщения в чате нет, вопрос PAY-7 остаётся в стори
--
2.45.2
From 82c003e2093d15859e4c6b5e1143277313a5a330 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 19:03:45 +0500
Subject: [PATCH 006/428] =?UTF-8?q?PEP-60:=20platform=20Telegram=20channel?=
=?UTF-8?q?=20=E2=80=94=20check,=20releases,=20outages/restarts,=20platfor?=
=?UTF-8?q?m=20digest?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/bot/src/bot.ts | 1 +
apps/web/app/(app)/platform/actions.ts | 57 +++
apps/web/app/(app)/platform/page.tsx | 114 ++++++
apps/web/app/(app)/settings/page.tsx | 3 +
apps/web/components/Sidebar.tsx | 3 +-
.../pep-60-platform-channel-digest/design.md | 66 ++++
.../pep-60-platform-channel-digest/tasks.md | 16 +-
packages/cli/src/index.ts | 41 ++
packages/core/src/index.ts | 1 +
packages/core/src/monitor.ts | 60 ++-
packages/core/src/notifications.ts | 5 +-
packages/core/src/platform-channel.ts | 371 ++++++++++++++++++
packages/runner/src/index.ts | 1 +
packages/runner/src/platform-build.ts | 57 +++
packages/runner/src/watchdog.ts | 8 +
packages/testkit/src/mock-telegram.ts | 24 ++
.../testkit/test/platform-channel.test.ts | 309 +++++++++++++++
17 files changed, 1123 insertions(+), 14 deletions(-)
create mode 100644 apps/web/app/(app)/platform/actions.ts
create mode 100644 apps/web/app/(app)/platform/page.tsx
create mode 100644 openspec/changes/pep-60-platform-channel-digest/design.md
create mode 100644 packages/core/src/platform-channel.ts
create mode 100644 packages/runner/src/platform-build.ts
create mode 100644 packages/testkit/test/platform-channel.test.ts
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 435ab96a..24d5de2f 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -94,6 +94,7 @@ const PUSH_TITLE: Record = {
incidents: "Ошибка в проде",
monitoring: "Мониторинг",
digest: "Сводка",
+ platform: "Обновления Пеппы",
};
/** Browser notification text for a question. */
diff --git a/apps/web/app/(app)/platform/actions.ts b/apps/web/app/(app)/platform/actions.ts
new file mode 100644
index 00000000..10b40ac9
--- /dev/null
+++ b/apps/web/app/(app)/platform/actions.ts
@@ -0,0 +1,57 @@
+"use server";
+// «Платформа» (PEP-60): the platform's Telegram channel and digest — superadmin only.
+
+import { checkPlatformChannel, parseChatId, PeppaError, platformDigestTick, PLATFORM_CHANNEL_EVENTS, requireSuperadmin, setPlatformChannel } from "@peppa/core";
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { asWebActor, requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+
+const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
+const BASE = "/platform";
+
+async function attempt(fn: () => Promise): Promise {
+ const user = asWebActor(await requireUser());
+ let target = BASE;
+ try {
+ await requireSuperadmin(db, user);
+ target = (await fn()) || target;
+ } catch (e) {
+ const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
+ target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
+ }
+ revalidatePath(BASE);
+ redirect(target);
+}
+
+/** Saves the Chat ID (and checks the channel right away). */
+export async function saveChannelAction(f: FormData) {
+ await attempt(async () => {
+ const raw = str(f, "chatId");
+ const c = await setPlatformChannel(db, { chatId: raw ? parseChatId(raw) : null });
+ if (c.chatId != null) await checkPlatformChannel(db);
+ });
+}
+
+export async function checkChannelAction() {
+ await attempt(async () => {
+ await checkPlatformChannel(db);
+ });
+}
+
+export async function saveChannelSettingsAction(f: FormData) {
+ await attempt(async () => {
+ const events = Object.fromEntries(PLATFORM_CHANNEL_EVENTS.map((e) => [e, f.get(`event.${e}`) === "on"]));
+ await setPlatformChannel(db, { events, digest: { time: str(f, "time"), timezone: str(f, "timezone"), users: f.get("users") === "on" } });
+ });
+}
+
+/** Sends the platform digest now (over the time since the previous one). */
+export async function sendDigestNowAction() {
+ await attempt(async () => {
+ const r = await platformDigestTick(db, { force: true });
+ if (!r) throw new PeppaError("Некуда отправлять: канал не подключён и дайджест пользователям выключен");
+ if (!r.channel && !r.users) return `${BASE}?sent=empty`;
+ return `${BASE}?sent=${r.channel ? "channel" : ""}${r.users ? `,users:${r.users}` : ""}`;
+ });
+}
diff --git a/apps/web/app/(app)/platform/page.tsx b/apps/web/app/(app)/platform/page.tsx
new file mode 100644
index 00000000..8865e0cf
--- /dev/null
+++ b/apps/web/app/(app)/platform/page.tsx
@@ -0,0 +1,114 @@
+import { notFound } from "next/navigation";
+import { Megaphone, RefreshCw, Send } from "lucide-react";
+import { buildPlatformDigest, getPlatformBuild, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
+import { ago, Flash, PageHeader, Section } from "@/components/common";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input, Label } from "@/components/ui/input";
+import { Workspace } from "@/components/Workspace";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions";
+
+export const metadata = { title: "Платформа — Пеппа" };
+
+/** Telegram HTML of the digest → plain text for the preview. */
+const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
+
+export default async function Platform({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
+ const user = await requireUser();
+ if (!(await isSuperadmin(db, user))) notFound();
+ const { error, sent } = await searchParams;
+ const [c, build] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db)]);
+ const digest = await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) });
+ return (
+
+
+
+ {sent &&
{sent === "empty" ? "Дайджест пуст — нечего отправлять." : `Дайджест отправлен: ${sent.replace("channel", "в канал").replace(",users:", " · пользователям: ")}`}
}
+
Платформа>}>
+ Telegram-канал Пеппы: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Пеппе и что происходит сейчас. Раздел видят только суперадмины.
+ {build && <> Сейчас: v{build.version} · {build.commit.slice(0, 7)} .>}
+
+
+
+
+
+ {c.chatId == null ? (
+ канал не задан
+ ) : !c.check ? (
+ не проверен
+ ) : c.check.ok ? (
+ канал подключён
+ ) : (
+ не работает
+ )}
+ {c.check?.ok && c.title && {c.title} }
+ {c.check && проверен {ago(new Date(c.check.at))} }
+
+ {c.check && !c.check.ok && {c.check.error}
}
+
+
+ Chat ID канала
+
+
+ Сохранить и проверить
+
+ {c.chatId != null && (
+
+ Проверить ещё раз
+
+ )}
+
+ Добавьте бота Пеппы в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Пеппа перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.
+
+
+
+
+
+
+
+ Отправить сейчас
+
+ }
+ >
+ {platformDigestEmpty(digest) ? (
+ За сутки ничего нового и ничего не происходит — дайджест не уйдёт.
+ ) : (
+ {plain(renderPlatformDigest(digest))}
+ )}
+
+
+
+ );
+}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 06389f30..b64fb563 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -82,6 +82,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
Журнал
+
+ Платформа
+
>
}
>
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 0cd5a95d..aade574d 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, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
+import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@@ -28,6 +28,7 @@ const ITEMS: Item[] = [
{ 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") },
];
diff --git a/openspec/changes/pep-60-platform-channel-digest/design.md b/openspec/changes/pep-60-platform-channel-digest/design.md
new file mode 100644
index 00000000..bb1a4d4c
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/design.md
@@ -0,0 +1,66 @@
+# Design: PEP-60 — канал платформы и дайджест Пеппы
+
+## Настройки (без миграций)
+
+`settings` `platform.telegram_channel` (ключ уже есть в боевой базе: `{chatId, setAt}`) —
+`PlatformChannel` в `core/platform-channel.ts`, поверх умолчаний:
+
+- `chatId`, `title`, `check: {ok, error, at}` — результат последней проверки;
+- `events: {releases, services, digest}` — всё включено;
+- `digest: {time "09:00", timezone (PEPPA_TZ/сервер), users: false}` — личные чаты включает
+ суперадмин (без сюрприза всем пользователям в первый же день).
+
+Менять может только суперадмин (`requireSuperadmin`): веб `/platform` и CLI
+`peppa platform channel chat= [releases=on|off …]` (отрицательный id — через `chat=`:
+`parseArgs` принимает `-100…` за флаг), `peppa platform channel check`, `peppa platform digest [now]`.
+
+## Проверка канала
+
+`checkPlatformChannel` — Bot API напрямую (как прямая доставка вачдога PEP-20):
+`getMe` → `getChat(chat_id)` → `getChatMember(chat_id, bot)`. `chat not found` / 403 →
+«бот не видит канал — добавьте его администратором»; не админ или `can_post_messages: false`
+(в канале) → «бот не может публиковать — дайте право «Публикация сообщений»». Удача —
+`title` канала. Проверка при сохранении, кнопкой и раз в час в вачдоге, пока не ок (PM
+добавит бота — канал заработает сам). Писать в канал только при `check.ok`.
+
+## Отправка
+
+`postToChannel(db, kind, dedupeKey, text)` → тот же `telegram_outbox` (повторы, 429). Ключи
+сервисных событий начинаются с `mon:` — их вачдог доставляет сам, когда упал бот. Канал не
+принимает ответов: кнопок нет, бот на сообщения канала не реагирует (updates `channel_post`
+он и так не обрабатывает).
+
+## События
+
+- **Сервисы** — в `checkServices` (PEP-20) рядом с алертом админам: одно сообщение о
+ падении (без напоминаний) и одно о восстановлении с длительностью простоя; ключи от
+ начала простоя, поэтому бот и вачдог вместе дают одно сообщение. **Перезапуск** — смена
+ `heartbeat.startedAt` без простоя: «🔄 вачдог перезапущен (v0.15.0 · abc1234)».
+- **Релиз**. В heartbeat добавлен `commit` (`peppaCommit()`: `PEPPA_COMMIT` /
+ `NEXT_PUBLIC_PEPPA_COMMIT_FULL` / `git rev-parse HEAD` корня). Вачдог раз в минуту
+ (`platformBuildTick`, runner) берёт HEAD корня Пеппы; если он отличается от
+ `platform.build` и входит в `main` (`git merge-base --is-ancestor HEAD main`) — это выкатка:
+ «🚀 Peppa v0.16.0 · b1c2d3e» и стори из сообщений коммитов `prev..HEAD`
+ (`PEP-N`, с названиями). Так работает и сейчас (dev из рабочей копии: ветка задачи не
+ объявляется, возврат на обновлённый main — объявляется), и в проде PEP-18 (`current` —
+ worktree релиза от `main`). Первый запуск только запоминает сборку.
+
+## Дайджест платформы
+
+`buildPlatformDigest(since, now)`: «Что нового» — стори проекта Пеппы (`PEPPA_PLATFORM_KEY`),
+ставшие `done` после `since`, и сборки, объявленные с тех пор; «Сейчас» — версия · коммит,
+сервисы, активные раннеры, открытые вопросы, лимиты подписок (`listAccountUsage`, ≥ 50% или
+«лимит до»). Пусто (нет нового, нет раннеров, нет вопросов, сервисы в порядке) — не
+отправляется. `platformDigestTick` в `tick` вачдога: в `digest.time` (окно 3 ч, раз в
+местные сутки, `platform.digest.last`), в канал и — если `digest.users` — каждому
+пользователю событием уведомлений `platform` («Обновления Пеппы»: Telegram вкл, push выкл).
+Отписка — «Настройки → Уведомления» (строка появляется сама из `NOTIFY_EVENTS`); личный
+дайджест по проектам (PEP-29, событие `digest`) не меняется.
+
+## Решения
+
+- Без миграций — всё в `settings`, как прочие настройки платформы.
+- Отдельная страница `/platform` для суперадмина (по образцу `/hosts`), пункт меню
+ «Платформа»; не суперадмину — 404.
+- Окно сервиса «упал» — общий порог мониторинга (`PEPPA_MONITOR_STALE_MIN`), отдельный
+ порог для канала не вводим.
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/pep-60-platform-channel-digest/tasks.md
index d84d35c4..7276743f 100644
--- a/openspec/changes/pep-60-platform-channel-digest/tasks.md
+++ b/openspec/changes/pep-60-platform-channel-digest/tasks.md
@@ -1,16 +1,18 @@
# Tasks: PEP-60
## 0. Перед стартом
-- [x] 0.1 Бот — админ канала (проверка `getChat`/тестовое сообщение по согласию PM); роль суперадмина из PEP-16 (иначе только CLI)
+- [x] 0.1 Проверка бота в канале: `getChat(-1004371018094)` → «chat not found» — бот ещё не админ; работаем, канал включится сам после проверки
## 1. Канал
-- [x] 1.1 core: настройки платформы (канал, события, расписание); CLI `peppa platform channel ` и `platform status`
-- [x] 1.2 Веб: «Настройки платформы» для суперадмина с проверкой канала
-- [x] 1.3 События: релиз (из деплоя/CI, PEP-57; до него — при старте веба с новым коммитом), рестарт и падение/восстановление сервисов (heartbeat, PEP-20)
+- [x] 1.1 core `platform-channel.ts`: настройки, проверка канала (Bot API), `postToChannel`; CLI `peppa platform channel`
+- [x] 1.2 Веб `/platform` для суперадмина: Chat ID, проверка, события, расписание; пункт меню
+- [x] 1.3 События сервисов в `checkServices`: падение/восстановление/перезапуск; `commit` в heartbeat
+- [x] 1.4 Релиз: `platformBuildTick` (runner) — новая сборка из `main` со списком стори
## 2. Дайджест
-- [x] 2.1 Сбор: смерженные PR/задачи PEP с прошлого дайджеста, версия, сервисы, раннеры, вопросы, лимиты; пропуск, если пусто
-- [x] 2.2 Расписание и отправка в канал; личный дайджест пользователям (после PEP-2) и отписка в Настройках
+- [x] 2.1 `buildPlatformDigest` + рендер; пропуск, если пусто
+- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
## 3. Проверка
-- [x] 3.1 Тесты на mock-telegram — по сценарию спецификации на каждый; весь e2e зелёный; `openspec validate`
+- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
+- [ ] 3.2 Документация: AGENTS.md, `/help`
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 7d3977cf..3b687e59 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -71,6 +71,7 @@ import {
import { createDb, migrateDb } from "@peppa/db";
import { checkHost, ensureSshKey, pushImage, sshArgs } 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 { 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";
@@ -121,6 +122,9 @@ const USAGE = `peppa — Peppa software factory CLI
(PEP-10/27: system → project → story; a story overrides mode/context only)
peppa platform allowlist | allow | deny (who may log into Peppa)
peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch)
+ peppa platform channel [chat=|@name|check] [releases|services|digest=on|off time=HH:MM tz= users=on|off]
+ (PEP-60: Telegram channel of the platform — events and the platform digest)
+ peppa platform digest [now] (PEP-60: show the platform digest; now — send it to the channel/users)
peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist)
peppa platform watchdog [key=value… | key=- | reset] (PEP-28: restartMax restartWindowMin restartDelaysMin=1,5,15
stallRestartMin remindMin escalateMin idleStopHours; 0 = off)
@@ -641,6 +645,7 @@ async function main(): Promise {
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(", ") || "нет"}`);
+ console.log(`канал платформы: ${describeChannel(await getPlatformChannel(db))}`);
break;
}
case "telegram pair": {
@@ -674,6 +679,42 @@ async function main(): Promise {
console.log(`${u.login} (#${u.id})`);
break;
}
+ case "platform channel": {
+ // PEP-60: the platform's Telegram channel (superadmin's setting; the CLI is an admin tool).
+ const patch: PlatformChannelPatch = {};
+ let check = false;
+ for (const a of args) {
+ if (a === "check") check = true;
+ else if (a === "-") patch.chatId = null;
+ else if (!a.includes("=")) patch.chatId = parseChatId(a);
+ else {
+ const [k, v] = [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)];
+ const on = v === "on" ? true : v === "off" ? false : null;
+ if (k === "chat") patch.chatId = v === "-" ? null : parseChatId(v);
+ else if ((PLATFORM_CHANNEL_EVENTS as readonly string[]).includes(k) && on != null) patch.events = { ...patch.events, [k]: on };
+ else if (k === "users" && on != null) patch.digest = { ...patch.digest, users: on };
+ else if (k === "time") patch.digest = { ...patch.digest, time: v };
+ else if (k === "tz") patch.digest = { ...patch.digest, timezone: v };
+ else throw new PeppaError(`unknown setting ${a}: chat=, releases|services|digest|users=on|off, time=HH:MM, tz=`);
+ }
+ }
+ let c = Object.keys(patch).length ? await setPlatformChannel(db, patch) : await getPlatformChannel(db);
+ if (c.chatId != null && (check || patch.chatId !== undefined)) c = await checkPlatformChannel(db);
+ console.log(describeChannel(c));
+ console.log(`события: ${PLATFORM_CHANNEL_EVENTS.map((e) => `${e}=${c.events[e] ? "on" : "off"}`).join(" ")}`);
+ console.log(`дайджест: ${c.digest.time} ${c.digest.timezone}, пользователям ${c.digest.users ? "да" : "нет"}`);
+ break;
+ }
+ case "platform digest": {
+ if (args[0] === "now") {
+ const r = await platformDigestTick(db, { force: true, log: console.log });
+ if (!r) console.log("некуда отправлять: канал не подключён и дайджест пользователям выключен");
+ break;
+ }
+ const { buildPlatformDigest, renderPlatformDigest } = await import("@peppa/core");
+ console.log(renderPlatformDigest(await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) })).replace(/<[^>]+>/g, ""));
+ break;
+ }
case "platform release-offers": {
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f06b1ada..a7c6cda7 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -28,6 +28,7 @@ export * from "./reviews.ts";
export * from "./webpush.ts";
export * from "./notifications.ts";
export * from "./digest.ts";
+export * from "./platform-channel.ts";
export * from "./autonomy.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts
index 1f67aeb3..64f27ad3 100644
--- a/packages/core/src/monitor.ts
+++ b/packages/core/src/monitor.ts
@@ -1,6 +1,7 @@
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
// watchdog and the bot check each other (and the web) and alert the platform admins in
// Telegram through the outbox when a service goes quiet, without spamming.
+import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { hostname } from "node:os";
import { dirname, join } from "node:path";
@@ -9,6 +10,7 @@ import { telegramOutbox, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm";
import { allowedLogins } from "./access.ts";
import { deliverToUser } from "./notifications.ts";
+import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import type { User } from "./users.ts";
@@ -23,6 +25,8 @@ export interface Heartbeat {
pid: number;
host: string;
version: string;
+ /** Commit the process runs (PEP-60); absent in heartbeats of older processes. */
+ commit?: string | null;
}
export interface ServiceState {
@@ -38,6 +42,8 @@ interface AlertState {
alerted: boolean;
reminders: number;
lastAlertAt: string | null;
+ /** PEP-60: the outage was posted to the platform channel (then its recovery is too). */
+ channelPosted?: boolean;
}
export interface MonitorOptions {
@@ -60,14 +66,33 @@ const startedAt = new Date().toISOString();
export const defaultStaleMs = () => Number(process.env.PEPPA_MONITOR_STALE_MIN ?? 5) * MIN;
/** Peppa version from the root package.json (bot, watchdog, CLI run from the checkout). */
-export function peppaVersion(): string {
+export function peppaVersion(root = join(dirname(fileURLToPath(import.meta.url)), "../../..")): string {
try {
- return (JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../../package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
+ return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
} catch {
return "0.0.0";
}
}
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+
+/** HEAD of Peppa's checkout right now (null outside git). */
+export function headCommit(root = ROOT): string | null {
+ try {
+ return execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+let processCommit: string | null | undefined;
+
+/** Commit this process runs: PEPPA_COMMIT, the web's build-time commit, or HEAD at first call. */
+export function peppaCommit(): string | null {
+ if (processCommit === undefined) processCommit = process.env.PEPPA_COMMIT || process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL || headCommit();
+ return processCommit;
+}
+
/** "I'm alive": called every 30–60 s by each service. */
export async function beat(db: Db, service: Service, o: { now?: Date; version?: string } = {}): Promise {
const hb: Heartbeat = {
@@ -76,6 +101,7 @@ export async function beat(db: Db, service: Service, o: { now?: Date; version?:
pid: process.pid,
host: hostname(),
version: o.version ?? peppaVersion(),
+ commit: peppaCommit(),
};
await setSetting(db, hbKey(service), hb);
}
@@ -162,23 +188,39 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
const cooldownMs = o.cooldownMs ?? 15 * MIN;
const log = o.log ?? (() => {});
let queued = 0;
+ const channel = await getPlatformChannel(db);
for (const s of await serviceStatus(db, { now, staleMs: o.staleMs })) {
if (s.service === o.self || !s.heartbeat) continue;
const name = SERVICE_NAMES[s.service];
const st = await getSetting(db, alertKey(s.service));
if (s.ok) {
- if (!st?.since) continue;
+ const restarted = await noteProcess(db, s.service, s.heartbeat);
+ if (!st?.since) {
+ // PEP-60: a new process without an outage = a restart (an outage ends with «снова на связи»).
+ if (restarted) {
+ const build = `v${s.heartbeat.version}${s.heartbeat.commit ? ` · ${s.heartbeat.commit.slice(0, 7)}` : ""}`;
+ await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, `🔄 Пеппа: ${name} перезапущен (${build}).`, channel);
+ }
+ continue;
+ }
// lastAlertAt survives the recovery: it is what the cooldown against flapping counts from.
await setSetting(db, alertKey(s.service), { since: null, alerted: false, reminders: 0, lastAlertAt: st.lastAlertAt });
+ const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
if (st.alerted) {
- const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова на связи (молчал ${quiet} мин).`, log);
}
+ if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова работает — простой ${quiet} мин.`, channel))) queued++;
continue;
}
// Down. A new outage starts when the last heartbeat differs from the remembered one.
const cur: AlertState =
st?.since === s.heartbeat.at ? st : { since: s.heartbeat.at, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null };
+ // PEP-60: the channel hears about an outage once (no reminders, no cooldown games).
+ if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, `⚠️ Пеппа: ${name} не отвечает с ${hhmm(s.heartbeat.at)}.`, channel))) {
+ cur.channelPosted = true;
+ queued++;
+ if (cur === st) await setSetting(db, alertKey(s.service), cur);
+ }
const sinceLast = cur.lastAlertAt ? now.getTime() - Date.parse(cur.lastAlertAt) : Infinity;
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
if (due) {
@@ -192,6 +234,16 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
return queued;
}
+/** Remembers the service's process; true when it differs from a previously seen one. */
+async function noteProcess(db: Db, service: Service, hb: Heartbeat): Promise {
+ const key = `monitor.process:${service}`;
+ const id = `${hb.host}:${hb.pid}:${hb.startedAt}`;
+ const prev = await getSetting(db, key);
+ if (prev === id) return false;
+ await setSetting(db, key, id);
+ return prev != null;
+}
+
/** Monitor messages not delivered yet (the watchdog sends them itself when the bot is down). */
export async function pendingMonitorMessages(db: Db) {
return db
diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts
index 9774da6a..7812860a 100644
--- a/packages/core/src/notifications.ts
+++ b/packages/core/src/notifications.ts
@@ -8,7 +8,7 @@ import type { Question } from "./tasks.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
-export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
+export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest", "platform"] as const;
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
export const NOTIFY_EVENT_NAMES: Record = {
@@ -19,6 +19,7 @@ export const NOTIFY_EVENT_NAMES: Record = {
incidents: "Ошибки из прода",
monitoring: "Мониторинг Пеппы (админам)",
digest: "Ежедневный дайджест",
+ platform: "Дайджест обновлений Пеппы",
};
export interface Channels {
@@ -47,7 +48,7 @@ export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat(
export function defaultPrefs(): NotifyPrefs {
const on = { telegram: true, push: true };
return {
- events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false } },
+ events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } },
quiet: null,
timezone: serverTimezone(),
digestTime: "09:00",
diff --git a/packages/core/src/platform-channel.ts b/packages/core/src/platform-channel.ts
new file mode 100644
index 00000000..4624305a
--- /dev/null
+++ b/packages/core/src/platform-channel.ts
@@ -0,0 +1,371 @@
+// Platform channel and Peppa's own digest (PEP-60): a Telegram channel set by a superadmin
+// gets platform events (releases, service outages, restarts) and the daily platform digest;
+// paired users get the platform digest too (notification event «platform»). No migrations:
+// everything lives in `settings`; messages go through the Telegram outbox with retries.
+import { projects, questions, sessions, tasks, users, type Db } from "@peppa/db";
+import { formatTaskKey, loadEnv } from "@peppa/shared";
+import { and, asc, eq, gte, isNotNull, isNull, notInArray } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+import { deliverToUser, hhmmToMinutes, isValidTimezone, localClock, serverTimezone } from "./notifications.ts";
+import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
+import { getSetting, setSetting } from "./settings.ts";
+import { enqueueTelegram } from "./telegram.ts";
+import { describeAccount, listAccountUsage } from "./usage.ts";
+
+export const PLATFORM_CHANNEL_EVENTS = ["releases", "services", "digest"] as const;
+export type PlatformChannelEvent = (typeof PLATFORM_CHANNEL_EVENTS)[number];
+
+export const PLATFORM_CHANNEL_EVENT_NAMES: Record = {
+ releases: "Новые версии Пеппы",
+ services: "Падение, восстановление и перезапуск сервисов",
+ digest: "Ежедневный дайджест",
+};
+
+export interface ChannelCheck {
+ ok: boolean;
+ /** Human-readable reason when not ok. */
+ error: string | null;
+ at: string;
+}
+
+export interface PlatformChannel {
+ /** Telegram Chat ID of the channel («-100…» or «@name»); null = no channel. */
+ chatId: number | string | null;
+ /** Channel title from the last good check. */
+ title: string | null;
+ check: ChannelCheck | null;
+ events: Record;
+ digest: { time: string; timezone: string; users: boolean };
+ setAt?: string;
+}
+
+const KEY = "platform.telegram_channel";
+const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
+
+export function defaultPlatformChannel(): PlatformChannel {
+ return {
+ chatId: null,
+ title: null,
+ check: null,
+ events: { releases: true, services: true, digest: true },
+ digest: { time: "09:00", timezone: serverTimezone(), users: false },
+ };
+}
+
+/** Saved channel settings merged over the defaults. */
+export async function getPlatformChannel(db: Db): Promise {
+ const d = defaultPlatformChannel();
+ const s = (await getSetting>(db, KEY)) ?? {};
+ const events = { ...d.events };
+ for (const e of PLATFORM_CHANNEL_EVENTS) if (typeof s.events?.[e] === "boolean") events[e] = s.events[e];
+ return {
+ chatId: s.chatId ?? null,
+ title: s.title ?? null,
+ check: s.check ?? null,
+ events,
+ digest: {
+ time: s.digest?.time && HHMM.test(s.digest.time) ? s.digest.time : d.digest.time,
+ timezone: s.digest?.timezone && isValidTimezone(s.digest.timezone) ? s.digest.timezone : d.digest.timezone,
+ users: s.digest?.users ?? d.digest.users,
+ },
+ ...(s.setAt ? { setAt: s.setAt } : {}),
+ };
+}
+
+/** «-1004371018094» → number, «@name» stays a string; anything else is refused. */
+export function parseChatId(raw: string): number | string {
+ const s = raw.trim();
+ if (/^-?\d{5,20}$/.test(s)) return Number(s);
+ if (/^@[A-Za-z][A-Za-z0-9_]{3,}$/.test(s)) return s;
+ throw new PeppaError("Chat ID канала — число вида -100… или @имя_канала");
+}
+
+export interface PlatformChannelPatch {
+ chatId?: number | string | null;
+ events?: Partial>;
+ digest?: Partial;
+}
+
+/** Changes the settings; a new Chat ID drops the previous check result. */
+export async function setPlatformChannel(db: Db, patch: PlatformChannelPatch): Promise {
+ const cur = await getPlatformChannel(db);
+ const next: PlatformChannel = { ...cur, events: { ...cur.events, ...patch.events }, digest: { ...cur.digest, ...patch.digest } };
+ if (!HHMM.test(next.digest.time)) throw new PeppaError("Время дайджеста: формат ЧЧ:ММ");
+ if (!isValidTimezone(next.digest.timezone)) throw new PeppaError(`Неизвестная таймзона: ${next.digest.timezone}`);
+ if (patch.chatId !== undefined && String(patch.chatId) !== String(cur.chatId)) {
+ Object.assign(next, { chatId: patch.chatId, title: null, check: null, setAt: new Date().toISOString() });
+ }
+ await setSetting(db, KEY, next);
+ return next;
+}
+
+// ── check ──────────────────────────────────────────────────────────────────────────
+
+export interface BotApiAccess {
+ token?: string;
+ apiUrl?: string;
+}
+
+export const CHANNEL_NOT_VISIBLE = "бот не видит канал — добавьте его администратором";
+export const CHANNEL_NO_POST = "бот не может публиковать — дайте ему право «Публикация сообщений»";
+
+type ApiResult = { ok: true; result: T } | { ok: false; error_code?: number; description?: string };
+
+async function botApi(tg: BotApiAccess, method: string, params: Record): Promise> {
+ const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;
+ if (!token) return { ok: false, description: "TELEGRAM_BOT_TOKEN не задан" };
+ const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org";
+ try {
+ const res = await fetch(`${base}/bot${token}/${method}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(params),
+ signal: AbortSignal.timeout(15_000),
+ });
+ return (await res.json()) as ApiResult;
+ } catch (e) {
+ return { ok: false, description: (e as Error).message };
+ }
+}
+
+/**
+ * Whether the bot can post to the channel: getMe → getChat → getChatMember. Saves the result
+ * (and the channel title) into the settings and returns them.
+ */
+export async function checkPlatformChannel(db: Db, tg: BotApiAccess = {}, o: { now?: Date } = {}): Promise {
+ const cur = await getPlatformChannel(db);
+ if (cur.chatId == null) throw new PeppaError("Канал платформы не задан");
+ const at = (o.now ?? new Date()).toISOString();
+ const verdict = async (): Promise<{ ok: boolean; error: string | null; title: string | null }> => {
+ const me = await botApi<{ id: number }>(tg, "getMe", {});
+ if (!me.ok) return { ok: false, error: `Telegram: ${me.description ?? "нет ответа"}`, title: null };
+ const chat = await botApi<{ title?: string; type: string }>(tg, "getChat", { chat_id: cur.chatId });
+ if (!chat.ok) {
+ const gone = chat.error_code === 400 || chat.error_code === 403 || /chat not found|not a member|kicked/i.test(chat.description ?? "");
+ return { ok: false, error: gone ? CHANNEL_NOT_VISIBLE : `Telegram: ${chat.description ?? "нет ответа"}`, title: null };
+ }
+ const title = chat.result.title ?? null;
+ const member = await botApi<{ status: string; can_post_messages?: boolean }>(tg, "getChatMember", { chat_id: cur.chatId, user_id: me.result.id });
+ if (!member.ok) return { ok: false, error: `Telegram: ${member.description ?? "нет ответа"}`, title };
+ const m = member.result;
+ const canPost = chat.result.type === "channel" ? m.status === "creator" || (m.status === "administrator" && m.can_post_messages !== false) : m.status !== "left" && m.status !== "kicked";
+ return canPost ? { ok: true, error: null, title } : { ok: false, error: m.status === "left" || m.status === "kicked" ? CHANNEL_NOT_VISIBLE : CHANNEL_NO_POST, title };
+ };
+ const v = await verdict();
+ const next: PlatformChannel = { ...cur, title: v.title ?? cur.title, check: { ok: v.ok, error: v.error, at } };
+ await setSetting(db, KEY, next);
+ return next;
+}
+
+/** «канал подключён — Peppa News» / the reason / «не проверен». */
+export function describeChannel(c: PlatformChannel): string {
+ if (c.chatId == null) return "канал не задан";
+ if (!c.check) return `${c.chatId}: не проверен`;
+ return c.check.ok ? `канал подключён${c.title ? ` — ${c.title}` : ""}` : `${c.chatId}: ${c.check.error}`;
+}
+
+/** Watchdog: re-checks a channel that isn't working yet at most once an hour. */
+export async function recheckPlatformChannel(db: Db, o: { now?: Date; tg?: BotApiAccess; log?: (m: string) => void } = {}): Promise {
+ const c = await getPlatformChannel(db);
+ const now = o.now ?? new Date();
+ if (c.chatId == null || c.check?.ok) return false;
+ if (c.check && now.getTime() - Date.parse(c.check.at) < 3600_000) return false;
+ const r = await checkPlatformChannel(db, o.tg, { now });
+ if (r.check?.ok) o.log?.(`platform channel: ${describeChannel(r)}`);
+ return true;
+}
+
+// ── posting ────────────────────────────────────────────────────────────────────────
+
+const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">");
+
+/**
+ * Queues a message to the platform channel if it is connected and the event is on. Service
+ * events use `mon:` keys so the watchdog delivers them itself when the bot is down.
+ */
+export async function postToChannel(db: Db, event: PlatformChannelEvent, dedupeKey: string, html: string, channel?: PlatformChannel): Promise {
+ const c = channel ?? (await getPlatformChannel(db));
+ if (c.chatId == null || !c.check?.ok || !c.events[event]) return false;
+ return enqueueTelegram(db, {
+ dedupeKey,
+ method: "sendMessage",
+ params: { chat_id: c.chatId, text: html, parse_mode: "HTML", link_preview_options: { is_disabled: true } },
+ });
+}
+
+// ── builds and releases ────────────────────────────────────────────────────────────
+
+/** Key of the project that is Peppa itself. */
+export const platformProjectKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP";
+
+export interface PlatformBuild {
+ version: string;
+ commit: string;
+ at: string;
+ /** Platform stories found in the commits since the previous build. */
+ tasks: string[];
+}
+
+const BUILD = "platform.build";
+const BUILDS = "platform.builds";
+
+export const getPlatformBuild = (db: Db) => getSetting(db, BUILD);
+
+/** Announced builds, newest last (the digest lists the ones since its previous run). */
+export async function recentPlatformBuilds(db: Db): Promise {
+ return (await getSetting(db, BUILDS)) ?? [];
+}
+
+const short = (sha: string) => sha.slice(0, 7);
+
+/** Titles of the platform's stories by key (missing ones are left out). */
+async function storyTitles(db: Db, keys: string[]): Promise> {
+ const pk = platformProjectKey();
+ const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk));
+ const out = new Map();
+ if (!p || !keys.length) return out;
+ const rows = await db.select({ number: tasks.number, title: tasks.title }).from(tasks).where(eq(tasks.projectId, p.id));
+ for (const r of rows) out.set(formatTaskKey(pk, r.number), r.title);
+ return out;
+}
+
+function storyLine(webUrl: string, key: string, title: string | undefined): string {
+ return ` • ${esc(key)} ${title ? ` ${esc(title.length > 70 ? `${title.slice(0, 70)}…` : title)}` : ""}`;
+}
+
+/**
+ * A new build of Peppa is live (watchdog, runner/platform-build.ts). The first one is only
+ * remembered; later ones are posted to the channel: «🚀 Peppa v0.16.0 · b1c2d3e» + stories.
+ */
+export async function announcePlatformBuild(db: Db, b: Omit, o: { now?: Date } = {}): Promise {
+ const prev = await getPlatformBuild(db);
+ if (prev?.commit === b.commit) return false;
+ const build: PlatformBuild = { ...b, at: (o.now ?? new Date()).toISOString() };
+ await setSetting(db, BUILD, build);
+ if (!prev) return false;
+ await setSetting(db, BUILDS, [...(await recentPlatformBuilds(db)), build].slice(-20));
+ return postToChannel(db, "releases", `pch:release:${b.commit}`, renderBuild(build, await storyTitles(db, build.tasks)));
+}
+
+export function renderBuild(b: PlatformBuild, titles: Map = new Map()): string {
+ const webUrl = loadEnv().PEPPA_WEB_URL;
+ const lines = [`🚀 Peppa v${esc(b.version)} · ${esc(short(b.commit))} `];
+ if (b.tasks.length) lines.push(`Стори: ${b.tasks.map(esc).join(", ")}`, ...b.tasks.slice(0, 15).map((k) => storyLine(webUrl, k, titles.get(k))));
+ return lines.join("\n");
+}
+
+// ── platform digest ────────────────────────────────────────────────────────────────
+
+export interface PlatformDigest {
+ since: Date;
+ build: PlatformBuild | null;
+ /** Builds announced since the previous digest. */
+ builds: PlatformBuild[];
+ /** Platform stories finished since the previous digest. */
+ done: { key: string; title: string }[];
+ services: { name: string; ok: boolean; state: string }[];
+ runners: number;
+ questions: number;
+ rateLimited: number;
+ limits: string[];
+}
+
+/** Changes of Peppa since `since` and the current state of the platform. */
+export async function buildPlatformDigest(db: Db, o: { since: Date; now?: Date }): Promise {
+ const now = o.now ?? new Date();
+ const { serviceStatus, describeState, SERVICE_NAMES } = await import("./monitor.ts");
+ const pk = platformProjectKey();
+ const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk));
+ const done = p
+ ? (
+ await db
+ .select({ number: tasks.number, title: tasks.title })
+ .from(tasks)
+ .where(and(eq(tasks.projectId, p.id), eq(tasks.status, "done"), gte(tasks.updatedAt, o.since)))
+ .orderBy(asc(tasks.number))
+ ).map((t) => ({ key: formatTaskKey(pk, t.number), title: t.title }))
+ : [];
+ const live = await db.select({ status: sessions.status }).from(sessions).where(notInArray(sessions.status, FINISHED_SESSION_STATUSES));
+ const open = await db.select({ id: questions.id }).from(questions).where(isNull(questions.answeredAt));
+ const services = (await serviceStatus(db, { now })).filter((s) => s.heartbeat).map((s) => ({ name: SERVICE_NAMES[s.service], ok: s.ok, state: describeState(s) }));
+ const limits = (await listAccountUsage(db, { now: now.getTime() }))
+ .filter((a) => a.limitedUntil || (a.fiveHour?.pct ?? 0) >= 50 || (a.sevenDay?.pct ?? 0) >= 50)
+ .map(describeAccount);
+ return {
+ since: o.since,
+ build: await getPlatformBuild(db),
+ builds: (await recentPlatformBuilds(db)).filter((b) => Date.parse(b.at) >= o.since.getTime()),
+ done,
+ services,
+ runners: live.length,
+ questions: open.length,
+ rateLimited: live.filter((s) => s.status === "rate_limited").length,
+ limits,
+ };
+}
+
+/** Nothing new and nothing going on: the digest isn't sent. */
+export const platformDigestEmpty = (d: PlatformDigest) => !d.done.length && !d.builds.length && !d.runners && !d.questions && d.services.every((s) => s.ok);
+
+export function renderPlatformDigest(d: PlatformDigest): string {
+ const webUrl = loadEnv().PEPPA_WEB_URL;
+ const lines = ["🐷 Дайджест Пеппы "];
+ if (d.done.length || d.builds.length) {
+ lines.push("", "Что нового ");
+ for (const b of d.builds) lines.push(`🚀 v${esc(b.version)} · ${esc(short(b.commit))}`);
+ if (d.done.length) lines.push(`✅ Сделано: ${d.done.map((t) => esc(t.key)).join(", ")}`, ...d.done.slice(0, 12).map((t) => storyLine(webUrl, t.key, t.title)));
+ if (d.done.length > 12) lines.push(` …и ещё ${d.done.length - 12}`);
+ }
+ lines.push("", "Сейчас ");
+ if (d.build) lines.push(`Версия: v${esc(d.build.version)} · ${esc(short(d.build.commit))}`);
+ if (d.services.length) lines.push(`Сервисы: ${d.services.map((s) => `${s.ok ? "✅" : "⚠️"} ${esc(s.name)}${s.ok ? "" : ` (${esc(s.state)})`}`).join(", ")}`);
+ lines.push(`Раннеров: ${d.runners}${d.rateLimited ? ` (ждут сброса лимита: ${d.rateLimited})` : ""}`, `Вопросов: ${d.questions}`);
+ if (d.limits.length) lines.push(`Лимиты: ${d.limits.map(esc).join("; ")}`);
+ return lines.join("\n");
+}
+
+const LAST = "platform.digest.last";
+const WINDOW_MIN = 180;
+
+/**
+ * Watchdog tick: at the platform's digest time (once a local day) builds the digest over the
+ * time since the previous one and sends it to the channel and, when enabled, to every paired
+ * user who keeps the «platform» notification on. Returns where it went.
+ */
+export async function platformDigestTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise<{ channel: boolean; users: number } | null> {
+ const now = o.now ?? new Date();
+ const c = await getPlatformChannel(db);
+ const clock = localClock(now, c.digest.timezone);
+ const target = hhmmToMinutes(c.digest.time);
+ const last = await getSetting<{ date: string; at: string }>(db, LAST);
+ if (!o.force) {
+ if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) return null;
+ if (last?.date === clock.date) return null;
+ }
+ const toChannel = c.chatId != null && !!c.check?.ok && c.events.digest;
+ if (!toChannel && !c.digest.users) return null;
+ await setSetting(db, LAST, { date: clock.date, at: now.toISOString() });
+ const since = last ? new Date(last.at) : new Date(now.getTime() - 24 * 3600_000);
+ const d = await buildPlatformDigest(db, { since, now });
+ if (platformDigestEmpty(d)) {
+ o.log?.("platform digest: nothing to report");
+ return { channel: false, users: 0 };
+ }
+ const text = renderPlatformDigest(d);
+ const channel = toChannel && (await postToChannel(db, "digest", `pch:digest:${clock.date}`, text, c));
+ let sent = 0;
+ if (c.digest.users) {
+ const paired = (await db.select().from(users).where(isNotNull(users.telegramChatId))).filter((u) => !u.disabledAt);
+ for (const u of paired) {
+ const r = await deliverToUser(db, u, {
+ event: "platform",
+ dedupeKey: `pdigest:${clock.date}:${u.telegramChatId}`,
+ telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
+ now,
+ });
+ if (r.telegram) sent++;
+ }
+ }
+ o.log?.(`platform digest: channel ${channel ? "yes" : "no"}, users ${sent}`);
+ return { channel, users: sent };
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d8956b45..823093b6 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -17,6 +17,7 @@ export * from "./triage.ts";
export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./platform-release.ts";
+export * from "./platform-build.ts";
export * from "./code.ts";
export * from "./agents-md.ts";
export * from "./terminal.ts";
diff --git a/packages/runner/src/platform-build.ts b/packages/runner/src/platform-build.ts
new file mode 100644
index 00000000..c77b1aec
--- /dev/null
+++ b/packages/runner/src/platform-build.ts
@@ -0,0 +1,57 @@
+// New builds of Peppa (PEP-60). The watchdog looks at HEAD of Peppa's checkout about once a
+// minute; a commit that differs from the last announced one and belongs to `main` is a
+// release: posted to the platform channel with the stories from the commit messages. Works
+// now (dev from the working copy: a story branch isn't announced, returning to an updated
+// main is) and in prod (PEP-18: ~/peppa/current is a worktree of a `main` commit).
+import { execFileSync } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { announcePlatformBuild, getPlatformBuild, headCommit, peppaVersion, platformProjectKey } from "@peppa/core";
+import type { Db } from "@peppa/db";
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+
+const git = (root: string, args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+
+/** True when `commit` is reachable from the branch (default `main`). */
+export function onMainBranch(root: string, commit: string, branch = process.env.PEPPA_MAIN_BRANCH || "main"): boolean {
+ try {
+ git(root, ["merge-base", "--is-ancestor", commit, branch]);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Platform stories mentioned in the commits `prev..commit` (all of HEAD's history is too much: none then). */
+export function storiesBetween(root: string, prev: string | null, commit: string, key = platformProjectKey()): string[] {
+ if (!prev) return [];
+ let log = "";
+ try {
+ log = git(root, ["log", "--format=%s%n%b", `${prev}..${commit}`]);
+ } catch {
+ return [];
+ }
+ const re = new RegExp(`\\b${key}-(\\d+)\\b`, "gi");
+ const nums = new Set();
+ for (const m of log.matchAll(re)) nums.add(Number(m[1]));
+ return [...nums].sort((a, b) => a - b).map((n) => `${key}-${n}`);
+}
+
+let lastCheck = 0;
+
+/** Watchdog: announces a new build of Peppa once (first run only remembers it). */
+export async function platformBuildTick(db: Db, o: { root?: string; now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise {
+ const nowMs = (o.now ?? new Date()).getTime();
+ if (!o.force && Math.abs(nowMs - lastCheck) < 60_000) return false;
+ lastCheck = nowMs;
+ const root = o.root ?? process.env.PEPPA_ROOT ?? ROOT;
+ const commit = headCommit(root);
+ if (!commit) return false;
+ const prev = await getPlatformBuild(db);
+ if (prev?.commit === commit || !onMainBranch(root, commit)) return false;
+ const tasks = storiesBetween(root, prev?.commit ?? null, commit);
+ const posted = await announcePlatformBuild(db, { version: peppaVersion(root), commit, tasks }, { now: o.now });
+ o.log?.(`platform build ${commit.slice(0, 7)}${tasks.length ? ` (${tasks.join(", ")})` : ""}${posted ? " → channel" : ""}`);
+ return posted;
+}
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 3175e7a0..acc5b321 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
+ platformDigestTick,
+ recheckPlatformChannel,
getBudgetState,
runAsActor,
expireSessionQuestions,
@@ -23,6 +25,7 @@ import { hostTick } from "./hosts.ts";
import { getSubscription, isUsable } from "@peppa/core";
import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
import { monitorTick } from "./monitor.ts";
+import { platformBuildTick } from "./platform-build.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
@@ -83,6 +86,11 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise {
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
// 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}`));
+ // 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}`));
}
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 9b177f04..4bace09c 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -32,8 +32,15 @@ export class MockTelegram {
private server: Server | null = null;
/** PEP-45: uploaded voice files by file_id (served at /file/bot/). */
private files = new Map();
+ /** PEP-60: channels by chat id; the bot's membership decides what getChat/sendMessage do. */
+ readonly channels = new Map();
url = "";
+ /** A channel; by default the bot is its admin with the right to post. */
+ addChannel(chatId: number, title: string, o: { bot?: "administrator" | "member" | "left"; canPost?: boolean } = {}) {
+ this.channels.set(chatId, { title, bot: o.bot ?? "administrator", canPost: o.canPost ?? true });
+ }
+
async start(port = 0): Promise {
this.server = createServer((req, res) => {
let body = "";
@@ -94,7 +101,24 @@ export class MockTelegram {
}
return { ok: true, result: pending() };
}
+ case "getChat": {
+ const c = this.channels.get(Number(p.chat_id));
+ if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ return { ok: true, result: { id: Number(p.chat_id), type: "channel", title: c.title } };
+ }
+ case "getChatMember": {
+ const c = this.channels.get(Number(p.chat_id));
+ if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (Number(p.user_id) !== this.bot.id) return { ok: false, error_code: 400, description: "Bad Request: user not found" };
+ return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
+ }
case "sendMessage": {
+ // Channels (-100…): the bot must be an admin that may post.
+ if (String(p.chat_id).startsWith("-100")) {
+ const c = this.channels.get(Number(p.chat_id));
+ if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (c.bot !== "administrator" || !c.canPost) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
+ }
const m: MockTgMessage = {
message_id: this.nextMessageId++,
chat_id: Number(p.chat_id),
diff --git a/packages/testkit/test/platform-channel.test.ts b/packages/testkit/test/platform-channel.test.ts
new file mode 100644
index 00000000..716b6cdf
--- /dev/null
+++ b/packages/testkit/test/platform-channel.test.ts
@@ -0,0 +1,309 @@
+// PEP-60, spec platform-notifications: the platform channel (check through the Bot API),
+// platform events (new build, outage/recovery, restart) and the platform digest to the
+// channel and to users — mock-telegram as the Bot API, the real bot delivers the outbox,
+// a temp git repo as Peppa's checkout for builds.
+import assert from "node:assert/strict";
+import { execFile, execFileSync } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, before, beforeEach, 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 { MockTelegram } from "../src/mock-telegram.ts";
+import { questions, sessions, tasks, telegramOutbox, users } from "@peppa/db";
+import { eq, like, sql } from "drizzle-orm";
+
+const { createBot } = await import("@peppa/bot");
+const { TelegramApi } = await import("@peppa/bot/telegram");
+
+const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
+const MIN = 60_000;
+const CHANNEL = -1004371018094;
+const tg = await new MockTelegram().start();
+const TG = { token: tg.token, apiUrl: tg.url };
+process.env.TELEGRAM_BOT_TOKEN = tg.token;
+process.env.TELEGRAM_API_URL = tg.url;
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+process.env.PEPPA_TZ = "UTC";
+
+const ANNA = { login: "mock-anna", chatId: 9301 };
+const BEK = { login: "mock-bek", chatId: 9302 };
+let pep: Awaited>;
+let pepId = 0;
+
+async function pair(login: string, chatId: number, giteaId: number) {
+ const u = await core.upsertUserFromGitea(db, { id: giteaId, login }, { access_token: "x" });
+ await db.update(users).set({ telegramChatId: chatId, telegramUserId: chatId }).where(eq(users.id, u.id));
+ return u;
+}
+
+/** Texts queued for a chat, oldest first. */
+async function queued(chatId: number, keyLike = "%"): Promise {
+ const rows = await db
+ .select()
+ .from(telegramOutbox)
+ .where(sql`${telegramOutbox.dedupeKey} like ${keyLike} and cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`)
+ .orderBy(telegramOutbox.id);
+ return rows.map((r) => String(r.params.text));
+}
+
+async function connectChannel() {
+ tg.addChannel(CHANNEL, "Peppa News");
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ return core.checkPlatformChannel(db, TG);
+}
+
+before(async () => {
+ pep = await project({ steps: [] });
+ process.env.PEPPA_PLATFORM_KEY = pep.key;
+ pepId = (await core.getProject(db, pep.key)).id;
+ await pair(ANNA.login, ANNA.chatId, 9401);
+ await pair(BEK.login, BEK.chatId, 9402);
+});
+beforeEach(async () => {
+ db.run(sql`delete from settings where key like 'platform.%' or key like 'heartbeat:%' or key like 'monitor.%' or key like 'notify.prefs:%'`);
+ await db.delete(telegramOutbox);
+ await db.delete(sessions);
+ tg.channels.clear();
+});
+after(async () => {
+ await tg.stop();
+ await teardown();
+});
+
+describe("Канал платформы", () => {
+ test("Бот — админ канала", async () => {
+ const c = await connectChannel();
+ assert.equal(c.check?.ok, true);
+ assert.equal(core.describeChannel(c), "канал подключён — Peppa News");
+ assert.equal((await core.getPlatformChannel(db)).title, "Peppa News");
+ });
+
+ test("Бот не добавлен в канал", async () => {
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ const c = await core.checkPlatformChannel(db, TG);
+ assert.equal(c.check?.ok, false);
+ assert.equal(c.check?.error, "бот не видит канал — добавьте его администратором");
+ // Not posting while the channel doesn't work.
+ assert.equal(await core.postToChannel(db, "releases", "pch:test", "x"), false);
+ });
+
+ test("Бот в канале без права публикации", async () => {
+ tg.addChannel(CHANNEL, "Peppa News", { canPost: false });
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ const c = await core.checkPlatformChannel(db, TG);
+ assert.equal(c.check?.error, core.CHANNEL_NO_POST);
+ });
+
+ test("Пеппа перепроверяет неработающий канал раз в час и включает его", async () => {
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ const t0 = new Date("2026-03-01T10:00:00Z");
+ assert.equal(await core.recheckPlatformChannel(db, { now: t0, tg: TG }), true);
+ assert.equal((await core.getPlatformChannel(db)).check?.ok, false);
+ tg.addChannel(CHANNEL, "Peppa News");
+ assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 30 * MIN), tg: TG }), false, "не раньше часа");
+ assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 61 * MIN), tg: TG }), true);
+ assert.equal((await core.getPlatformChannel(db)).check?.ok, true);
+ });
+
+ test("Неверный Chat ID и сброс проверки при смене канала", async () => {
+ assert.throws(() => core.parseChatId("канал"), /Chat ID/);
+ assert.equal(core.parseChatId("@peppa_news"), "@peppa_news");
+ await connectChannel();
+ const c = await core.setPlatformChannel(db, { chatId: -1009999999999 });
+ assert.equal(c.check, null);
+ });
+
+ test("Не суперадмин", async () => {
+ await core.setPlatformAdmins(db, [ANNA.login]);
+ await assert.rejects(core.requireSuperadmin(db, { login: BEK.login }));
+ await core.requireSuperadmin(db, { login: ANNA.login });
+ });
+
+ test("CLI: peppa platform channel", async () => {
+ tg.addChannel(CHANNEL, "Peppa News");
+ // Async: the mock Bot API lives in this process.
+ const { stdout: out } = await promisify(execFile)(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), "platform", "channel", `chat=${CHANNEL}`, "services=off", "time=08:30"], { encoding: "utf8", env: process.env });
+ assert.match(out, /канал подключён — Peppa News/);
+ assert.match(out, /services=off/);
+ assert.match(out, /дайджест: 08:30/);
+ });
+});
+
+describe("События платформы в канал", () => {
+ test("Новый релиз", async () => {
+ await connectChannel();
+ await db.insert(tasks).values([
+ { projectId: pepId, number: 59, title: "Версия и коммит в футере веба" },
+ { projectId: pepId, number: 61, title: "Меню сверху" },
+ ]);
+ const k = (n: number) => `${pep.key}-${n}`;
+ assert.equal(await core.announcePlatformBuild(db, { version: "0.15.0", commit: "aa8796a".padEnd(40, "0"), tasks: [] }), false, "первая сборка только запоминается");
+ assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [k(59), k(61)] }), true);
+ const [msg] = await queued(CHANNEL);
+ assert.match(msg!, /Peppa v0\.16\.0 · b1c2d3e/);
+ assert.match(msg!, new RegExp(`Стори: ${k(59)}, ${k(61)}`));
+ assert.match(msg!, /Версия и коммит в футере веба/);
+ // The same commit again — nothing new.
+ assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [] }), false);
+ assert.equal((await queued(CHANNEL)).length, 1);
+ });
+
+ test("Сборка из ветки стори не объявляется, из main — со стори из коммитов", async () => {
+ await connectChannel();
+ const repo = mkdtempSync(join(tmpdir(), "peppa-build-"));
+ const git = (...a: string[]) => execFileSync("git", ["-C", repo, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim();
+ git("init", "-q", "-b", "main");
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.15.0" }));
+ git("add", "-A");
+ git("commit", "-qm", "base");
+ const now = new Date("2026-03-02T10:00:00Z");
+ await runner.platformBuildTick(db, { root: repo, force: true, now });
+ assert.equal((await core.getPlatformBuild(db))?.version, "0.15.0");
+ // A story branch checked out: not a release.
+ git("checkout", "-qb", `task/${pep.key.toLowerCase()}-70`);
+ mkdirSync(join(repo, "src"));
+ writeFileSync(join(repo, "src/a.txt"), "a");
+ git("add", "-A");
+ git("commit", "-qm", `${pep.key}-70: work in progress`);
+ assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), false);
+ // Merged into main with a version bump: announced with the stories of the merged commits.
+ git("checkout", "-q", "main");
+ git("merge", "-q", "--no-ff", "-m", `Merge pull request '${pep.key}-70: канал' (#9) from task/${pep.key.toLowerCase()}-70 into main`, `task/${pep.key.toLowerCase()}-70`);
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.16.0" }));
+ git("commit", "-qam", `${pep.key}-72: bump`);
+ assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), true);
+ const [msg] = await queued(CHANNEL);
+ assert.match(msg!, new RegExp(`Peppa v0\\.16\\.0 · ${git("rev-parse", "--short=7", "HEAD")}`));
+ assert.match(msg!, new RegExp(`Стори: ${pep.key}-70, ${pep.key}-72`));
+ });
+
+ test("Сервис упал и поднялся", async () => {
+ await connectChannel();
+ const T0 = Date.parse("2026-03-03T12:00:00Z");
+ const at = (m: number) => new Date(T0 + m * MIN);
+ const staleMs = 2 * MIN;
+ await core.beat(db, "bot", { now: at(0) });
+ for (const m of [1, 3, 4, 10]) {
+ await core.checkServices(db, { self: "watchdog", now: at(m), staleMs });
+ await core.checkServices(db, { self: "web", now: at(m), staleMs });
+ }
+ await core.beat(db, "bot", { now: at(12) });
+ await core.checkServices(db, { self: "watchdog", now: at(12), staleMs });
+ await core.checkServices(db, { self: "web", now: at(12.5), staleMs });
+ const msgs = await queued(CHANNEL, "mon:ch:%");
+ assert.equal(msgs.length, 2, msgs.join("\n"));
+ assert.match(msgs[0]!, /бот не отвечает с/);
+ assert.match(msgs[1]!, /бот снова работает — простой 12 мин/);
+ });
+
+ test("Перезапуск сервиса без простоя", async () => {
+ await connectChannel();
+ const now = new Date();
+ const hb = (pid: number) => ({ at: now.toISOString(), startedAt: new Date(now.getTime() - pid).toISOString(), pid, host: "mac", version: "0.15.0", commit: "abc1234".padEnd(40, "0") });
+ await core.setSetting(db, "heartbeat:web", hb(100));
+ await core.checkServices(db, { self: "watchdog", now });
+ assert.equal((await queued(CHANNEL)).length, 0, "первый процесс только запоминается");
+ await core.setSetting(db, "heartbeat:web", hb(200));
+ await core.checkServices(db, { self: "watchdog", now });
+ await core.checkServices(db, { self: "bot", now });
+ const msgs = await queued(CHANNEL);
+ assert.deepEqual(msgs, ["🔄 Пеппа: веб перезапущен (v0.15.0 · abc1234)."]);
+ });
+
+ test("Выключенные события сервисов в канал не идут", async () => {
+ await connectChannel();
+ await core.setPlatformChannel(db, { events: { services: false } });
+ const T0 = Date.parse("2026-03-04T12:00:00Z");
+ await core.beat(db, "bot", { now: new Date(T0) });
+ await core.checkServices(db, { self: "watchdog", now: new Date(T0 + 10 * MIN), staleMs: 2 * MIN });
+ assert.equal((await queued(CHANNEL, "mon:ch:%")).length, 0);
+ });
+});
+
+describe("Дайджест", () => {
+ const day = (h: number, d = 5) => new Date(`2026-03-${String(d).padStart(2, "0")}T${String(h).padStart(2, "0")}:05:00Z`);
+
+ async function activity() {
+ // Stories finished after the previous digest, two live runners and one open question.
+ await db.insert(tasks).values([
+ { projectId: pepId, number: 159, title: "Футер с версией", status: "done", updatedAt: day(6) },
+ { projectId: pepId, number: 161, title: "Меню сверху", status: "done", updatedAt: day(7) },
+ ]);
+ await db.insert(sessions).values([
+ { projectId: pepId, tmuxName: "mock-digest-1", status: "running" },
+ { projectId: pepId, tmuxName: "mock-digest-2", status: "idle" },
+ ]);
+ await db.insert(questions).values({ projectId: pepId, kind: "question", text: "Какой цвет?" });
+ }
+
+ async function cleanActivity() {
+ await db.delete(questions);
+ await db.delete(tasks).where(sql`${tasks.number} in (159, 161)`);
+ }
+
+ test("Ежедневный дайджест", async () => {
+ await connectChannel();
+ await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
+ await activity();
+ try {
+ assert.equal(await core.platformDigestTick(db, { now: day(8) }), null, "до времени дайджеста — ничего");
+ const r = await core.platformDigestTick(db, { now: day(9) });
+ assert.deepEqual(r, { channel: true, users: 0 });
+ const [msg] = await queued(CHANNEL, "pch:digest:%");
+ assert.match(msg!, /Что нового<\/b>/);
+ assert.match(msg!, new RegExp(`Сделано: ${pep.key}-159, ${pep.key}-161`));
+ assert.match(msg!, /Сейчас<\/b>/);
+ assert.match(msg!, /Раннеров: 2/);
+ assert.match(msg!, /Вопросов: 1/);
+ assert.equal(await core.platformDigestTick(db, { now: day(10) }), null, "раз в сутки");
+ } finally {
+ await cleanActivity();
+ }
+ });
+
+ test("Нечего сообщить", async () => {
+ await connectChannel();
+ await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
+ const r = await core.platformDigestTick(db, { now: day(9) });
+ assert.deepEqual(r, { channel: false, users: 0 });
+ assert.equal((await queued(CHANNEL)).length, 0);
+ });
+
+ test("Отписка", async () => {
+ await connectChannel();
+ await core.setPlatformChannel(db, { digest: { users: true } });
+ const anna = (await core.getUserByLogin(db, ANNA.login))!;
+ const prefs = await core.getNotifyPrefs(db, anna.id);
+ await core.setNotifyPrefs(db, anna.id, { ...prefs, events: { ...prefs.events, platform: { telegram: false, push: false } } });
+ await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
+ await activity();
+ try {
+ const r = await core.platformDigestTick(db, { now: day(9) });
+ assert.equal(r?.channel, true);
+ assert.equal((await queued(ANNA.chatId, "pdigest:%")).length, 0, "отписавшийся не получает");
+ assert.equal((await queued(BEK.chatId, "pdigest:%")).length, 1);
+ assert.equal((await queued(CHANNEL, "pch:digest:%")).length, 1, "канал получает");
+ } finally {
+ await cleanActivity();
+ }
+ });
+
+ test("Бот доставляет сообщения канала из outbox", async () => {
+ await connectChannel();
+ await core.setPlatformChannel(db, { digest: { users: false } });
+ await core.postToChannel(db, "releases", "pch:release:mock", "🚀 Peppa v9.9.9 · mock000 ");
+ const bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 5000, heartbeatIntervalMs: 60_000 });
+ await bot.start();
+ try {
+ await waitFor("channel message delivered", async () => tg.botMessages(CHANNEL).some((m) => /Peppa v9\.9\.9/.test(m.text)));
+ const [row] = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "pch:release:mock"));
+ assert.equal(row?.status, "sent");
+ } finally {
+ await bot.stop();
+ }
+ });
+});
--
2.45.2
From fbe4336d20ea0e28296c246e7924d3f1e4a85514 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 19:04:21 +0500
Subject: [PATCH 007/428] =?UTF-8?q?PEP-60:=20docs=20=E2=80=94=20AGENTS.md,?=
=?UTF-8?q?=20/help;=20project=20memory?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.peppa/memory.md | 6 ++++++
AGENTS.md | 1 +
apps/web/app/(app)/help/page.tsx | 6 ++++++
3 files changed, 13 insertions(+)
create mode 100644 .peppa/memory.md
diff --git a/.peppa/memory.md b/.peppa/memory.md
new file mode 100644
index 00000000..53b342f6
--- /dev/null
+++ b/.peppa/memory.md
@@ -0,0 +1,6 @@
+# Память проекта
+
+Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.
+
+## Грабли
+- Один файл e2e: `env -u NODE_TEST_CONTEXT node --test --test-reporter=spec test/.test.ts` (внутри сессии Claude без этого вывод бинарный); CLI из теста с моком в том же процессе — только async execFile, execFileSync вешает мок.
diff --git a/AGENTS.md b/AGENTS.md
index 6ba94b29..33a99983 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,6 +43,7 @@
- **Секреты (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`
- **Уведомления (PEP-29/35/55)**: события `questions`/`review`/`failures`/`releases`/`incidents`/`monitoring`/`digest` × каналы Telegram/push на пользователя — `notify.prefs:` в `settings` (`getNotifyPrefs` с умолчаниями, всё включено, кроме дайджеста в браузер), тихие часы (Telegram с `disable_notification`, push пропускается), таймзона (по умолчанию сервера или `PEPPA_TZ`), выключенные проекты. Всё идёт через `deliverToUser` (core/notifications.ts): вопросы (бот `reconcile`, категория — `questionEvent`, получатели — `projectAudience`; ключи Telegram `q::` прежние), ошибки из прода, алерты мониторинга. Web Push — свой на `node:crypto` (core/webpush.ts: VAPID в `settings` `push.vapid`, aes128gcm), таблицы `push_subscriptions` + `push_outbox` (разбирает бот вместе с Telegram-outbox, 404/410 удаляют подписку; push только для вопросов моложе 30 мин). Веб: «Настройки → Уведомления», `public/sw.js`, `app/manifest.ts` (PWA), `AttentionBadge` (счётчик в заголовке и значке, звук; `/api/attention`). Дайджест (core/digest.ts): `digestTick` в `tick` вачдога — в выбранное время (окно 3 ч, `digest.last:`), пустой не шлётся; `/digest` в боте. Мок — `mock-push` (testkit: проверяет VAPID и расшифровывает)
+- **Канал платформы и дайджест Пеппы (PEP-60)**: `core/platform-channel.ts`, настройки в `settings` `platform.telegram_channel` (Chat ID, `check` — результат `checkPlatformChannel`: Bot API `getMe`→`getChat`→`getChatMember`, «бот не видит канал — добавьте его администратором» / нет права публикации; события releases/services/digest; `digest.time/timezone/users`, личные чаты по умолчанию выкл). В канал пишет только при `check.ok` (`postToChannel`, outbox; сервисные ключи `mon:ch:*` — вачдог доставит сам, если упал бот); неработающий канал вачдог перепроверяет раз в час (`recheckPlatformChannel`). События: `checkServices` — одно «не отвечает» и одно «снова работает — простой N мин» на простой, «перезапущен» при смене процесса без простоя (`monitor.process:`, heartbeat несёт `commit`); `platformBuildTick` (runner/platform-build.ts) — HEAD корня ≠ `platform.build` и входит в `main` → «🚀 Peppa vX · sha» + стори из коммитов (первый раз только запоминает). `platformDigestTick` (вачдог): «Что нового» (done-стори `PEPPA_PLATFORM_KEY`, сборки) + «Сейчас» (версия, сервисы, раннеры, вопросы, лимиты), пустой не шлётся, в канал и пользователям событием уведомлений `platform`. Веб `/platform` (суперадмин), CLI `peppa platform channel chat= [k=v…]|check`, `peppa platform digest [now]`. Мок — каналы в `mock-telegram` (`addChannel`)
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]`
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)
- Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью)
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 049e478e..fb1bad36 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -227,6 +227,12 @@ export default async function Help() {
при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию
09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит.
+
+ Новости самой Пеппы — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Пеппы» (что нового и
+ что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа».
+ Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест
+ обновлений Пеппы» в Настройках → Уведомления.
+
--
2.45.2
From 3b23bbad2409a82bb8dfe1c6f24b7c0c07c6a1d9 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 19:04:49 +0500
Subject: [PATCH 008/428] PEP-60: test scenario type
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/platform-channel.test.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/testkit/test/platform-channel.test.ts b/packages/testkit/test/platform-channel.test.ts
index 716b6cdf..42a66e22 100644
--- a/packages/testkit/test/platform-channel.test.ts
+++ b/packages/testkit/test/platform-channel.test.ts
@@ -57,7 +57,7 @@ async function connectChannel() {
}
before(async () => {
- pep = await project({ steps: [] });
+ pep = await project({ turns: [] });
process.env.PEPPA_PLATFORM_KEY = pep.key;
pepId = (await core.getProject(db, pep.key)).id;
await pair(ANNA.login, ANNA.chatId, 9401);
--
2.45.2
From b13b87d38d8657e90eed049d8fb7afbfdf192985 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 19:11:13 +0500
Subject: [PATCH 009/428] =?UTF-8?q?PEP-60:=20archive=20change=20=E2=80=94?=
=?UTF-8?q?=20platform-notifications=20spec?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.../.openspec.yaml | 0
.../design.md | 0
.../proposal.md | 0
.../specs/platform-notifications/spec.md | 0
.../tasks.md | 4 +-
openspec/specs/platform-notifications/spec.md | 55 +++++++++++++++++++
6 files changed, 57 insertions(+), 2 deletions(-)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/.openspec.yaml (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/design.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/proposal.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/specs/platform-notifications/spec.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/tasks.md (91%)
create mode 100644 openspec/specs/platform-notifications/spec.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/.openspec.yaml b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/.openspec.yaml
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/.openspec.yaml
diff --git a/openspec/changes/pep-60-platform-channel-digest/design.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/design.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/design.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/design.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/proposal.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/proposal.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/proposal.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/specs/platform-notifications/spec.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/specs/platform-notifications/spec.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
similarity index 91%
rename from openspec/changes/pep-60-platform-channel-digest/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
index 7276743f..2ea66040 100644
--- a/openspec/changes/pep-60-platform-channel-digest/tasks.md
+++ b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
@@ -14,5 +14,5 @@
- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
## 3. Проверка
-- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
-- [ ] 3.2 Документация: AGENTS.md, `/help`
+- [x] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
+- [x] 3.2 Документация: AGENTS.md, `/help`
diff --git a/openspec/specs/platform-notifications/spec.md b/openspec/specs/platform-notifications/spec.md
new file mode 100644
index 00000000..3da90d2a
--- /dev/null
+++ b/openspec/specs/platform-notifications/spec.md
@@ -0,0 +1,55 @@
+# platform-notifications Specification
+
+## Purpose
+Определяет, как Пеппа сообщает о себе: события платформы в Telegram-канал, заданный суперадмином, и дайджесты обновлений и состояния.
+
+## Requirements
+
+### Requirement: Канал платформы
+Суперадмин SHALL задавать Telegram-канал платформы по Chat ID в настройках платформы; Пеппа SHALL проверять, что бот может писать в канал, и показывать результат.
+
+#### Scenario: Бот — админ канала
+- **GIVEN** бот добавлен администратором канала с Chat ID «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** в настройках видно «канал подключён» с названием канала
+
+#### Scenario: Бот не добавлен в канал
+- **GIVEN** бот не состоит в канале «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** настройки показывают «бот не видит канал — добавьте его администратором»
+
+#### Scenario: Не суперадмин
+- **GIVEN** пользователь без роли суперадмина
+- **WHEN** он открывает настройки платформы
+- **THEN** он получает «не найдено»
+
+### Requirement: События платформы в канал
+Пеппа SHALL публиковать в канал платформы новые релизы, перезапуски и падения сервисов и их восстановление.
+
+#### Scenario: Новый релиз
+- **GIVEN** канал платформы подключён и в проде версия «0.15.0» коммит «aa8796a»
+- **WHEN** выкачена версия «0.16.0» коммит «b1c2d3e» с задачами PEP-59 и PEP-61
+- **THEN** в канале появляется сообщение «Peppa v0.16.0 · b1c2d3e» со списком «PEP-59, PEP-61»
+
+#### Scenario: Сервис упал и поднялся
+- **GIVEN** канал платформы подключён
+- **WHEN** бот Пеппы перестал отвечать дольше 2 минут, а затем восстановился
+- **THEN** в канале одно сообщение о падении и одно о восстановлении с длительностью простоя
+
+### Requirement: Дайджест
+Пеппа SHALL по расписанию отправлять в канал дайджест: изменения Пеппы с прошлого дайджеста и текущее состояние платформы; пользователи с привязанным Telegram SHALL получать личный дайджест по своим проектам, если не отписались.
+
+#### Scenario: Ежедневный дайджест
+- **GIVEN** с прошлого дайджеста смержены задачи PEP-59 и PEP-61, сейчас 2 активных раннера и 1 открытый вопрос
+- **WHEN** наступает время дайджеста
+- **THEN** в канале сообщение с разделами «Что нового» (PEP-59, PEP-61), «Сейчас»: раннеров 2, вопросов 1
+
+#### Scenario: Нечего сообщить
+- **GIVEN** с прошлого дайджеста не было изменений и активности
+- **WHEN** наступает время дайджеста
+- **THEN** дайджест не отправляется
+
+#### Scenario: Отписка
+- **GIVEN** пользователь отключил личный дайджест в Настройках
+- **WHEN** наступает время дайджеста
+- **THEN** он личный дайджест не получает, канал — получает
--
2.45.2
From b4b31ea88c89a8f649aa658e1d95443c43f9f1e0 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 19:21:23 +0500
Subject: [PATCH 010/428] PEP-62: write chat cursors only when they move
Co-Authored-By: Claude Opus 5.5
---
packages/core/src/chats.ts | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 1422ed20..282248e9 100644
--- a/packages/core/src/chats.ts
+++ b/packages/core/src/chats.ts
@@ -326,7 +326,9 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
};
// events
- let cursor = (await getSetting(db, CURSOR_EVENTS)) ?? (await initialCursor(db, events, now));
+ // Cursors are written only when they move: a no-op sync doesn't wake the other processes.
+ const savedEvents = await getSetting(db, CURSOR_EVENTS);
+ let cursor = savedEvents ?? (await initialCursor(db, events, now));
for (;;) {
// Read the newest id first: a row committed after it is picked up by the next call.
const [top] = await db.select({ max: sql`max(${events.id})` }).from(events);
@@ -355,10 +357,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo);
if (rows.length < BATCH) break;
}
- await setSetting(db, CURSOR_EVENTS, cursor);
+ if (cursor !== savedEvents) await setSetting(db, CURSOR_EVENTS, cursor);
// questions
- let qCursor = (await getSetting(db, CURSOR_QUESTIONS)) ?? (await initialCursor(db, questions, now));
+ const savedQuestions = await getSetting(db, CURSOR_QUESTIONS);
+ let qCursor = savedQuestions ?? (await initialCursor(db, questions, now));
for (;;) {
const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH);
for (const q of rows) {
@@ -379,10 +382,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
}
if (rows.length < BATCH) break;
}
- await setSetting(db, CURSOR_QUESTIONS, qCursor);
+ if (qCursor !== savedQuestions) await setSetting(db, CURSOR_QUESTIONS, qCursor);
// releases and incidents: one message per (id, status); the window overlaps a little.
- const since = new Date(((await getSetting(db, CURSOR_OBJECTS)) ?? now.getTime() - DAY) - 60_000);
+ const savedObjects = await getSetting(db, CURSOR_OBJECTS);
+ const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000);
for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
await add({
@@ -407,7 +411,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
dedupeKey: `incident:${i.id}:${i.status}`,
});
}
- await setSetting(db, CURSOR_OBJECTS, now.getTime());
+ // Moved at most every 30 s (the window overlaps by a minute, so nothing is lost).
+ if (savedObjects == null || now.getTime() - savedObjects >= 30_000) await setSetting(db, CURSOR_OBJECTS, now.getTime());
if (added) await notify(db, { type: "chat_message", messageId: 0 });
return added;
}
--
2.45.2
From f00076c575d749ae7c3fcb68b7caefcab4e7b837 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 19:35:52 +0500
Subject: [PATCH 011/428] =?UTF-8?q?PEP-76:=20the=20project=20owner=20picks?=
=?UTF-8?q?=20the=20subscription=20=E2=80=94=20the=20shared=20pool=20or=20?=
=?UTF-8?q?their=20own=20Claude=20token?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 17 ++++++-
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/p/[key]/page.tsx | 41 +++++++++++++----
.../proposal.md | 16 +++++++
.../specs/agent-credentials/spec.md | 24 ++++++++++
.../tasks.md | 4 ++
openspec/specs/agent-credentials/spec.md | 23 ++++++++++
packages/cli/src/index.ts | 11 ++++-
packages/core/src/onboarding.ts | 7 ++-
packages/core/src/subscriptions.ts | 25 +++++++++++
packages/runner/src/index.ts | 1 +
packages/runner/src/project-subscription.ts | 45 +++++++++++++++++++
packages/runner/src/sessions.ts | 2 +-
packages/testkit/test/subscriptions.test.ts | 41 +++++++++++++++++
15 files changed, 247 insertions(+), 12 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md
create mode 100644 packages/runner/src/project-subscription.ts
diff --git a/AGENTS.md b/AGENTS.md
index 6ba94b29..fc2081e4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,6 +34,7 @@
- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
+- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (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`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 96ae9a2a..ec2e9d6c 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -660,3 +660,18 @@ export async function saveAgentsMdAction(f: FormData) {
return `/p/${p.key}?tab=agents&saved=1`;
});
}
+
+// ── PEP-76: what the project's agents run on ───────────────────────────────────────
+export async function chooseSharedSubscriptionAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await chooseSharedSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))));
+ });
+}
+
+export async function connectOwnSubscriptionAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await connectOwnSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), String(f.get("token") ?? ""));
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 049e478e..256b4aea 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,6 +70,7 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
+ Подписка проекта — на чём работают агенты, выбирает владелец в «⋯ Настройки проекта → Подписки»: «Общая подписка Пеппы» или своя подписка Claude (токен команды claude setup-token на своём компьютере). Пока выбор не сделан, проект нового пользователя агентов не запускает.
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 624b3c19..16ce033c 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -21,7 +21,7 @@ import { requireUser } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
-import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
+import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
import { AgentsMdTab, CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
@@ -100,7 +100,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const isOwner = p.ownerId === user.id;
// PEP-67: default subscription pool; only a superadmin changes it.
const superadmin = await isSuperadmin(db, user);
- const [pool, pools, autonomy] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id)]);
+ const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
// PEP-10/27: runner settings of the project over the system ones.
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
// PEP-41: agent provider/model of the project over the platform's.
@@ -291,7 +291,34 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
- {superadmin ? (
+
+ {pool ? (
+ <>Агенты работают на пуле «{pool.name}»{shared?.id === pool.id ? " — общая подписка Пеппы" : ""}.>
+ ) : agentWarning ? (
+ Подписка не выбрана — агенты не запустятся.
+ ) : (
+ "Пул не назначен — агенты работают на входе машины."
+ )}
+
+ {(isOwner || superadmin) && (
+ <>
+ {shared && shared.id !== pool?.id && (
+
+
+ Общая подписка Пеппы
+
+ )}
+
+
+
+ Своя подписка Claude
+
+ Токен выдаёт команда claude setup-token на вашем компьютере. Хранится зашифрованным, показать его нельзя. Уже подключали — оставьте поле пустым.
+
+
+ >
+ )}
+ {superadmin && (
@@ -302,10 +329,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Сохранить
- ) : (
- {pool ? <>Пул «{pool.name}»> : "Пул не назначен — агенты работают на входе машины"}
)}
- Раннеры проекта стартуют на свободной подписке пула по умолчанию. {superadmin ? Пулы и подписки : "Меняет суперадмин."}
+ Раннеры проекта стартуют на свободной подписке пула. {superadmin ? Пулы и подписки : "Выбирает владелец проекта."}
);
@@ -362,7 +387,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{agentWarning && (
Агенты не запустятся: {agentWarning}.
- {superadmin ? Подписки → : Попроси суперадмина проверить подписки или сменить пул в «⋯ Настройки проекта». }
+ {pool ? (superadmin ? Подписки → : Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её. ) : null}
)}
diff --git a/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md
new file mode 100644
index 00000000..342448d4
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md
@@ -0,0 +1,16 @@
+# PEP-76: выбор подписки для проекта — общая или своя
+
+## Why
+После PEP-71 зарегистрироваться может любой человек с eGov, а его проект без пула подписок агентов не запускает: пул назначал
+только суперадмин. PM решил: новый пользователь сам выбирает — подключить свою подписку или работать на подписке PM.
+
+## What Changes
+- Общий пул платформы: настройка `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`).
+- Панель «Подписки» в настройках проекта для владельца (и суперадмина): «Общая подписка Пеппы» (`chooseSharedSubscription`) и
+ «Своя подписка Claude» (`connectOwnSubscription`): токен `claude setup-token` → подписка пользователя в его личном пуле
+ «Claude — <логин>»; пул уже есть и поле пустое — проект просто переходит на него. Токен хранится зашифрованным, только на запись.
+- `projectAgentWarning`: проект без пула, владелец которого не получает вход машины, — «подписка не выбрана» со ссылкой на выбор;
+ тот же текст в отказе запуска.
+- Событие `project_subscription` в журнале.
+
+Вне scope: свои подписки Codex/OpenCode, вход `claude setup-token` через браузер, лимиты на общую подписку. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..5dfed336
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md
@@ -0,0 +1,24 @@
+## ADDED Requirements
+
+### Requirement: Владелец выбирает подписку проекта
+Владелец проекта SHALL выбирать, на чём работают агенты проекта: на общем пуле платформы
+(«Общая подписка Пеппы», задаёт суперадмин) или на своей подписке Claude, подключённой
+токеном. Проект без пула, владельцу которого не положен вход машины, SHALL показывать, что
+подписка не выбрана, и не запускать агентов.
+
+#### Scenario: Общая подписка
+- **GIVEN** суперадмин задал общий пул, у проекта нового пользователя пула нет
+- **WHEN** владелец нажимает «Общая подписка Пеппы»
+- **THEN** проект работает на общем пуле, предупреждение «Агенты не запустятся» исчезает
+
+#### Scenario: Своя подписка
+- **WHEN** владелец вставляет токен своей подписки Claude и нажимает «Своя подписка Claude»
+- **THEN** создаются его подписка и пул «Claude — <логин>», проект работает на нём, токен нигде не показывается
+
+#### Scenario: Неверный токен
+- **WHEN** владелец вставляет строку, не похожую на токен Claude
+- **THEN** выбор отклонён, подписка не создаётся, пул проекта не меняется
+
+#### Scenario: Не владелец
+- **WHEN** участник проекта, не владелец и не суперадмин, пытается сменить подписку
+- **THEN** действие отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md
new file mode 100644
index 00000000..d9158adc
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md
@@ -0,0 +1,4 @@
+- [x] 1 `sharedPool`/`setSharedPool`/`ownPool`, CLI `peppa platform shared-pool`
+- [x] 2 `chooseSharedSubscription`/`connectOwnSubscription`, предупреждение «подписка не выбрана»
+- [x] 3 Панель «Подписки» в проекте
+- [x] 4 Тест в `subscriptions.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md
index 532df4b8..5531053c 100644
--- a/openspec/specs/agent-credentials/spec.md
+++ b/openspec/specs/agent-credentials/spec.md
@@ -98,3 +98,26 @@ Claude и делать пул с этой подпиской пулом по у
- **GIVEN** у «asel» в настройках был подключён Claude и он владелец проекта PEP
- **WHEN** применяется миграция
- **THEN** есть активная подписка «Claude — asel» с тем же токеном, у PEP пул «Claude — asel», а у пользователя токена больше нет
+
+### Requirement: Владелец выбирает подписку проекта
+Владелец проекта SHALL выбирать, на чём работают агенты проекта: на общем пуле платформы
+(«Общая подписка Пеппы», задаёт суперадмин) или на своей подписке Claude, подключённой
+токеном. Проект без пула, владельцу которого не положен вход машины, SHALL показывать, что
+подписка не выбрана, и не запускать агентов.
+
+#### Scenario: Общая подписка
+- **GIVEN** суперадмин задал общий пул, у проекта нового пользователя пула нет
+- **WHEN** владелец нажимает «Общая подписка Пеппы»
+- **THEN** проект работает на общем пуле, предупреждение «Агенты не запустятся» исчезает
+
+#### Scenario: Своя подписка
+- **WHEN** владелец вставляет токен своей подписки Claude и нажимает «Своя подписка Claude»
+- **THEN** создаются его подписка и пул «Claude — <логин>», проект работает на нём, токен нигде не показывается
+
+#### Scenario: Неверный токен
+- **WHEN** владелец вставляет строку, не похожую на токен Claude
+- **THEN** выбор отклонён, подписка не создаётся, пул проекта не меняется
+
+#### Scenario: Не владелец
+- **WHEN** участник проекта, не владелец и не суперадмин, пытается сменить подписку
+- **THEN** действие отклонено
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 7d3977cf..759c72e0 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -71,7 +71,7 @@ import {
import { createDb, migrateDb } from "@peppa/db";
import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
-import { createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } 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 { spawnSync } from "node:child_process";
@@ -120,6 +120,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa host check|disable|enable|rm|push-image
(PEP-10/27: system → project → story; a story overrides mode/context only)
peppa platform allowlist | allow | deny (who may log into Peppa)
+ peppa platform shared-pool [poolId|-] (the pool any project owner may pick as the shared subscription)
peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch)
peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist)
peppa platform watchdog [key=value… | key=- | reset] (PEP-28: restartMax restartWindowMin restartDelaysMin=1,5,15
@@ -674,6 +675,14 @@ async function main(): Promise {
console.log(`${u.login} (#${u.id})`);
break;
}
+ case "platform shared-pool": {
+ // PEP-76: the pool project owners may pick as «Общая подписка Пеппы».
+ if (args[0] === "-") await setSharedPool(db, null);
+ else if (args[0]) await setSharedPool(db, Number(args[0]));
+ const sp = await sharedPool(db);
+ console.log(sp ? `общий пул: #${sp.id} «${sp.name}»` : "общий пул не задан");
+ break;
+ }
case "platform release-offers": {
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index 02c9c759..dcf895e1 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -1,6 +1,7 @@
// PEP-31: first-run checklist on the home page and the "agents won't start" project warning.
import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
+import { mayUseMachineLogin } from "./access.ts";
import { isSuperadmin } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { isUsable, poolSubscriptions } from "./subscriptions.ts";
@@ -78,7 +79,11 @@ const STATUS_RU: Record = { pending: "не подключена"
*/
export async function projectAgentWarning(db: Db, projectId: number, now = new Date()): Promise {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
- if (p?.poolId == null) return null;
+ if (p?.poolId == null) {
+ // PEP-71/76: a self-registered owner has no machine login — a subscription must be chosen.
+ const [o] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
+ return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не выбрана — владелец выбирает общую или подключает свою в «⋯ Настройки проекта → Подписки»";
+ }
const subs = await poolSubscriptions(db, p.poolId);
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
if (subs.some((s) => isUsable(s, now))) return null;
diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts
index 00da7e5c..afe86721 100644
--- a/packages/core/src/subscriptions.ts
+++ b/packages/core/src/subscriptions.ts
@@ -9,6 +9,7 @@ import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { isSuperadmin } from "./monitor.ts";
import type { Project } from "./projects.ts";
+import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
import type { User } from "./users.ts";
@@ -377,3 +378,27 @@ export async function projectPoolExhausted(db: Db, projectId: number, now = new
if (p?.poolId == null) return false;
return !(await poolSubscriptions(db, p.poolId)).some((s) => isUsable(s, now));
}
+
+// ── PEP-76: the platform's shared pool and the owner's choice ───────────────────────
+const SHARED_POOL = "platform.shared_pool";
+
+/** The pool any project owner may pick as «Общая подписка Пеппы» (set by a superadmin), or null. */
+export async function sharedPool(db: Db): Promise {
+ const id = await getSetting(db, SHARED_POOL);
+ if (id == null) return null;
+ const [p] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id));
+ return p ?? null;
+}
+
+export async function setSharedPool(db: Db, poolId: number | null): Promise {
+ if (poolId == null) return deleteSetting(db, SHARED_POOL);
+ await getPool(db, poolId);
+ await setSetting(db, SHARED_POOL, poolId);
+}
+
+/** The user's own pool (the first one they created that is not the shared pool), or null. */
+export async function ownPool(db: Db, userId: number): Promise {
+ const shared = await sharedPool(db);
+ const rows = await db.select().from(subscriptionPools).where(eq(subscriptionPools.createdBy, userId)).orderBy(asc(subscriptionPools.id));
+ return rows.find((p) => p.id !== shared?.id) ?? null;
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d8956b45..d67c661c 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -19,6 +19,7 @@ export * from "./deploy.ts";
export * from "./platform-release.ts";
export * from "./code.ts";
export * from "./agents-md.ts";
+export * from "./project-subscription.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts
new file mode 100644
index 00000000..3e9f892f
--- /dev/null
+++ b/packages/runner/src/project-subscription.ts
@@ -0,0 +1,45 @@
+// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
+// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
+// kept encrypted like every subscription, in the owner's personal pool).
+import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, type Project, type User } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { addSubscription } from "./subscriptions.ts";
+
+async function requireOwner(db: Db, user: User, project: Project): Promise {
+ if (project.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError("Подписку проекта выбирает его владелец");
+}
+
+/** «Общая подписка Пеппы»: the project runs on the platform's shared pool. */
+export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise {
+ await requireOwner(db, user, project);
+ const pool = await sharedPool(db);
+ if (!pool) throw new PeppaError("Общая подписка не настроена — подключите свою или попросите администратора");
+ await setProjectPool(db, project.id, pool.id);
+ await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
+}
+
+/**
+ * «Своя подписка»: with a token — a new Claude subscription of the user goes into their own
+ * pool (created on first use); without one — the project just moves to the pool they already have.
+ */
+export async function connectOwnSubscription(db: Db, user: User, project: Project, token: string): Promise {
+ await requireOwner(db, user, project);
+ let pool = await ownPool(db, user.id);
+ if (token.trim()) {
+ const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
+ let name = `Claude — ${user.login}`;
+ for (let n = 2; taken.has(name); n++) name = `Claude — ${user.login} ${n}`;
+ const sub = await addSubscription(db, { provider: "claude", name, method: "token", secret: token, createdBy: user.id });
+ if (pool) {
+ const cur = (await listPools(db)).find((p) => p.id === pool!.id);
+ await updatePool(db, pool.id, { subscriptionIds: [...(cur?.subscriptionIds ?? []), sub.id] });
+ } else {
+ pool = await createPool(db, { name: `Claude — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
+ }
+ } else if (!pool) {
+ throw new PeppaError("Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат");
+ }
+ await getPool(db, pool.id);
+ await setProjectPool(db, project.id, pool.id);
+ await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", poolId: pool.id } });
+}
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 86aaf6ad..18ab2521 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -146,7 +146,7 @@ export async function startRunner(
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
// PEP-71: self-registered (eGov) users don't get this machine's login for free.
if (!sub && !sandboxed && !(await mayUseMachineLogin(db, project.ownerId))) {
- throw new PeppaError("У проекта нет пула подписок — агенты не запустятся. Попросите администратора назначить пул в «⋯ Настройки проекта»");
+ throw new PeppaError("Подписка проекта не выбрана — агенты не запустятся. Владелец выбирает общую подписку Пеппы или подключает свою в «⋯ Настройки проекта → Подписки»");
}
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError("Для запуска агента в контейнере нужна подписка: добавьте её в пул проекта (раздел «Подписки»)");
diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts
index 102d1a3c..cb624bf1 100644
--- a/packages/testkit/test/subscriptions.test.ts
+++ b/packages/testkit/test/subscriptions.test.ts
@@ -251,3 +251,44 @@ describe("Перенос токена Claude из настроек", () => {
await runner.stopSession(db, sid);
});
});
+
+describe("PEP-76: владелец выбирает подписку проекта", () => {
+ test("Scenario: общая подписка или своя; без выбора агенты самозарегистрированного не запускаются", async () => {
+ const admin = await core.upsertUserFromGitea(db, { id: 7601, login: "mock-p76-admin" }, { access_token: "x" });
+ const owner = await core.registerEgovUser(db, { iin: "850505400008", name: "ВЫБОРОВ ТЕСТ" });
+ const stranger = await core.registerEgovUser(db, { iin: "850505400018", name: "ЧУЖОЙ ТЕСТ" });
+ const p = await core.createProject(db, { slug: "mock-p76", key: "MPSUB", name: "P76", giteaOwner: "x", workspacePath: "/tmp/mock-p76", ownerId: owner.id });
+ assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не выбрана/);
+
+ // No shared pool yet → only the own one is possible.
+ await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не настроена/);
+ const sub = await runner.addSubscription(db, { provider: "claude", name: "mock-p76 общая", method: "token", secret: "sk-ant-oat01-" + "a".repeat(40), createdBy: admin.id });
+ const pool = await core.createPool(db, { name: "mock-p76 общий", subscriptionIds: [sub.id], createdBy: admin.id });
+ await core.setSharedPool(db, pool.id);
+ try {
+ await assert.rejects(runner.chooseSharedSubscription(db, stranger, p), /владелец/);
+ await runner.chooseSharedSubscription(db, owner, p);
+ assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
+ assert.equal(await core.projectAgentWarning(db, p.id), null);
+
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, ""), /Вставьте токен/);
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "не токен"), /не похоже на токен/);
+ assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 0, "a bad token leaves nothing behind");
+ await runner.connectOwnSubscription(db, owner, p, "sk-ant-oat01-" + "b".repeat(40));
+ const own = (await core.ownPool(db, owner.id))!;
+ assert.equal((await core.projectPool(db, p.id))!.id, own.id);
+ assert.equal(own.name, `Claude — ${owner.login}`);
+ const mine = (await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id);
+ assert.equal(mine.length, 1);
+ assert.equal(core.subscriptionSecret(mine[0]!), "sk-ant-oat01-" + "b".repeat(40));
+
+ // Back to shared and to own again without a token: the existing pool is reused.
+ await runner.chooseSharedSubscription(db, owner, p);
+ await runner.connectOwnSubscription(db, owner, p, "");
+ assert.equal((await core.projectPool(db, p.id))!.id, own.id);
+ assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 1);
+ } finally {
+ await core.setSharedPool(db, null);
+ }
+ });
+});
--
2.45.2
From 4729300a10d7e917967bbeb8ce270c05343d644c 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 19:50:59 +0500
Subject: [PATCH 012/428] PEP-77: progress of all stories and projects on the
Home page
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/page.tsx | 8 +-
apps/web/components/ProgressOverview.tsx | 122 ++++++++++++++++++
.../proposal.md | 14 ++
.../specs/web-workspace/spec.md | 21 +++
.../2026-11-14-pep-77-home-progress/tasks.md | 3 +
openspec/specs/web-workspace/spec.md | 20 +++
packages/core/src/index.ts | 1 +
packages/core/src/progress.ts | 77 +++++++++++
packages/testkit/test/web.test.ts | 39 ++++++
10 files changed, 304 insertions(+), 2 deletions(-)
create mode 100644 apps/web/components/ProgressOverview.tsx
create mode 100644 openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md
create mode 100644 packages/core/src/progress.ts
diff --git a/AGENTS.md b/AGENTS.md
index 3eeaba4b..0206372e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -36,6 +36,7 @@
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
- **Чаты (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-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (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`
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 81f7fc99..454e7bd9 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -1,4 +1,5 @@
-import { listUserProjects, onboardingChecklist } from "@peppa/core";
+import { listUserProjects, onboardingChecklist, progressOverview } from "@peppa/core";
+import { ProgressOverview } from "@/components/ProgressOverview";
import { OnboardingChecklist } from "@/components/Onboarding";
import { PugBanner } from "@/components/PugMascot";
import { LiveRefresh } from "@/components/LiveRefresh";
@@ -13,7 +14,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;
- const [items, sessions, projects, onboarding] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user)]);
+ 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 (
}>
@@ -24,6 +25,9 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
{items.map((q) => )}
+
все раннеры}>
{sessions.length === 0 ? Сейчас ничего не запущено. : sessions.map((s) => )}
diff --git a/apps/web/components/ProgressOverview.tsx b/apps/web/components/ProgressOverview.tsx
new file mode 100644
index 00000000..88eddb60
--- /dev/null
+++ b/apps/web/components/ProgressOverview.tsx
@@ -0,0 +1,122 @@
+import Link from "next/link";
+import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
+import { AgentBadge } from "@/components/AgentBadge";
+import { Disclosure, Empty, Key } from "@/components/common";
+import { cn } from "@/lib/utils";
+
+const PARTS = [
+ { k: "done", label: "готово", bar: "bg-ok" },
+ { k: "review", label: "ревью", bar: "bg-primary" },
+ { k: "inProgress", label: "в работе", bar: "bg-info" },
+ { k: "backlog", label: "бэклог", bar: "bg-muted-foreground/40" },
+] as const;
+
+type Counts = Pick;
+
+/** One bar split by board column: done · review · in work · backlog. */
+function StackedBar({ c, className }: { c: Counts; className?: string }) {
+ const label = PARTS.map((p) => `${p.label} ${c[p.k]}`).join(", ");
+ return (
+
+ {c.total > 0 && PARTS.map((p) => (c[p.k] ? : null))}
+
+ );
+}
+
+const pct = (c: Counts) => (c.total ? Math.round((c.done / c.total) * 100) : 0);
+
+function Legend({ c }: { c: Counts }) {
+ return (
+
+ {PARTS.map((p) => (
+
+
+ {p.label} {c[p.k]}
+
+ ))}
+
+ );
+}
+
+function ProjectRow({ p }: { p: ProjectProgress }) {
+ return (
+
+
+ {p.key}
+ {p.name}
+ {p.ownerLogin && {p.ownerLogin} }
+
+ {p.total ? (
+ <>
+ готово {p.done} из {p.total} · {pct(p)}%
+ >
+ ) : (
+ "стори пока нет"
+ )}
+
+
+
+ {p.working.length > 0 && (
+
+ {p.working.map((s) => (
+
+ {s.key}
+ {s.title}
+ {s.agent && }
+ {s.total ? (
+
+ {s.done}/{s.total}
+
+ ) : null}
+
+ ))}
+
+ )}
+ {p.reviewKeys.length > 0 && (
+
+ Ждут «Принять»:
+ {p.reviewKeys.slice(0, 8).map((k) => (
+ {k}
+ ))}
+ {p.reviewKeys.length > 8 && и ещё {p.reviewKeys.length - 8} }
+
+ )}
+
+ );
+}
+
+/** PEP-77: progress of all stories and projects on the Home page. */
+export function ProgressOverview({ data }: { data: Overview }) {
+ if (!data.mine.length && !data.others.length) return Проектов пока нет — прогресс появится с первой стори. ;
+ const t = data.totals;
+ return (
+
+ {data.mine.length > 0 && (
+
+
+ {pct(t)}%
+
+ готово {t.done} из {t.total} стори в {data.mine.length} {data.mine.length === 1 ? "проекте" : "проектах"}
+
+
+
+
+
+ )}
+
+ {data.mine.map((p) => (
+
+ ))}
+
+ {data.others.length > 0 && (
+
+
+ {data.others.map((p) => (
+
+ ))}
+
+
+ )}
+
+ );
+}
diff --git a/openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md b/openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md
new file mode 100644
index 00000000..1c315820
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md
@@ -0,0 +1,14 @@
+# PEP-77: прогресс по всем проектам на Главной
+
+## Why
+На Главной видны вопросы агентов и раннеры, но не видно, как идут дела в целом. Чтобы понять, сколько сделано и что в работе,
+приходится открывать доску каждого проекта.
+
+## What Changes
+- `progressOverview` (core/progress.ts): по проектам пользователя — число стори в колонках доски (бэклог / в работе / ревью / готово,
+ без архивных), стори в работе с агентом и прогрессом tasks.md, ключи стори, ждущих «Принять»; общий итог по своим проектам.
+ Суперадмину — отдельно проекты других (в итог не входят).
+- Раздел «Прогресс» на Главной (`components/ProgressOverview.tsx`): итог с процентом и полосой, строка на проект, «Проекты других»
+ свёрнуты.
+
+Вне scope: графики по времени (они во вкладке «Метрики» проекта). Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md
new file mode 100644
index 00000000..29292228
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md
@@ -0,0 +1,21 @@
+## ADDED Requirements
+
+### Requirement: Прогресс на Главной
+Главная SHALL показывать раздел «Прогресс»: общий итог по стори своих проектов и по каждому
+проекту — сколько стори в бэклоге, в работе, в ревью и готово, какие стори в работе (агент,
+прогресс tasks.md) и какие ждут «Принять». Архивные стори не считаются. Суперадмин SHALL
+видеть отдельно проекты других, не входящие в общий итог.
+
+#### Scenario: Свои проекты
+- **GIVEN** в проекте «PAY» 1 стори в бэклоге, 1 в работе, 1 в ревью, 1 готова и 1 в архиве
+- **WHEN** владелец открывает Главную
+- **THEN** итог — «готово 1 из 4», у «PAY» показаны стори в работе и стори, ждущая «Принять»
+
+#### Scenario: Суперадмин
+- **GIVEN** проект «TZK» другого пользователя
+- **WHEN** суперадмин открывает Главную
+- **THEN** «TZK» показан в свёрнутом блоке «Проекты других» с логином владельца, в общий итог он не входит
+
+#### Scenario: Обычный пользователь
+- **WHEN** Главную открывает пользователь без прав суперадмина
+- **THEN** блока «Проекты других» нет
diff --git a/openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md b/openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md
new file mode 100644
index 00000000..47d928df
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `progressOverview` в core
+- [x] 2 Раздел «Прогресс» на Главной
+- [x] 3 Тест в `web.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 476bfab6..34794b34 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -381,3 +381,23 @@ PM SHALL уметь убрать стори в архив и вернуть её
- **GIVEN** участник открыл редактор, а коллега тем временем закоммитил другой `AGENTS.md`
- **WHEN** участник сохраняет свою версию
- **THEN** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
+
+### Requirement: Прогресс на Главной
+Главная SHALL показывать раздел «Прогресс»: общий итог по стори своих проектов и по каждому
+проекту — сколько стори в бэклоге, в работе, в ревью и готово, какие стори в работе (агент,
+прогресс tasks.md) и какие ждут «Принять». Архивные стори не считаются. Суперадмин SHALL
+видеть отдельно проекты других, не входящие в общий итог.
+
+#### Scenario: Свои проекты
+- **GIVEN** в проекте «PAY» 1 стори в бэклоге, 1 в работе, 1 в ревью, 1 готова и 1 в архиве
+- **WHEN** владелец открывает Главную
+- **THEN** итог — «готово 1 из 4», у «PAY» показаны стори в работе и стори, ждущая «Принять»
+
+#### Scenario: Суперадмин
+- **GIVEN** проект «TZK» другого пользователя
+- **WHEN** суперадмин открывает Главную
+- **THEN** «TZK» показан в свёрнутом блоке «Проекты других» с логином владельца, в общий итог он не входит
+
+#### Scenario: Обычный пользователь
+- **WHEN** Главную открывает пользователь без прав суперадмина
+- **THEN** блока «Проекты других» нет
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a7e18ba0..0a0ededf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -21,6 +21,7 @@ export * from "./incidents.ts";
export * from "./ci.ts";
export * from "./egov.ts";
export * from "./team.ts";
+export * from "./progress.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";
diff --git a/packages/core/src/progress.ts b/packages/core/src/progress.ts
new file mode 100644
index 00000000..63a9a75c
--- /dev/null
+++ b/packages/core/src/progress.ts
@@ -0,0 +1,77 @@
+// PEP-77: progress of every project on the Home page — stories per board column and what is
+// in work right now (agent, tasks.md progress).
+import { projects, tasks, users, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, asc, eq, inArray, isNull } from "drizzle-orm";
+import { taskProgress } from "./openspec.ts";
+import { taskAgentNames } from "./team.ts";
+import { listOtherProjects, userProjectIds } from "./users.ts";
+
+export interface StoryInWork {
+ key: string;
+ title: string;
+ status: string;
+ agent: string | null;
+ /** tasks.md of the story's change: done/total and the current item. */
+ done: number | null;
+ total: number | null;
+ current: string | null;
+}
+
+export interface ProjectProgress {
+ key: string;
+ name: string;
+ /** Set for a project of somebody else (a superadmin's view). */
+ ownerLogin: string | null;
+ backlog: number;
+ inProgress: number;
+ review: number;
+ done: number;
+ total: number;
+ working: StoryInWork[];
+ /** Stories waiting for the PM's «Принять». */
+ reviewKeys: string[];
+}
+
+export interface ProgressOverview {
+ mine: ProjectProgress[];
+ /** Other people's projects — for a superadmin only. */
+ others: ProjectProgress[];
+ totals: { backlog: number; inProgress: number; review: number; done: number; total: number };
+}
+
+/** Board column of a story status (the same split as the board). */
+const column = (status: string) => (status === "backlog" ? "backlog" : status === "review" ? "review" : status === "done" ? "done" : "inProgress");
+
+export async function progressOverview(db: Db, userId: number): Promise {
+ const mineIds = await userProjectIds(db, userId);
+ const otherRows = await listOtherProjects(db, userId);
+ const ids = [...mineIds, ...otherRows.map((p) => p.id)];
+ const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 } };
+ if (!ids.length) return empty;
+ const ps = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).where(inArray(projects.id, ids)).orderBy(asc(projects.key));
+ const ts = await db.select().from(tasks).where(and(inArray(tasks.projectId, ids), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number));
+ const mine = new Set(mineIds);
+ const out = empty;
+ for (const { p, ownerLogin } of ps) {
+ const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? "без владельца"), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [] };
+ const own = ts.filter((t) => t.projectId === p.id);
+ const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map();
+ for (const t of own) {
+ const c = column(t.status);
+ row[c]++;
+ row.total++;
+ const key = formatTaskKey(p.key, t.number);
+ if (c === "review") row.reviewKeys.push(key);
+ if (c === "inProgress") {
+ const pr = taskProgress(p, t.openspecChange);
+ row.working.push({ key, title: t.title, status: t.status, agent: agentsOf.get(t.id) ?? null, done: pr?.done ?? null, total: pr?.total ?? null, current: pr?.current ?? null });
+ }
+ }
+ if (mine.has(p.id)) {
+ out.mine.push(row);
+ for (const k of ["backlog", "inProgress", "review", "done", "total"] as const) out.totals[k] += row[k];
+ } else out.others.push(row);
+ }
+ return out;
+}
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 137ad7a4..9b710bff 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -163,3 +163,42 @@ describe("PEP-74: суперадмин видит все проекты", () =>
}
});
});
+
+describe("PEP-77: прогресс по всем проектам", () => {
+ test("колонки, стори в работе, ждущие «Принять»; чужие проекты — только суперадмину", async () => {
+ const me = await core.upsertUserFromGitea(db, { id: 7701, login: "mock-p77-me" }, { access_token: "x" });
+ const other = await core.upsertUserFromGitea(db, { id: 7702, login: "mock-p77-other" }, { access_token: "x" });
+ const a = await core.createProject(db, { slug: "mock-p77a", key: "MPRA", name: "A", giteaOwner: "x", workspacePath: "/tmp/mock-p77a", ownerId: me.id });
+ const b = await core.createProject(db, { slug: "mock-p77b", key: "MPRB", name: "B", giteaOwner: "x", workspacePath: "/tmp/mock-p77b", ownerId: other.id });
+ const mk = async (projectId: number, title: string, status?: "in_progress" | "review" | "done") => {
+ const t = await core.createTask(db, { projectId, title });
+ if (status) await core.updateTask(db, t, { status });
+ return t;
+ };
+ await mk(a.id, "бэклог");
+ const w = await mk(a.id, "в работе", "in_progress");
+ const r = await mk(a.id, "ревью", "review");
+ await mk(a.id, "готово", "done");
+ const archived = await mk(a.id, "в архиве", "done");
+ await core.setTaskArchived(db, archived, true);
+ await mk(b.id, "чужая", "done");
+
+ const mine = await core.progressOverview(db, me.id);
+ assert.deepEqual(mine.totals, { backlog: 1, inProgress: 1, review: 1, done: 1, total: 4 }, "archived stories are not counted");
+ assert.deepEqual(mine.mine.map((p) => p.key), ["MPRA"]);
+ assert.deepEqual(mine.others, []);
+ assert.deepEqual(mine.mine[0]!.working.map((s) => s.key), [w.key]);
+ assert.deepEqual(mine.mine[0]!.reviewKeys, [r.key]);
+
+ await core.setPlatformAdmins(db, ["mock-p77-me"]);
+ try {
+ const boss = await core.progressOverview(db, me.id);
+ const row = boss.others.find((p) => p.key === "MPRB")!;
+ assert.equal(row.ownerLogin, "mock-p77-other");
+ assert.equal(row.done, 1);
+ assert.equal(boss.totals.total, 4, "totals — own projects only");
+ } finally {
+ await core.setPlatformAdmins(db, null);
+ }
+ });
+});
--
2.45.2
From 335b8b159ed760b295f0557eced19ec14af2a5f0 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 20:02:16 +0500
Subject: [PATCH 013/428] PEP-78: the action error stays in view while the page
is scrolled
Co-Authored-By: Claude Fable 5.2
---
apps/web/components/common.tsx | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx
index ace2ab0a..bcfc1be4 100644
--- a/apps/web/components/common.tsx
+++ b/apps/web/components/common.tsx
@@ -62,7 +62,8 @@ export function StatusBadge({ status, kind = "task" }: { status: string; kind?:
export function Flash({ error }: { error?: string }) {
return error ? (
-
+ // Sticky: an action far down the page (a board card, «Принять») must not fail silently above the fold.
+
{error}
--
2.45.2
From 6066ce8763107cd4dc437a90a3f0cb0082e8d26c 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 20:14:40 +0500
Subject: [PATCH 014/428] PEP-60: mock-telegram rejects posts only to channels
added with addChannel (supergroups of PEP-62 keep working)
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/src/mock-telegram.ts | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 27d12638..61a7bb33 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -116,12 +116,11 @@ export class MockTelegram {
return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
}
case "sendMessage": {
- // Channels (-100…): the bot must be an admin that may post.
- if (String(p.chat_id).startsWith("-100")) {
- const c = this.channels.get(Number(p.chat_id));
- if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
- if (c.bot !== "administrator" || !c.canPost) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
- }
+ // Channels added with addChannel: the bot must be an admin that may post. Other «-100…»
+ // ids are supergroups (PEP-62) and accept messages as before.
+ const ch = this.channels.get(Number(p.chat_id));
+ if (ch && ch.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (ch && (ch.bot !== "administrator" || !ch.canPost)) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
const m: MockTgMessage = {
message_id: this.nextMessageId++,
chat_id: Number(p.chat_id),
--
2.45.2
From e9526c9329e48c6610c17e1b5634c98cca2bbffa 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 20:15:22 +0500
Subject: [PATCH 015/428] =?UTF-8?q?PEP-79,=20PEP-80:=20new=20projects=20pi?=
=?UTF-8?q?ck=20stories=20themselves;=20own=20subscription=20=E2=80=94=20C?=
=?UTF-8?q?laude=20or=20ChatGPT?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 2 +
apps/web/app/(app)/actions.ts | 8 ++-
apps/web/app/(app)/help/page.tsx | 3 +-
apps/web/app/(app)/p/[key]/page.tsx | 34 +++++++++--
.../proposal.md | 15 +++++
.../specs/agent-credentials/spec.md | 19 ++++++
.../specs/project-autonomy/spec.md | 16 +++++
.../tasks.md | 3 +
openspec/specs/agent-credentials/spec.md | 18 ++++++
openspec/specs/project-autonomy/spec.md | 15 +++++
packages/core/src/autonomy.ts | 10 ++-
packages/core/src/onboarding.ts | 2 +-
packages/runner/src/autonomy.ts | 3 +
packages/runner/src/project-subscription.ts | 61 +++++++++++++++----
packages/runner/src/provision.ts | 4 +-
packages/runner/src/sessions.ts | 2 +-
packages/testkit/test/subscriptions.test.ts | 35 +++++++++--
17 files changed, 220 insertions(+), 30 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index 0206372e..5d5861c5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -37,6 +37,8 @@
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
- **Чаты (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-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (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`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index ec2e9d6c..39782563 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, chooseSharedSubscription } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -672,6 +672,10 @@ export async function chooseSharedSubscriptionAction(f: FormData) {
export async function connectOwnSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
- await connectOwnSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), String(f.get("token") ?? ""));
+ const kind = str(f, "kind") as OwnSubscriptionKind;
+ if (!["claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
+ return `/p/${p.key}?settings=subscription`;
});
}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 64f0a746..223f267c 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,7 +70,8 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
- Подписка проекта — на чём работают агенты, выбирает владелец в «⋯ Настройки проекта → Подписки»: «Общая подписка Пеппы» или своя подписка Claude (токен команды claude setup-token на своём компьютере). Пока выбор не сделан, проект нового пользователя агентов не запускает.
+ Подписка проекта — на чём работают агенты. Владелец подключает свою в «⋯ Настройки проекта → Подписки»: Claude (токен команды claude setup-token ), ChatGPT (вход по ссылке и коду) или ключ OpenAI API. Пока подписки нет, агенты проекта не запускаются.
+ Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 16ce033c..8119e0a9 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
-import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
+import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -107,6 +107,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
// PEP-31: the project's pool has no working subscription — agents won't start.
const agentWarning = await projectAgentWarning(db, p.id);
+ // PEP-80: the owner's own subscriptions — a ChatGPT device login in progress, and whether a pool exists already.
+ const mayChoose = isOwner || superadmin;
+ const [ownLogins, hasOwnPool] = await Promise.all([mayChoose && pool ? ownPendingLogins(db, pool.id) : Promise.resolve([]), mayChoose ? ownPool(db, user.id).then((x) => !!x) : Promise.resolve(false)]);
// Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
@@ -308,12 +311,33 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Общая подписка Пеппы
)}
+ {ownLogins.map((l) => (
+
+
Вход в ChatGPT не завершён
+
+ 1. Откройте {l.url} и войдите в свой ChatGPT.
+
+ {l.code && (
+
+ 2. Введите код {l.code}
+
+ )}
+
Потом обновите эту страницу — подписка станет активной.
+
+ ))}
-
- Своя подписка Claude
+
+ Claude — токен (claude setup-token)
+ ChatGPT — вход по ссылке и коду
+ Codex — ключ OpenAI API
+ {hasOwnPool && Моя уже подключённая подписка }
+
+
+ Подключить свою подписку
- Токен выдаёт команда claude setup-token на вашем компьютере. Хранится зашифрованным, показать его нельзя. Уже подключали — оставьте поле пустым.
+ Claude: выполните claude setup-token на своём компьютере и вставьте токен. ChatGPT: поле оставьте пустым — появится ссылка и код для входа. Токены и ключи
+ хранятся зашифрованными, показать их нельзя.
>
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md
new file mode 100644
index 00000000..dcea9824
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md
@@ -0,0 +1,15 @@
+# PEP-79 / PEP-80: стори берутся сами; своя подписка Claude или ChatGPT
+
+## Why
+PM: пользователь-непрограммист не должен перетаскивать карточки, чтобы агент начал работать. И новые пользователи должны
+работать на своих подписках (Claude или ChatGPT), а не на подписке PM.
+
+## What Changes
+- PEP-79: уровень автономности «Сам берёт» (`self`: pick=auto, мерж и приёмка за PM). Новый проект создаётся с ним
+ (`NEW_PROJECT_AUTONOMY` в `provisionProject`); существующие проекты не меняются. Диспетчер ничего не запускает и никого не
+ пингует, пока у проекта есть предупреждение «Агенты не запустятся» (подписка не подключена или не работает).
+- PEP-80: `connectOwnSubscription(kind)`: `claude` (токен), `codex_login` (ChatGPT — device-вход Codex; ссылку и код показывает
+ панель «Подписки» проекта, `ownPendingLogins`), `codex_key` (ключ OpenAI API), `existing` (уже подключённый пул). Личный пул —
+ «Подписки — <логин>». Общая подписка остаётся возможностью суперадмина (`platform.shared_pool`), на живой системе выключена.
+
+Вне scope: подписки OpenCode у пользователей. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..7205c721
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md
@@ -0,0 +1,19 @@
+## ADDED Requirements
+
+### Requirement: Своя подписка Claude или ChatGPT
+Владелец проекта SHALL подключать свою подписку: Claude по токену, ChatGPT входом по ссылке
+и одноразовому коду, либо Codex по ключу OpenAI API. Подписки пользователя SHALL собираться
+в его личный пул, который можно назначить и другим его проектам.
+
+#### Scenario: ChatGPT
+- **WHEN** владелец выбирает «ChatGPT — вход по ссылке и коду» и нажимает «Подключить свою подписку»
+- **THEN** панель «Подписки» показывает ссылку и код; после входа и обновления страницы подписка активна
+
+#### Scenario: Уже подключённая
+- **GIVEN** у владельца есть личный пул
+- **WHEN** в другом своём проекте он выбирает «Моя уже подключённая подписка»
+- **THEN** проект работает на этом пуле, новая подписка не создаётся
+
+#### Scenario: Пустой токен Claude
+- **WHEN** владелец выбирает Claude и не вставляет токен
+- **THEN** подключение отклонено с подсказкой про `claude setup-token`
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md
new file mode 100644
index 00000000..0f5274a6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Новый проект берёт стори сам
+Новый проект SHALL создаваться с уровнем автономности «Сам берёт»: диспетчер берёт стори из
+бэклога по порядку доски, результат принимает PM. Пока у проекта нет рабочей подписки,
+диспетчер SHALL NOT запускать стори и беспокоить PM.
+
+#### Scenario: Стори без перетаскивания
+- **GIVEN** новый проект с подключённой подпиской
+- **WHEN** пользователь создаёт стори
+- **THEN** агент берёт её из бэклога сам, карточка переходит «В работу»
+
+#### Scenario: Подписка не подключена
+- **GIVEN** новый проект без подписки и стори в бэклоге
+- **WHEN** проходит тик диспетчера
+- **THEN** стори остаётся в бэклоге, вопросов PM не появляется
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md
new file mode 100644
index 00000000..98865924
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 Уровень `self`, `NEW_PROJECT_AUTONOMY`, новый проект создаётся с ним; диспетчер молчит без подписки
+- [x] 2 `connectOwnSubscription` с видами подписки, `ownPendingLogins`, панель «Подписки»
+- [x] 3 Тесты `subscriptions.test.ts`, `openspec validate`
diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md
index 5531053c..c586dae1 100644
--- a/openspec/specs/agent-credentials/spec.md
+++ b/openspec/specs/agent-credentials/spec.md
@@ -121,3 +121,21 @@ Claude и делать пул с этой подпиской пулом по у
#### Scenario: Не владелец
- **WHEN** участник проекта, не владелец и не суперадмин, пытается сменить подписку
- **THEN** действие отклонено
+
+### Requirement: Своя подписка Claude или ChatGPT
+Владелец проекта SHALL подключать свою подписку: Claude по токену, ChatGPT входом по ссылке
+и одноразовому коду, либо Codex по ключу OpenAI API. Подписки пользователя SHALL собираться
+в его личный пул, который можно назначить и другим его проектам.
+
+#### Scenario: ChatGPT
+- **WHEN** владелец выбирает «ChatGPT — вход по ссылке и коду» и нажимает «Подключить свою подписку»
+- **THEN** панель «Подписки» показывает ссылку и код; после входа и обновления страницы подписка активна
+
+#### Scenario: Уже подключённая
+- **GIVEN** у владельца есть личный пул
+- **WHEN** в другом своём проекте он выбирает «Моя уже подключённая подписка»
+- **THEN** проект работает на этом пуле, новая подписка не создаётся
+
+#### Scenario: Пустой токен Claude
+- **WHEN** владелец выбирает Claude и не вставляет токен
+- **THEN** подключение отклонено с подсказкой про `claude setup-token`
diff --git a/openspec/specs/project-autonomy/spec.md b/openspec/specs/project-autonomy/spec.md
index 28582511..3266f29d 100644
--- a/openspec/specs/project-autonomy/spec.md
+++ b/openspec/specs/project-autonomy/spec.md
@@ -110,3 +110,18 @@ PM SHALL получить один вопрос «Агенты простаив
- **GIVEN** автономность «авто», WIP 1, PAY-1 ждёт PAY-2, PAY-1 выше в бэклоге
- **WHEN** вачдог запускает диспетчер
- **THEN** агент запускается на PAY-2, PAY-1 остаётся в бэклоге до ревью PAY-2
+
+### Requirement: Новый проект берёт стори сам
+Новый проект SHALL создаваться с уровнем автономности «Сам берёт»: диспетчер берёт стори из
+бэклога по порядку доски, результат принимает PM. Пока у проекта нет рабочей подписки,
+диспетчер SHALL NOT запускать стори и беспокоить PM.
+
+#### Scenario: Стори без перетаскивания
+- **GIVEN** новый проект с подключённой подпиской
+- **WHEN** пользователь создаёт стори
+- **THEN** агент берёт её из бэклога сам, карточка переходит «В работу»
+
+#### Scenario: Подписка не подключена
+- **GIVEN** новый проект без подписки и стори в бэклоге
+- **WHEN** проходит тик диспетчера
+- **THEN** стори остаётся в бэклоге, вопросов PM не появляется
diff --git a/packages/core/src/autonomy.ts b/packages/core/src/autonomy.ts
index 48427d8a..ccf3b59a 100644
--- a/packages/core/src/autonomy.ts
+++ b/packages/core/src/autonomy.ts
@@ -32,7 +32,7 @@ export interface AutonomySettings {
quietTo: number | null;
}
-export type AutonomyLevel = "manual" | "assisted" | "auto";
+export type AutonomyLevel = "manual" | "assisted" | "self" | "auto";
const BASE: AutonomySettings = {
pick: "pm",
@@ -53,6 +53,9 @@ export const AUTONOMY_LEVELS: Record = {
manual: BASE,
// The PM still decides, but Peppa pushes when agents idle with a non-empty backlog.
assisted: { ...BASE, idlePush: true },
+ // PEP-79: nobody drags cards — the dispatcher takes stories from the backlog; the PM still
+ // accepts the result. The default of a new project.
+ self: { ...BASE, pick: "auto" },
// Backlog → Done without a human: dispatcher, auto-merge, closing after the merge.
auto: { ...BASE, pick: "auto", merge: "auto", close: "after_merge", idlePush: true },
};
@@ -60,6 +63,7 @@ export const AUTONOMY_LEVELS: Record = {
export const AUTONOMY_LEVEL_RU: Record = {
manual: "Ручной",
assisted: "С подсказками",
+ self: "Сам берёт",
auto: "Автомат",
custom: "Свой",
};
@@ -67,9 +71,13 @@ export const AUTONOMY_LEVEL_RU: Record = {
export const AUTONOMY_LEVEL_HINT: Record = {
manual: "PM двигает карточки и принимает стори; при простое Пеппа молчит.",
assisted: "PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас».",
+ self: "Стори берутся из бэклога сами, по порядку на доске; результат принимаете вы («Принять» в ревью).",
auto: "Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера.",
};
+/** PEP-79: what a newly created project starts with (existing projects keep their settings). */
+export const NEW_PROJECT_AUTONOMY: AutonomySettings = AUTONOMY_LEVELS.self;
+
const key = (projectId: number) => `project.autonomy:${projectId}`;
export function autonomyLevel(s: AutonomySettings): AutonomyLevel | "custom" {
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index dcf895e1..6acd1c38 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -82,7 +82,7 @@ export async function projectAgentWarning(db: Db, projectId: number, now = new D
if (p?.poolId == null) {
// PEP-71/76: a self-registered owner has no machine login — a subscription must be chosen.
const [o] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
- return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не выбрана — владелец выбирает общую или подключает свою в «⋯ Настройки проекта → Подписки»";
+ return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не подключена — владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»";
}
const subs = await poolSubscriptions(db, p.poolId);
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts
index 02823dad..dcb8b267 100644
--- a/packages/runner/src/autonomy.ts
+++ b/packages/runner/src/autonomy.ts
@@ -31,6 +31,7 @@ import {
type SessionView,
type Task,
type TaskRef,
+ projectAgentWarning,
} from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -243,6 +244,8 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
const limited = sessions.some((s) => s.status === "rate_limited") || (await projectPoolExhausted(db, project.id, now));
if (a.pick === "auto") {
+ // PEP-79: no subscription chosen (or none works) — the project page says so; no retries, no pings.
+ if (await projectAgentWarning(db, project.id, now)) return;
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
// PEP-10: stories waiting in runner queues count as taken.
let slots = a.wipLimit - working.length - (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length;
diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts
index 3e9f892f..3e85f600 100644
--- a/packages/runner/src/project-subscription.ts
+++ b/packages/runner/src/project-subscription.ts
@@ -1,8 +1,9 @@
// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
// kept encrypted like every subscription, in the owner's personal pool).
-import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, type Project, type User } from "@peppa/core";
+import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, type Project, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
+import { pendingLogin, pollCodexLogin } from "./subscription-login.ts";
import { addSubscription } from "./subscriptions.ts";
async function requireOwner(db: Db, user: User, project: Project): Promise {
@@ -18,28 +19,64 @@ export async function chooseSharedSubscription(db: Db, user: User, project: Proj
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
}
+export type OwnSubscriptionKind = "claude" | "codex_login" | "codex_key" | "existing";
+
+const OWN_NAMES: Record, string> = { claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
+
/**
- * «Своя подписка»: with a token — a new Claude subscription of the user goes into their own
- * pool (created on first use); without one — the project just moves to the pool they already have.
+ * «Своя подписка» (PEP-76/80): a new subscription of the user goes into their own pool (created on
+ * first use) — Claude by a `claude setup-token` token, ChatGPT by the Codex device login (the
+ * page then shows the link and the one-time code), Codex by an OpenAI API key; "existing" just
+ * moves the project to the pool the user already has.
*/
-export async function connectOwnSubscription(db: Db, user: User, project: Project, token: string): Promise {
+export async function connectOwnSubscription(db: Db, user: User, project: Project, kind: OwnSubscriptionKind, secret = ""): Promise<{ subscriptionId: number | null }> {
await requireOwner(db, user, project);
let pool = await ownPool(db, user.id);
- if (token.trim()) {
+ let subscriptionId: number | null = null;
+ if (kind === "existing") {
+ if (!pool) throw new PeppaError("Своей подписки ещё нет — подключите Claude или ChatGPT");
+ } else {
+ if (kind !== "codex_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API");
const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
- let name = `Claude — ${user.login}`;
- for (let n = 2; taken.has(name); n++) name = `Claude — ${user.login} ${n}`;
- const sub = await addSubscription(db, { provider: "claude", name, method: "token", secret: token, createdBy: user.id });
+ const base = `${OWN_NAMES[kind]} — ${user.login}`;
+ let name = base;
+ for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
+ const sub =
+ kind === "claude"
+ ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id })
+ : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id });
+ subscriptionId = sub.id;
if (pool) {
const cur = (await listPools(db)).find((p) => p.id === pool!.id);
await updatePool(db, pool.id, { subscriptionIds: [...(cur?.subscriptionIds ?? []), sub.id] });
} else {
- pool = await createPool(db, { name: `Claude — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
+ pool = await createPool(db, { name: `Подписки — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
}
- } else if (!pool) {
- throw new PeppaError("Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат");
}
await getPool(db, pool.id);
await setProjectPool(db, project.id, pool.id);
- await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", poolId: pool.id } });
+ await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", kind, poolId: pool.id } });
+ return { subscriptionId };
+}
+
+export interface OwnLogin {
+ subscriptionId: number;
+ name: string;
+ url: string;
+ code: string | null;
+}
+
+/**
+ * Device logins of the pool's subscriptions still waiting for the user (ChatGPT: open the link,
+ * enter the code). Polls Codex first, so a finished login turns the subscription active.
+ */
+export async function ownPendingLogins(db: Db, poolId: number): Promise {
+ const out: OwnLogin[] = [];
+ for (const s of await poolSubscriptions(db, poolId)) {
+ if (s.provider !== "codex" || s.status !== "pending") continue;
+ if ((await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue;
+ const l = await pendingLogin(db, s.id);
+ if (l) out.push({ subscriptionId: s.id, name: s.name, url: l.url, code: l.code ?? null });
+ }
+ return out;
}
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index 741e3d48..c8e511de 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -4,7 +4,7 @@
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { createProject, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
+import { createProject, NEW_PROJECT_AUTONOMY, setAutonomy, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { eq, or } from "drizzle-orm";
@@ -129,6 +129,8 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise log(`ci: ${(e as Error).message}`));
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 18ab2521..c4539939 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -146,7 +146,7 @@ export async function startRunner(
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
// PEP-71: self-registered (eGov) users don't get this machine's login for free.
if (!sub && !sandboxed && !(await mayUseMachineLogin(db, project.ownerId))) {
- throw new PeppaError("Подписка проекта не выбрана — агенты не запустятся. Владелец выбирает общую подписку Пеппы или подключает свою в «⋯ Настройки проекта → Подписки»");
+ throw new PeppaError("Подписка проекта не подключена — агенты не запустятся. Владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»");
}
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError("Для запуска агента в контейнере нужна подписка: добавьте её в пул проекта (раздел «Подписки»)");
diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts
index cb624bf1..0084dc47 100644
--- a/packages/testkit/test/subscriptions.test.ts
+++ b/packages/testkit/test/subscriptions.test.ts
@@ -258,7 +258,7 @@ describe("PEP-76: владелец выбирает подписку проек
const owner = await core.registerEgovUser(db, { iin: "850505400008", name: "ВЫБОРОВ ТЕСТ" });
const stranger = await core.registerEgovUser(db, { iin: "850505400018", name: "ЧУЖОЙ ТЕСТ" });
const p = await core.createProject(db, { slug: "mock-p76", key: "MPSUB", name: "P76", giteaOwner: "x", workspacePath: "/tmp/mock-p76", ownerId: owner.id });
- assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не выбрана/);
+ assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не подключена/);
// No shared pool yet → only the own one is possible.
await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не настроена/);
@@ -271,24 +271,47 @@ describe("PEP-76: владелец выбирает подписку проек
assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
assert.equal(await core.projectAgentWarning(db, p.id), null);
- await assert.rejects(runner.connectOwnSubscription(db, owner, p, ""), /Вставьте токен/);
- await assert.rejects(runner.connectOwnSubscription(db, owner, p, "не токен"), /не похоже на токен/);
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", ""), /Вставьте токен/);
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", "не токен"), /не похоже на токен/);
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 0, "a bad token leaves nothing behind");
- await runner.connectOwnSubscription(db, owner, p, "sk-ant-oat01-" + "b".repeat(40));
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "existing"), /ещё нет/);
+ await runner.connectOwnSubscription(db, owner, p, "claude", "sk-ant-oat01-" + "b".repeat(40));
const own = (await core.ownPool(db, owner.id))!;
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
- assert.equal(own.name, `Claude — ${owner.login}`);
+ assert.equal(own.name, `Подписки — ${owner.login}`);
const mine = (await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id);
assert.equal(mine.length, 1);
assert.equal(core.subscriptionSecret(mine[0]!), "sk-ant-oat01-" + "b".repeat(40));
// Back to shared and to own again without a token: the existing pool is reused.
await runner.chooseSharedSubscription(db, owner, p);
- await runner.connectOwnSubscription(db, owner, p, "");
+ await runner.connectOwnSubscription(db, owner, p, "existing");
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 1);
+
+ // PEP-80: ChatGPT by the Codex device login — the subscription waits, the page gets the link and the code.
+ const { subscriptionId } = await runner.connectOwnSubscription(db, owner, p, "codex_login");
+ const logins = await runner.ownPendingLogins(db, own.id);
+ assert.equal(logins.length, 1);
+ assert.equal(logins[0]!.subscriptionId, subscriptionId);
+ assert.match(logins[0]!.url, /^https:\/\//);
+ assert.ok(logins[0]!.code);
+ await runner.cancelLogin(db, subscriptionId!);
} finally {
await core.setSharedPool(db, null);
}
});
+
+ test("PEP-79: «Сам берёт» — диспетчер молчит, пока подписка не подключена", async () => {
+ assert.equal(core.autonomyLevel(core.NEW_PROJECT_AUTONOMY), "self");
+ assert.equal(core.NEW_PROJECT_AUTONOMY.pick, "auto");
+ assert.equal(core.NEW_PROJECT_AUTONOMY.merge, "manual");
+ const owner = await core.registerEgovUser(db, { iin: "850505400028", name: "САМОВ БЕРЁТ" });
+ const p = await core.createProject(db, { slug: "mock-p79", key: "MPSLF", name: "P79", giteaOwner: "x", workspacePath: "/tmp/mock-p79", ownerId: owner.id });
+ await core.setAutonomy(db, p.id, core.NEW_PROJECT_AUTONOMY);
+ const t = await core.createTask(db, { projectId: p.id, title: "первая" });
+ await runner.autonomyTick(db, { log: () => {} });
+ assert.equal((await core.resolveTask(db, t.key)).task.status, "backlog", "not started without a subscription");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "and nobody is pinged about it");
+ });
});
--
2.45.2
From 63576a9845a86df5015dd812dc9b7b4b53bc3bfe 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 21:06:36 +0500
Subject: [PATCH 016/428] PEP-81: epics tab and the epic label on board cards
(WIP, not verified in the browser)
Co-Authored-By: Claude Fable 5.2
---
apps/web/app/(app)/p/[key]/page.tsx | 18 +++++--
apps/web/app/(app)/p/[key]/tabs.tsx | 75 +++++++++++++++++++++++++++++
apps/web/components/Board.tsx | 1 +
3 files changed, 91 insertions(+), 3 deletions(-)
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 16ce033c..006bd07c 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -22,7 +22,7 @@ import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
-import { AgentsMdTab, CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
+import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
import { saveProjectBudgetAction } from "../../actions";
@@ -37,6 +37,7 @@ const RELEASE_STATUS: RecordСоздать стори
);
- const tabCount: Partial> = { board: tasks.length, bugs: incidents.length, sessions: sessions.length };
+ const tabCount: Partial> = { board: tasks.length, epics: epics.length, bugs: incidents.length, sessions: sessions.length };
return (
@@ -412,7 +413,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<>
{epics.length > 0 && (
- Эпик:
+ Эпики:
{[{ id: 0, title: "все" }, ...epics].map((e) => {
const active = (epicFilter?.id ?? 0) === e.id;
return (
@@ -443,6 +444,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
>
)}
+ {tab === "epics" && (
+ ({ key: `${p.key}-${t.number}`, title: t.title, status: t.status, goalId: t.goalId }))}
+ progress={progress}
+ back={back}
+ />
+ )}
+
{tab === "code" && code && }
{tab === "specs" && (
diff --git a/apps/web/app/(app)/p/[key]/tabs.tsx b/apps/web/app/(app)/p/[key]/tabs.tsx
index 24bcc62b..bcf057be 100644
--- a/apps/web/app/(app)/p/[key]/tabs.tsx
+++ b/apps/web/app/(app)/p/[key]/tabs.tsx
@@ -312,3 +312,78 @@ const AGENTS_MD_STARTER = `# AGENTS.md
- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
`;
+
+interface EpicStory {
+ key: string;
+ title: string;
+ status: string;
+ goalId: number | null;
+}
+
+/** PEP-81: epics in plain sight — each epic (a big goal) with its stories (the steps agents do). */
+export function EpicsTab({ projectId, projectKey, epics, stories, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; stories: EpicStory[]; progress: Map; back: string }) {
+ const loose = stories.filter((s) => !s.goalId || !epics.some((e) => e.id === s.goalId));
+ const list = (items: EpicStory[]) =>
+ items.length ? (
+
+ {items.map((s) => (
+
+ {s.key}
+ {s.title}
+
+
+ ))}
+
+ ) : (
+ Стори пока нет.
+ );
+ return (
+
+ );
+}
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index 248c244b..de1fc025 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -198,6 +198,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
)}
{card.epic && (
+ эпик
{card.epic}
)}
--
2.45.2
From 1afc95117dea6694fcb879eaaf23dbf0f943028b 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 21:09:42 +0500
Subject: [PATCH 017/428] =?UTF-8?q?PEP-82:=20connect=20your=20own=20Claude?=
=?UTF-8?q?=20or=20ChatGPT=20on=20the=20project=20page=20=E2=80=94=20a=20l?=
=?UTF-8?q?ink=20and=20a=20code,=20no=20terminal?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 22 ++++-
apps/web/app/(app)/help/page.tsx | 2 +-
apps/web/app/(app)/p/[key]/page.tsx | 27 ++----
apps/web/components/SubscriptionSetup.tsx | 90 +++++++++++++++++++
.../proposal.md | 15 ++++
.../specs/agent-credentials/spec.md | 20 +++++
.../tasks.md | 3 +
openspec/specs/agent-credentials/spec.md | 19 ++++
packages/runner/src/project-subscription.ts | 57 +++++++++---
packages/testkit/test/subscriptions.test.ts | 27 ++++++
11 files changed, 247 insertions(+), 36 deletions(-)
create mode 100644 apps/web/components/SubscriptionSetup.tsx
create mode 100644 openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index f813325a..7b2facdf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -39,6 +39,7 @@
- **Прогресс на Главной (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-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-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (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`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 39782563..a3c00ac2 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -673,9 +673,25 @@ export async function connectOwnSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const kind = str(f, "kind") as OwnSubscriptionKind;
- if (!["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("Выберите, что подключить");
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
- return `/p/${p.key}?settings=subscription`;
+ });
+}
+
+/** PEP-82: step 3 of the Claude sign-in on the project page. */
+export async function finishOwnClaudeLoginAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"));
+ });
+}
+
+export async function cancelOwnLoginAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await cancelOwnLogin(db, user, p, Number(str(f, "subscriptionId")));
});
}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 5763b9d9..32b54396 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,7 +70,7 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
- Подписка проекта — на чём работают агенты. Владелец подключает свою в «⋯ Настройки проекта → Подписки»: Claude (токен команды claude setup-token ), ChatGPT (вход по ссылке и коду) или ключ OpenAI API. Пока подписки нет, агенты проекта не запускаются.
+ Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 8119e0a9..7b5dfc47 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -17,6 +17,7 @@ import { Input, NativeSelect, Textarea } from "@/components/ui/input";
import { SettingsDialog } from "@/components/SettingsDialog";
import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
import { Workspace } from "@/components/Workspace";
+import { SubscriptionSetup } from "@/components/SubscriptionSetup";
import { requireUser } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
@@ -311,32 +312,19 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Общая подписка Пеппы
)}
- {ownLogins.map((l) => (
-
-
Вход в ChatGPT не завершён
-
- 1. Откройте {l.url} и войдите в свой ChatGPT.
-
- {l.code && (
-
- 2. Введите код {l.code}
-
- )}
-
Потом обновите эту страницу — подписка станет активной.
-
- ))}
-
- Claude — токен (claude setup-token)
+
+ Claude — вход по ссылке
ChatGPT — вход по ссылке и коду
+ Claude — готовый токен (claude setup-token)
Codex — ключ OpenAI API
{hasOwnPool && Моя уже подключённая подписка }
-
+
Подключить свою подписку
- Claude: выполните claude setup-token на своём компьютере и вставьте токен. ChatGPT: поле оставьте пустым — появится ссылка и код для входа. Токены и ключи
+ Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт claude setup-token на вашем компьютере. Токены и ключи
хранятся зашифрованными, показать их нельзя.
@@ -408,7 +396,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{repo.fullName} · {repoVisibilityLabel(repo.private)}
- {agentWarning && (
+ {mayChoose && (ownLogins.length > 0 || (!pool && agentWarning)) && }
+ {agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool)) && (
Агенты не запустятся: {agentWarning}.
{pool ? (superadmin ? Подписки → : Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её. ) : null}
diff --git a/apps/web/components/SubscriptionSetup.tsx b/apps/web/components/SubscriptionSetup.tsx
new file mode 100644
index 00000000..39db9d06
--- /dev/null
+++ b/apps/web/components/SubscriptionSetup.tsx
@@ -0,0 +1,90 @@
+import { ExternalLink } from "lucide-react";
+import type { OwnLogin } from "@peppa/runner";
+import { cancelOwnLoginAction, connectOwnSubscriptionAction, finishOwnClaudeLoginAction } from "@/app/(app)/actions";
+import { Hidden } from "@/components/cards";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+
+const step = "flex gap-2.5";
+const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary";
+
+/**
+ * PEP-82: connecting the owner's own subscription without a terminal, in plain steps, right on
+ * the project page — «Подключить Claude» / «Подключить ChatGPT», then the link and the code.
+ */
+export function SubscriptionSetup({ projectId, back, logins }: { projectId: number; back: string; logins: OwnLogin[] }) {
+ if (logins.length) {
+ return (
+
+ {logins.map((l) => (
+
+ Подключаем {l.provider === "claude" ? "Claude" : "ChatGPT"} — осталось {l.provider === "claude" ? "три шага" : "два шага"}
+
+
1
+
+
Откройте страницу входа и войдите в свой аккаунт {l.provider === "claude" ? "Claude" : "ChatGPT"}{l.provider === "claude" ? ", затем нажмите «Authorize»" : ""}.
+
+
+ Открыть страницу входа
+
+
+
+
+ {l.provider === "claude" ? (
+ <>
+
+ 2
+ Claude покажет длинный код — нажмите «Copy code».
+
+
+ 3
+
+
+
+ Готово
+
+
+ >
+ ) : (
+
+ )}
+
+
+ Отменить и начать заново
+
+
+ ))}
+
+ );
+ }
+ return (
+
+ Подключите подписку — и агенты начнут работать
+
+ Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Это одна минута: вы входите в свой аккаунт, как на любом сайте. Пароль
+ Пеппа не видит.
+
+
+
+
+ Подключить Claude
+
+
+
+ Подключить ChatGPT
+
+
+ Нет подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) — в «⋯ Настройки проекта → Подписки».
+
+ );
+}
diff --git a/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md
new file mode 100644
index 00000000..8141c478
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md
@@ -0,0 +1,15 @@
+# PEP-82: подключение своей подписки понятно непрограммисту
+
+## Why
+Новый пользователь не понимает, как подключить свою подписку Claude: форма спрятана в настройках проекта и просит токен
+команды `claude setup-token`, то есть требует терминал и установленный Claude Code.
+
+## What Changes
+- Вход в Claude без терминала: вид подписки `claude_login` — Пеппа сама запускает `claude setup-token` на сервере и даёт
+ ссылку; пользователь входит в свой Claude, копирует код и вставляет его (`finishOwnClaudeLogin`). «Отменить и начать заново» —
+ `cancelOwnLogin` (последняя ожидающая подписка ушла — проект снова без пула).
+- Мастер `SubscriptionSetup` прямо на странице проекта вместо предупреждения «Агенты не запустятся», когда подписки нет:
+ «Подключить Claude» / «Подключить ChatGPT», затем шаги со ссылкой и кодом. Видят владелец и суперадмин.
+- `ownPendingLogins` отдаёт и входы Claude; форма в «⋯ Настройки проекта → Подписки» остаётся для готового токена и ключа API.
+
+Вне scope: вставка кода за пользователя, подписки OpenCode. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..ff0bfe66
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md
@@ -0,0 +1,20 @@
+## ADDED Requirements
+
+### Requirement: Подключение подписки без терминала
+Страница проекта без подписки SHALL показывать владельцу мастер подключения: кнопки
+«Подключить Claude» и «Подключить ChatGPT» и дальше шаги со ссылкой на вход. Для Claude
+пользователь SHALL завершать вход кодом, который Claude показывает после входа.
+
+#### Scenario: Claude по ссылке
+- **GIVEN** проект нового пользователя без подписки
+- **WHEN** владелец нажимает «Подключить Claude», открывает ссылку, входит и вставляет код в мастер
+- **THEN** подписка активна, мастер исчезает, агенты проекта могут запускаться
+
+#### Scenario: Отмена
+- **GIVEN** вход начат, код ещё не введён
+- **WHEN** владелец нажимает «Отменить и начать заново»
+- **THEN** ожидающая подписка удалена, мастер снова предлагает подключить Claude или ChatGPT
+
+#### Scenario: Чужой код
+- **WHEN** код для входа пытается ввести не владелец проекта и не суперадмин
+- **THEN** действие отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md
new file mode 100644
index 00000000..42dc77e9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `claude_login`, `finishOwnClaudeLogin`, `cancelOwnLogin`, входы Claude в `ownPendingLogins`
+- [x] 2 Мастер `SubscriptionSetup` на странице проекта
+- [x] 3 Тест в `subscriptions.test.ts`, проверка в браузере и первого шага с настоящим Claude, `openspec validate`
diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md
index c586dae1..585bd2ec 100644
--- a/openspec/specs/agent-credentials/spec.md
+++ b/openspec/specs/agent-credentials/spec.md
@@ -139,3 +139,22 @@ Claude и делать пул с этой подпиской пулом по у
#### Scenario: Пустой токен Claude
- **WHEN** владелец выбирает Claude и не вставляет токен
- **THEN** подключение отклонено с подсказкой про `claude setup-token`
+
+### Requirement: Подключение подписки без терминала
+Страница проекта без подписки SHALL показывать владельцу мастер подключения: кнопки
+«Подключить Claude» и «Подключить ChatGPT» и дальше шаги со ссылкой на вход. Для Claude
+пользователь SHALL завершать вход кодом, который Claude показывает после входа.
+
+#### Scenario: Claude по ссылке
+- **GIVEN** проект нового пользователя без подписки
+- **WHEN** владелец нажимает «Подключить Claude», открывает ссылку, входит и вставляет код в мастер
+- **THEN** подписка активна, мастер исчезает, агенты проекта могут запускаться
+
+#### Scenario: Отмена
+- **GIVEN** вход начат, код ещё не введён
+- **WHEN** владелец нажимает «Отменить и начать заново»
+- **THEN** ожидающая подписка удалена, мастер снова предлагает подключить Claude или ChatGPT
+
+#### Scenario: Чужой код
+- **WHEN** код для входа пытается ввести не владелец проекта и не суперадмин
+- **THEN** действие отклонено
diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts
index 3e85f600..f223a111 100644
--- a/packages/runner/src/project-subscription.ts
+++ b/packages/runner/src/project-subscription.ts
@@ -1,9 +1,9 @@
// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
// kept encrypted like every subscription, in the owner's personal pool).
-import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, type Project, type User } from "@peppa/core";
+import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, projectPool, type Project, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
-import { pendingLogin, pollCodexLogin } from "./subscription-login.ts";
+import { finishClaudeLogin, pendingLogin, pollCodexLogin, removeSubscription } from "./subscription-login.ts";
import { addSubscription } from "./subscriptions.ts";
async function requireOwner(db: Db, user: User, project: Project): Promise {
@@ -19,9 +19,9 @@ export async function chooseSharedSubscription(db: Db, user: User, project: Proj
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
}
-export type OwnSubscriptionKind = "claude" | "codex_login" | "codex_key" | "existing";
+export type OwnSubscriptionKind = "claude_login" | "claude" | "codex_login" | "codex_key" | "existing";
-const OWN_NAMES: Record, string> = { claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
+const OWN_NAMES: Record, string> = { claude_login: "Claude", claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
/**
* «Своя подписка» (PEP-76/80): a new subscription of the user goes into their own pool (created on
@@ -36,15 +36,17 @@ export async function connectOwnSubscription(db: Db, user: User, project: Projec
if (kind === "existing") {
if (!pool) throw new PeppaError("Своей подписки ещё нет — подключите Claude или ChatGPT");
} else {
- if (kind !== "codex_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API");
+ if (kind !== "codex_login" && kind !== "claude_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API");
const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
const base = `${OWN_NAMES[kind]} — ${user.login}`;
let name = base;
for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
const sub =
- kind === "claude"
- ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id })
- : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id });
+ kind === "claude_login"
+ ? await addSubscription(db, { provider: "claude", name, method: "login", createdBy: user.id })
+ : kind === "claude"
+ ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id })
+ : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id });
subscriptionId = sub.id;
if (pool) {
const cur = (await listPools(db)).find((p) => p.id === pool!.id);
@@ -61,22 +63,51 @@ export async function connectOwnSubscription(db: Db, user: User, project: Projec
export interface OwnLogin {
subscriptionId: number;
+ provider: "claude" | "codex";
name: string;
url: string;
+ /** ChatGPT: the one-time code to enter on the page behind the link. */
code: string | null;
}
/**
- * Device logins of the pool's subscriptions still waiting for the user (ChatGPT: open the link,
- * enter the code). Polls Codex first, so a finished login turns the subscription active.
+ * Sign-ins of the pool's subscriptions still waiting for the user. Claude: open the link, sign
+ * in, paste the code Claude shows (`finishOwnClaudeLogin`). ChatGPT: open the link and enter the
+ * code — Codex is polled first, so a finished login turns the subscription active.
*/
export async function ownPendingLogins(db: Db, poolId: number): Promise {
const out: OwnLogin[] = [];
for (const s of await poolSubscriptions(db, poolId)) {
- if (s.provider !== "codex" || s.status !== "pending") continue;
- if ((await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue;
+ if (s.status !== "pending" || s.provider === "opencode") continue;
+ if (s.provider === "codex" && (await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue;
const l = await pendingLogin(db, s.id);
- if (l) out.push({ subscriptionId: s.id, name: s.name, url: l.url, code: l.code ?? null });
+ if (l) out.push({ subscriptionId: s.id, provider: s.provider, name: s.name, url: l.url, code: l.code ?? null });
}
return out;
}
+
+/** The user's own pending subscription of the project's pool, or an error. */
+async function ownPendingSubscription(db: Db, user: User, project: Project, subscriptionId: number) {
+ await requireOwner(db, user, project);
+ const pool = await projectPool(db, project.id);
+ const sub = pool ? (await poolSubscriptions(db, pool.id)).find((s) => s.id === subscriptionId) : undefined;
+ if (!sub || (sub.createdBy !== user.id && !(await isSuperadmin(db, user)))) throw new PeppaError("Подписка не найдена");
+ return sub;
+}
+
+/** Step 3 of the Claude sign-in: the code Claude showed after the user signed in. */
+export async function finishOwnClaudeLogin(db: Db, user: User, project: Project, subscriptionId: number, code: string): Promise {
+ const sub = await ownPendingSubscription(db, user, project, subscriptionId);
+ if (sub.provider !== "claude") throw new PeppaError("Код нужен только для Claude");
+ await finishClaudeLogin(db, sub.id, code);
+}
+
+/** «Отмена» of a sign-in that was not finished: the pending subscription goes away. */
+export async function cancelOwnLogin(db: Db, user: User, project: Project, subscriptionId: number): Promise {
+ const sub = await ownPendingSubscription(db, user, project, subscriptionId);
+ if (sub.status !== "pending") throw new PeppaError("Эта подписка уже подключена");
+ await removeSubscription(db, sub.id);
+ const pool = await projectPool(db, project.id);
+ // The last one is gone: back to "no subscription", so the page offers to connect again.
+ if (pool && !(await poolSubscriptions(db, pool.id)).length && pool.createdBy === user.id) await setProjectPool(db, project.id, null);
+}
diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts
index 0084dc47..c57ce0a8 100644
--- a/packages/testkit/test/subscriptions.test.ts
+++ b/packages/testkit/test/subscriptions.test.ts
@@ -302,6 +302,33 @@ describe("PEP-76: владелец выбирает подписку проек
}
});
+ test("PEP-82: вход в Claude по ссылке и коду на странице проекта, без терминала", async () => {
+ const owner = await core.registerEgovUser(db, { iin: "850505400038", name: "ССЫЛКИН ВХОД" });
+ const stranger = await core.registerEgovUser(db, { iin: "850505400048", name: "ПОСТОРОННИЙ ВХОД" });
+ const p = await core.createProject(db, { slug: "mock-p82", key: "MPLNK", name: "P82", giteaOwner: "x", workspacePath: "/tmp/mock-p82", ownerId: owner.id });
+ const { subscriptionId } = await runner.connectOwnSubscription(db, owner, p, "claude_login");
+ const pool = (await core.projectPool(db, p.id))!;
+ const [l] = await runner.ownPendingLogins(db, pool.id);
+ assert.equal(l!.subscriptionId, subscriptionId);
+ assert.equal(l!.provider, "claude");
+ assert.match(l!.url, /^https:\/\//);
+ assert.match((await core.projectAgentWarning(db, p.id))!, /не подключена/, "pending is not working yet");
+
+ await assert.rejects(runner.finishOwnClaudeLogin(db, stranger, p, subscriptionId!, "mock-good-1"), /владелец/);
+ await runner.finishOwnClaudeLogin(db, owner, p, subscriptionId!, "mock-good-1");
+ assert.equal((await core.getSubscription(db, subscriptionId!)).status, "active");
+ assert.equal(await core.projectAgentWarning(db, p.id), null);
+ assert.deepEqual(await runner.ownPendingLogins(db, pool.id), []);
+ await assert.rejects(runner.cancelOwnLogin(db, owner, p, subscriptionId!), /уже подключена/);
+
+ // «Отменить и начать заново»: a pending sign-in goes away; with nothing left the project is unassigned.
+ const p2 = await core.createProject(db, { slug: "mock-p82b", key: "MPLNB", name: "P82b", giteaOwner: "x", workspacePath: "/tmp/mock-p82b", ownerId: stranger.id });
+ const second = await runner.connectOwnSubscription(db, stranger, p2, "claude_login");
+ await runner.cancelOwnLogin(db, stranger, p2, second.subscriptionId!);
+ assert.equal(await core.projectPool(db, p2.id), null);
+ assert.equal((await core.listSubscriptions(db)).some((s) => s.id === second.subscriptionId), false);
+ });
+
test("PEP-79: «Сам берёт» — диспетчер молчит, пока подписка не подключена", async () => {
assert.equal(core.autonomyLevel(core.NEW_PROJECT_AUTONOMY), "self");
assert.equal(core.NEW_PROJECT_AUTONOMY.pick, "auto");
--
2.45.2
From efe411f94ea34b916354905b6105a3ea038e2485 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 21:17:07 +0500
Subject: [PATCH 018/428] PEP-81: archive the change; epics tab verified in the
browser
Co-Authored-By: Claude Fable 5.2
---
.../2026-11-14-pep-81-epics-in-sight/proposal.md | 11 +++++++++++
.../specs/web-workspace/spec.md | 16 ++++++++++++++++
.../2026-11-14-pep-81-epics-in-sight/tasks.md | 3 +++
openspec/specs/web-workspace/spec.md | 15 +++++++++++++++
4 files changed, 45 insertions(+)
create mode 100644 openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md
diff --git a/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md
new file mode 100644
index 00000000..5a7fea30
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md
@@ -0,0 +1,11 @@
+# PEP-81: эпики на виду
+
+## Why
+Пользователи не понимают, где эпик, а где стори: эпики были видны только строкой фильтра над доской и в «⋯ Настройки проекта».
+
+## What Changes
+- Вкладка «Эпики» в проекте (`EpicsTab`): пояснение «эпик — большая цель, стори — шаг к ней», форма «Добавить эпик»,
+ по карточке на эпик (описание, прогресс «готово N из M», его стори со статусами, «На доске», «Спланировать стори»), блок «Стори без эпика».
+- На карточке доски метка эпика подписана «эпик»; «Эпики:» над доской ведёт на вкладку.
+
+Вне scope: группировка доски по эпикам. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md
new file mode 100644
index 00000000..53a84ce2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Вкладка «Эпики»
+Страница проекта SHALL иметь вкладку «Эпики»: объяснение, чем эпик отличается от стори,
+и каждый открытый эпик с описанием, прогрессом и списком его стори; стори без эпика
+показаны отдельным блоком. На карточке доски эпик стори SHALL быть подписан словом «эпик».
+
+#### Scenario: Эпик и его стори
+- **GIVEN** эпик «Оплата» с тремя стори, одна из них готова
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** он видит «Оплата», «готово 1 из 3» и три стори со статусами
+
+#### Scenario: Стори без эпика
+- **GIVEN** стори, не привязанная к эпику
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** стори показана в блоке «Стори без эпика»
diff --git a/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md
new file mode 100644
index 00000000..5db5adc0
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 Вкладка «Эпики» со стори каждого эпика
+- [x] 2 Подпись «эпик» на карточках доски, ссылка «Эпики:»
+- [x] 3 Проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 34794b34..12bfb664 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -401,3 +401,18 @@ PM SHALL уметь убрать стори в архив и вернуть её
#### Scenario: Обычный пользователь
- **WHEN** Главную открывает пользователь без прав суперадмина
- **THEN** блока «Проекты других» нет
+
+### Requirement: Вкладка «Эпики»
+Страница проекта SHALL иметь вкладку «Эпики»: объяснение, чем эпик отличается от стори,
+и каждый открытый эпик с описанием, прогрессом и списком его стори; стори без эпика
+показаны отдельным блоком. На карточке доски эпик стори SHALL быть подписан словом «эпик».
+
+#### Scenario: Эпик и его стори
+- **GIVEN** эпик «Оплата» с тремя стори, одна из них готова
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** он видит «Оплата», «готово 1 из 3» и три стори со статусами
+
+#### Scenario: Стори без эпика
+- **GIVEN** стори, не привязанная к эпику
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** стори показана в блоке «Стори без эпика»
--
2.45.2
From 27e43b1ea6a5741e597c7f93334a841d78173bd4 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 22:21:54 +0500
Subject: [PATCH 019/428] PEP-83: the login page says why the factory; first
steps for a product manager
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/login/page.tsx | 90 +++++++++++++++++--
apps/web/components/Onboarding.tsx | 80 ++++++++++-------
.../proposal.md | 14 +++
.../specs/onboarding/spec.md | 26 ++++++
.../tasks.md | 4 +
openspec/specs/onboarding/spec.md | 25 ++++++
packages/core/src/onboarding.ts | 86 +++++++++++++++---
packages/testkit/test/agent-smarts.test.ts | 15 ++--
9 files changed, 286 insertions(+), 55 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index 7b2facdf..b847bbb2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -62,6 +62,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-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 не трогаем
diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index 58bccf1f..9020612e 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -1,26 +1,104 @@
import { redirect } from "next/navigation";
+import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
import { currentUser, safeNext } from "@/lib/auth";
import { Brand } from "@/components/Brand";
import { Flash } from "@/components/common";
import { EgovSign } from "@/components/EgovSign";
import { Footer } from "@/components/Footer";
+import { PugMascot } from "@/components/PugMascot";
export const dynamic = "force-dynamic";
-/** PEP-71: eGov QR is the only way in; the first login registers the account. */
+const WHY = [
+ { title: "Программировать не нужно", text: "Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты." },
+ { title: "Всё на виду", text: "Доска показывает, что в работе, что готово и какой агент чем занят. Никаких «спросите у разработчиков»." },
+ { title: "Последнее слово за вами", text: "Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять»." },
+];
+
+const STEPS = [
+ { title: "Войдите с ноутбука", text: "Через eGov QR — учётка создаётся сама, пароль не нужен." },
+ { title: "Привяжите Telegram-бота", text: "Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова." },
+ { title: "Создайте проект и подключите подписку", text: "Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута." },
+ { title: "Опишите задачу словами", text: "«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам." },
+ { title: "Примите результат", text: "Придёт сообщение «готово». Посмотрите и нажмите «Принять» — или напишите, что поправить." },
+];
+
+const NEED = [
+ { icon: Laptop, text: "Ноутбук — управлять фабрикой удобнее с большого экрана" },
+ { icon: ShieldCheck, text: "eGov Mobile на телефоне — для входа" },
+ { icon: MessageCircle, text: "Telegram — туда приходят вопросы агентов и «готово»" },
+ { icon: Sparkles, text: "Платная подписка Claude или ChatGPT — на ней работают агенты" },
+];
+
+/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) {
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
return (
-
-
-
-
Софтвейр-фабрика: проекты в Gitea, стори по OpenSpec, агенты Claude Code и Codex.
+
+ {/* Phone: headline → sign-in → details. Laptop: text on the left, sign-in sticks on the right. */}
+
+
+ Опишите идею словами — команда ИИ-агентов сделает продукт
+
+ Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.
+
+
+
+
+
+ Начать — одна минута
+ Вход через eGov. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.
- Первый вход сразу создаёт учётку по вашему ИИН. На телефоне вход открывает eGov Mobile, QR не нужен.
+ Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.
+
+
+
+
+ Зачем это вам
+
+ {WHY.map((w) => (
+
+
+ {w.title}
+
+ {w.text}
+
+ ))}
+
+
+
+
+ Как это работает — пять шагов
+
+ {STEPS.map((s, i) => (
+
+
+ {i + 1}
+
+
+ {s.title}
+ {s.text}
+
+
+ ))}
+
+
+
+
+ Что понадобится
+
+ {NEED.map((n) => (
+
+ {n.text}
+
+ ))}
+
+
+
);
}
diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx
index 03179740..e9959ceb 100644
--- a/apps/web/components/Onboarding.tsx
+++ b/apps/web/components/Onboarding.tsx
@@ -1,5 +1,6 @@
-// PEP-31: first-run checklist on the home page.
-import { CircleCheck, Circle, X } from "lucide-react";
+// PEP-31/83: the first steps on the home page — for a product manager: what to do and why, in
+// order, with one button on the current step.
+import { ArrowRight, Check, X } from "lucide-react";
import type { Onboarding } from "@peppa/core";
import { dismissOnboardingAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
@@ -8,44 +9,61 @@ import { cn } from "@/lib/utils";
export function OnboardingChecklist({ data }: { data: Onboarding }) {
const next = data.steps.find((s) => !s.done && !s.optional);
+ const fresh = data.done === 0;
return (
-
-
-
Первый запуск
-
- {data.done} из {data.total}
-
-
-
+
);
diff --git a/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md
new file mode 100644
index 00000000..466b3e6b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md
@@ -0,0 +1,14 @@
+# PEP-83: вход и первый запуск для продактов
+
+## Why
+Пеппой пользуются продакт-менеджеры, которые не знают, что такое софтвер-фабрика. Страница входа не объясняла, зачем она нужна,
+а чек-лист «Первый запуск» был написан для программиста и не вёл по шагам. Управляют они с ноутбука, а отвечают агентам через Telegram.
+
+## What Changes
+- Страница входа: заголовок-обещание, «Зачем это вам» (3 причины), «Как это работает — пять шагов», «Что понадобится» (ноутбук,
+ eGov Mobile, Telegram, подписка Claude или ChatGPT), блок входа с мопсом. На телефоне порядок: заголовок → вход → подробности.
+- Первый запуск на Главной: шесть шагов для продакта — Telegram → проект → своя подписка → первая задача → агент взял в работу →
+ принять результат. У шага — объяснение «зачем» и кнопка на текущем шаге (`OnboardingStep.action`). Шаг eGov убран (вход и так
+ через eGov); новый шаг `accepted`; шаг `subscription` у обычного пользователя — «проект готов запускать агентов».
+
+Вне scope: обучающее видео, тур по интерфейсу. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md
new file mode 100644
index 00000000..9fb53bf6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md
@@ -0,0 +1,26 @@
+## ADDED Requirements
+
+### Requirement: Страница входа объясняет фабрику
+Страница входа SHALL до входа объяснять простым языком, зачем нужна фабрика, как она
+работает по шагам и что понадобится (ноутбук, eGov Mobile, Telegram, подписка Claude или
+ChatGPT). На телефоне заголовок SHALL идти перед блоком входа.
+
+#### Scenario: Новый человек
+- **WHEN** человек без сессии открывает Пеппу
+- **THEN** он видит обещание продукта, три причины «зачем», пять шагов «как» и кнопку «Войти через eGov»
+
+### Requirement: Пошаговый старт для продакта
+Главная нового пользователя SHALL показывать шаги: привязать Telegram, создать проект,
+подключить свою подписку, описать первую задачу, агент взял задачу, принять результат —
+с объяснением каждого шага и кнопкой действия на текущем. Блок скрывается после первой
+принятой стори или по кнопке «Скрыть».
+
+#### Scenario: Первый вход
+- **GIVEN** пользователь только что зарегистрировался
+- **WHEN** он открывает Главную
+- **THEN** текущий шаг — «Привяжите Telegram» с кнопкой «Привязать Telegram», сделано 0 из 6
+
+#### Scenario: Первая принятая стори
+- **GIVEN** пользователь прошёл пять шагов
+- **WHEN** он принимает первую стори
+- **THEN** блок шагов больше не показывается
diff --git a/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md
new file mode 100644
index 00000000..43c3d628
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md
@@ -0,0 +1,4 @@
+- [x] 1 Шаги онбординга в core: порядок, тексты, `action`, `accepted`, подписка обычного пользователя
+- [x] 2 Компонент шагов на Главной
+- [x] 3 Страница входа
+- [x] 4 Тест `agent-smarts.test.ts`, проверка в браузере (ноутбук и телефон), `openspec validate`
diff --git a/openspec/specs/onboarding/spec.md b/openspec/specs/onboarding/spec.md
index e5e31cca..807ea738 100644
--- a/openspec/specs/onboarding/spec.md
+++ b/openspec/specs/onboarding/spec.md
@@ -28,3 +28,28 @@
- **GIVEN** у проекта PAY пул с одной подпиской в статусе `auth_error`
- **WHEN** участник открывает проект
- **THEN** над вкладками плашка «Агенты не запустятся» с причиной
+
+### Requirement: Страница входа объясняет фабрику
+Страница входа SHALL до входа объяснять простым языком, зачем нужна фабрика, как она
+работает по шагам и что понадобится (ноутбук, eGov Mobile, Telegram, подписка Claude или
+ChatGPT). На телефоне заголовок SHALL идти перед блоком входа.
+
+#### Scenario: Новый человек
+- **WHEN** человек без сессии открывает Пеппу
+- **THEN** он видит обещание продукта, три причины «зачем», пять шагов «как» и кнопку «Войти через eGov»
+
+### Requirement: Пошаговый старт для продакта
+Главная нового пользователя SHALL показывать шаги: привязать Telegram, создать проект,
+подключить свою подписку, описать первую задачу, агент взял задачу, принять результат —
+с объяснением каждого шага и кнопкой действия на текущем. Блок скрывается после первой
+принятой стори или по кнопке «Скрыть».
+
+#### Scenario: Первый вход
+- **GIVEN** пользователь только что зарегистрировался
+- **WHEN** он открывает Главную
+- **THEN** текущий шаг — «Привяжите Telegram» с кнопкой «Привязать Telegram», сделано 0 из 6
+
+#### Scenario: Первая принятая стори
+- **GIVEN** пользователь прошёл пять шагов
+- **WHEN** он принимает первую стори
+- **THEN** блок шагов больше не показывается
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index 6acd1c38..d92056f6 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -7,12 +7,14 @@ import { getSetting, setSetting } from "./settings.ts";
import { isUsable, poolSubscriptions } from "./subscriptions.ts";
import { userProjectIds, type User } from "./users.ts";
-export type OnboardingStepId = "subscription" | "telegram" | "egov" | "project" | "story" | "started";
+export type OnboardingStepId = "subscription" | "telegram" | "project" | "story" | "started" | "accepted";
export interface OnboardingStep {
id: OnboardingStepId;
title: string;
hint: string;
+ /** Button label of the step while it is the current one (PEP-83). */
+ action: string;
href: string;
done: boolean;
optional: boolean;
@@ -45,25 +47,83 @@ export async function onboardingChecklist(db: Db, user: Pick
0,
+ optional: false,
+ };
+ let subscription: OnboardingStep;
if (admin) {
const subs = await db.select({ status: subscriptions.status, limitedUntil: subscriptions.limitedUntil }).from(subscriptions);
- steps.push({
+ subscription = {
id: "subscription",
- title: "Подключить подписку агента",
- hint: "Claude, Codex или OpenCode — на ней работают агенты; добавь её в пул проекта.",
+ title: "Подключите подписку агента",
+ hint: "Claude, Codex или OpenCode — на ней работают агенты; добавьте её в пул проекта.",
+ action: "Открыть подписки",
href: "/subscriptions",
done: subs.some((s) => s.status === "active" || s.status === "limited"),
optional: false,
- });
+ };
+ } else {
+ let ready = false;
+ for (const id of ids) if (!(await projectAgentWarning(db, id))) ready = true;
+ subscription = {
+ id: "subscription",
+ title: "Подключите свою подписку Claude или ChatGPT",
+ hint: "На ней агенты пишут код. Подойдёт обычная платная подписка; подключение — одна минута, кнопка на странице проекта.",
+ action: "Подключить подписку",
+ href: projectHref,
+ done: ready,
+ optional: false,
+ };
}
- steps.push(
- { id: "telegram", title: "Привязать Telegram", hint: "Вопросы агентов и «готово к ревью» придут в бот, отвечать можно кнопками.", href: "/settings#telegram", done: me?.chat != null, optional: false },
- { id: "egov", title: "Привязать eGov", hint: "Вход по QR из eGov Mobile без пароля.", href: "/settings#egov", done: !!me?.iin, optional: true },
- { id: "project", title: "Создать проект", hint: "Пеппа заведёт репозиторий в Gitea с шаблоном и CI.", href: "/projects/new", done: ids.length > 0, optional: false },
- { id: "story", title: "Завести стори", hint: "Опиши, что нужно сделать, — одна стори = одно изменение.", href: firstKey ? `/p/${firstKey}` : "/projects", done: storyCount > 0, optional: false },
- { id: "started", title: "Двинуть стори в работу", hint: "Перетащи карточку в «В работе» — агент запустится сам.", href: firstKey ? `/p/${firstKey}` : "/projects", done: started > 0, optional: false },
- );
+ const rest: OnboardingStep[] = [
+ {
+ id: "story",
+ title: "Опишите первую задачу",
+ hint: "Кнопка «+ Стори» в проекте. Напишите обычными словами, что должно получиться, — как объяснили бы человеку.",
+ action: "Написать задачу",
+ href: projectHref,
+ done: storyCount > 0,
+ optional: false,
+ },
+ {
+ id: "started",
+ title: "Агент берёт задачу в работу",
+ hint: "В новом проекте это происходит само за минуту; на карточке появятся имя агента и прогресс. Ничего перетаскивать не нужно.",
+ action: "Открыть доску",
+ href: projectHref,
+ done: started > 0,
+ optional: false,
+ },
+ {
+ id: "accepted",
+ title: "Посмотрите результат и нажмите «Принять»",
+ hint: "Когда агент закончит, придёт сообщение, а карточка перейдёт в «Ревью». Что-то не так — напишите комментарий, агент переделает.",
+ action: "Открыть доску",
+ href: projectHref,
+ done: accepted > 0,
+ optional: false,
+ },
+ ];
+ const steps: OnboardingStep[] = admin ? [subscription, telegram, project, ...rest] : [telegram, project, subscription, ...rest];
const required = steps.filter((s) => !s.optional);
const done = required.filter((s) => s.done).length;
const complete = done === required.length;
diff --git a/packages/testkit/test/agent-smarts.test.ts b/packages/testkit/test/agent-smarts.test.ts
index 51bedc13..2edb0669 100644
--- a/packages/testkit/test/agent-smarts.test.ts
+++ b/packages/testkit/test/agent-smarts.test.ts
@@ -173,27 +173,32 @@ describe("PEP-31: чек-лист первого запуска", () => {
test("Шаги отмечаются по данным, чек-лист скрывается после выполнения или по кнопке", async () => {
const u = await core.upsertUserFromGitea(db, { id: 3131, login: "mock-new-3131" }, { access_token: "x" });
let ob = await core.onboardingChecklist(db, u);
- assert.deepEqual(ob.steps.map((s) => s.id), ["telegram", "egov", "project", "story", "started"], "no subscription step for a non-admin");
- assert.deepEqual({ done: ob.done, total: ob.total, visible: ob.visible }, { done: 0, total: 4, visible: true });
+ assert.deepEqual(ob.steps.map((s) => s.id), ["telegram", "project", "subscription", "story", "started", "accepted"], "PEP-83: a product manager's path");
+ assert.deepEqual({ done: ob.done, total: ob.total, visible: ob.visible }, { done: 0, total: 6, visible: true });
+ assert.ok(ob.steps.every((s) => s.action && s.hint), "every step says what to do");
db.$client.prepare("UPDATE users SET telegram_chat_id = ? WHERE id = ?").run(3131, u.id);
setDefaultOwner(u.id);
const p = await project({ turns: [[{ say: "ok" }]] });
setDefaultOwner(pm.id);
ob = await core.onboardingChecklist(db, u);
- assert.deepEqual(ob.steps.filter((s) => s.done).map((s) => s.id), ["telegram", "project", "story"]);
+ assert.deepEqual(ob.steps.filter((s) => s.done).map((s) => s.id), ["telegram", "project", "subscription", "story"], "a Gitea-era owner may run without a pool");
assert.equal(ob.steps.find((s) => s.id === "started")!.href, `/p/${p.key}`);
const sid = await p.start();
ob = await core.onboardingChecklist(db, u);
- assert.deepEqual({ done: ob.done, complete: ob.complete, visible: ob.visible }, { done: 4, complete: true, visible: false });
+ assert.deepEqual({ done: ob.done, complete: ob.complete, visible: ob.visible }, { done: 5, complete: false, visible: true });
await runner.stopSession(db, sid);
+ // The last step — the first accepted story.
+ await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "done" });
+ ob = await core.onboardingChecklist(db, u);
+ assert.deepEqual({ done: ob.done, complete: ob.complete, visible: ob.visible }, { done: 6, complete: true, visible: false });
const admin = await core.upsertUserFromGitea(db, { id: 3132, login: "mock-admin-3132" }, { access_token: "x" });
await core.setPlatformAdmins(db, ["mock-admin-3132"]);
ob = await core.onboardingChecklist(db, admin);
assert.equal(ob.steps[0]!.id, "subscription");
- assert.equal(ob.total, 5);
+ assert.equal(ob.total, 6);
await core.dismissOnboarding(db, admin.id);
ob = await core.onboardingChecklist(db, admin);
assert.deepEqual({ dismissed: ob.dismissed, visible: ob.visible }, { dismissed: true, visible: false });
--
2.45.2
From ee4a3130747041f0be7e2e230ab75e75e54e47f3 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 22:39:07 +0500
Subject: [PATCH 020/428] =?UTF-8?q?PEP-84:=20=C2=AB=D0=BF=D1=80=D0=BE?=
=?UTF-8?q?=D0=B4=D0=B0=D0=BA=D1=82=C2=BB=20and=20=C2=AB=D0=B0=D0=BD=D0=B0?=
=?UTF-8?q?=D0=BB=D0=B8=D1=82=D0=B8=D0=BA=C2=BB=20refine=20a=20story=20bef?=
=?UTF-8?q?ore=20any=20developer=20agent=20takes=20it?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Also: a subscription the owner connected once is assigned to their new projects; claudePrint never
falls back to the machine login for a self-registered owner.
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 10 +
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/p/[key]/page.tsx | 25 +-
apps/web/app/(app)/t/[key]/page.tsx | 22 +-
apps/web/app/(app)/t/[key]/tabs.tsx | 7 +-
apps/web/components/Board.tsx | 7 +
.../proposal.md | 24 ++
.../specs/story-planning/spec.md | 36 ++
.../tasks.md | 5 +
openspec/specs/story-planning/spec.md | 35 ++
packages/core/src/chats.ts | 2 +
packages/core/src/index.ts | 1 +
packages/core/src/intake.ts | 310 ++++++++++++++++++
packages/core/src/tasks.ts | 7 +-
packages/runner/src/autonomy.ts | 5 +-
packages/runner/src/claude-print.ts | 11 +-
packages/runner/src/flow.ts | 3 +
packages/runner/src/index.ts | 1 +
packages/runner/src/intake.ts | 180 ++++++++++
packages/runner/src/provision.ts | 7 +-
packages/runner/src/watchdog.ts | 3 +
packages/testkit/bin/mock-intake | 3 +
packages/testkit/src/mock-intake.ts | 44 +++
packages/testkit/test/intake.test.ts | 165 ++++++++++
packages/testkit/test/web.test.ts | 14 +
26 files changed, 917 insertions(+), 12 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md
create mode 100644 packages/core/src/intake.ts
create mode 100644 packages/runner/src/intake.ts
create mode 100755 packages/testkit/bin/mock-intake
create mode 100644 packages/testkit/src/mock-intake.ts
create mode 100644 packages/testkit/test/intake.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index b847bbb2..a87fd48f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -40,6 +40,7 @@
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
- **Своя подписка (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`)
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (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`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index a3c00ac2..815c0d41 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -20,6 +20,7 @@ import {
getProject as getProjectByKey,
updateIncidentSettings,
setReviewSettings,
+ setIntakeSettings,
type IncidentPolicy,
getUser,
isSuperadmin,
@@ -695,3 +696,12 @@ export async function cancelOwnLoginAction(f: FormData) {
await cancelOwnLogin(db, user, p, Number(str(f, "subscriptionId")));
});
}
+
+// ── PEP-84: «продакт» and «аналитик» ───────────────────────────────────────────────
+export async function saveIntakeSettingsAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 32b54396..5917c083 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -72,6 +72,7 @@ export default async function Help() {
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
+ Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 622d94ec..b8121705 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -22,7 +22,7 @@ import { requireUser } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
-import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
+import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, saveIntakeSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
@@ -118,6 +118,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
const agentNames = await taskAgentNames(db, p.id);
+ const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
const cards: Card[] = tasks
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
.map((t) => {
@@ -132,6 +133,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
agent: agentNames.get(t.id) ?? null,
+ refining: refining.has(t.id) ? (refining.get(t.id) === "waiting" ? "ждёт ваших ответов" : "уточняется") : null,
};
});
// Gitea and the working copy are read only for the open tab.
@@ -208,6 +210,25 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
+
+
+
+
+
+ Новые стори сначала уточняют продакт и аналитик
+
+
+ Ждать ответа на вопросы, минут
+
+
+ Сохранить
+
+
+ Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). Стори, созданные
+ до включения, не трогает.
+
+
+
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index 14a957cb..e7e36cb7 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -1,5 +1,6 @@
// Story page (PEP-32): header with the story, the agent and its live session; tabs by the
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
+import { Markdown } from "@/components/Markdown";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Archive, ArchiveRestore, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
@@ -31,6 +32,9 @@ import {
reviewPreview,
sessionSteps,
storyComments,
+ getIntakeSettings,
+ getIntakeState,
+ intakePending,
taskCiSummary,
type GateResult,
} from "@peppa/core";
@@ -96,6 +100,9 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
// Only the open tab reads the rest (Gitea for the merge request).
const comments = tab === "comments" ? await storyComments(db, task.id) : [];
+ // PEP-84: is the story still with «продакт» and «аналитик»?
+ const intake = task.status === "backlog" ? await getIntakeState(db, task.id) : null;
+ const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "product") : null;
const runs: CheckRunRow[] =
tab === "tests" && ci.sha
? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt))).filter((r) => r.sha === ci.sha).sort((a, b) => a.check.localeCompare(b.check))
@@ -256,6 +263,14 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
+ {refining && (
+
+ {refining === "waiting" ? "Аналитик ждёт ваших ответов" : "Продакт и аналитик уточняют задачу"}
+
+ {refining === "waiting" ? "— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу." : "— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого."}
+
+
+ )}
{sp.edit ? (
@@ -287,7 +302,12 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
) : (
Описание}>
- {task.description || Без описания }
+ {/* PEP-84: the analyst writes the story in Markdown (criteria, out of scope, assumptions). */}
+ {task.description && /^## /m.test(task.description) ? (
+
+ ) : (
+ {task.description || Без описания }
+ )}
)}
diff --git a/apps/web/app/(app)/t/[key]/tabs.tsx b/apps/web/app/(app)/t/[key]/tabs.tsx
index db58d529..54758365 100644
--- a/apps/web/app/(app)/t/[key]/tabs.tsx
+++ b/apps/web/app/(app)/t/[key]/tabs.tsx
@@ -1,5 +1,6 @@
// Story page tabs (PEP-32): OpenSpec artifacts of the change, comments, checks, the PR and
// the activity log. Server components; each tab reads only what it shows.
+import { AgentBadge } from "@/components/AgentBadge";
import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass, MessageSquare, Send } from "lucide-react";
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
import { reviewLabel } from "@peppa/core";
@@ -146,10 +147,10 @@ export function CommentsTab({ taskKey, taskStatus, questions, comments, back, ha
t.kind === "q" ? (
) : (
-
+
-
- {t.c.login} комментарий PM · {ago(t.c.createdAt)}
+ {t.c.role ? : }
+ {t.c.role ? (t.c.role === "product" ? "зачем и что берём" : "что должно получиться") : <>{t.c.login} комментарий PM>} · {ago(t.c.createdAt)}
{t.c.text}
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index de1fc025..637d5fca 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -25,6 +25,8 @@ export interface Card {
blocked?: string | null;
/** PEP-75: the persona working on the story right now. */
agent?: string | null;
+ /** PEP-84: «продакт» and «аналитик» still hold the story ("уточняется" / "ждёт ваших ответов"). */
+ refining?: string | null;
}
export interface CardProgress {
done: number;
@@ -186,6 +188,11 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
)}
+ {card.refining && (
+
+ {card.refining}
+
+ )}
{card.agent &&
}
{card.progress &&
}
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
diff --git a/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md
new file mode 100644
index 00000000..90d1c93d
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md
@@ -0,0 +1,24 @@
+# PEP-84: агенты «продакт» и «аналитик» — уточнение задачи перед работой
+
+## Why
+Сырое пожелание продакта сразу попадало к агенту-разработчику, и тот сам додумывал, что имелось в виду. PM: нужны агенты
+«продакт» и «аналитик», которые уточняют задачу, не льстят, помнят контекст и не ждут разрешений.
+
+## What Changes
+- Две роли (`core/intake.ts`, `runner/intake.ts`) — короткие вызовы `claude -p` на подписке проекта (`PEPPA_INTAKE_BIN`,
+ `PEPPA_INTAKE_MODEL`=sonnet): продакт (цель, самая маленькая версия, деление на стори — до 4 дополнительных, новое название),
+ затем аналитик (описание, критерии приёмки, вне задачи, допущения, до 3 вопросов с вариантом по умолчанию).
+- Контекст ролей: AGENTS.md проекта, память проекта, эпики, другие стори. Тон в промпте: без похвалы, прямо, для непрограммиста,
+ без запросов разрешения.
+- Состояние стори — `settings` `intake.task:
` (product → analyst → waiting | finalize → done); настройка проекта
+ `project.intake:` (вкл, сколько минут ждать; стори до включения не трогаются). Миграций нет.
+- Не ждут: вопросы уходят PM обычным вопросом; нет ответа за `waitMin` (30) минут — срок сдвигается за тихие часы проекта —
+ аналитик пишет допущения и закрывает вопрос. Ответ PM → аналитик дописывает стори. Две неудачи модели → стори идёт как написана.
+- Диспетчер (`readyBacklog`) не берёт стори, пока роли не закончили; PM, перетащивший карточку в работу, отменяет уточнение.
+- Реплики ролей — событие `intake_note`: вкладка Comments стори, чат проекта (и Telegram-группа), `get_task` разработчика.
+ Доска: метка «уточняется» / «ждёт ваших ответов»; страница стори: плашка и описание в Markdown.
+- Новый проект: уточнение включено; подписка владельца, подключённая однажды, назначается новому проекту сама.
+- `claudePrint` без подписки Claude в пуле не уходит на вход машины для самозарегистрированного владельца.
+
+Вне scope: сверка результата с критериями при приёмке, роли как персонажи «Команды», уточнение через свободный диалог.
+Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md
new file mode 100644
index 00000000..6fcd0fdb
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md
@@ -0,0 +1,36 @@
+## ADDED Requirements
+
+### Requirement: Продакт и аналитик уточняют стори
+В проекте с включённым уточнением новая стори в бэклоге SHALL сначала пройти роль «продакт»
+(цель, урезание до минимальной версии, деление на стори) и роль «аналитик» (описание,
+критерии приёмки, что вне задачи, допущения). Роли SHALL получать стандарты, память, эпики и
+другие стори проекта, писать без похвалы и не спрашивать разрешений. Диспетчер SHALL NOT
+брать стори, пока уточнение не закончено.
+
+#### Scenario: Стори уточнена
+- **GIVEN** проект с включённым уточнением
+- **WHEN** продакт создаёт стори «Корзина» с текстом «хочу складывать товары»
+- **THEN** в комментариях стори появляются реплики «Продакт» и «Аналитик», в описании — «Критерии приёмки» и «Исходный запрос» с его словами
+
+#### Scenario: Запрос больше одной стори
+- **WHEN** продакт-агент решает, что запрос «сделай интернет-магазин» — три задачи
+- **THEN** исходная стори переименована в первую из них, две другие созданы в бэклоге и проходят аналитика
+
+### Requirement: Аналитик не ждёт
+Аналитик SHALL задавать не больше трёх вопросов, каждый с вариантом по умолчанию, и по
+истечении срока ожидания (по умолчанию 30 минут; ночью — до конца тихих часов проекта)
+принимать варианты по умолчанию как допущения и отдавать стори в работу.
+
+#### Scenario: Ответ получен
+- **GIVEN** аналитик спросил «Нужна ли мобильная версия? По умолчанию: да»
+- **WHEN** продакт отвечает «не нужна»
+- **THEN** аналитик дописывает стори с учётом ответа, вопросов больше нет, стори доступна диспетчеру
+
+#### Scenario: Ответа нет
+- **GIVEN** вопрос аналитика без ответа
+- **WHEN** проходит 30 минут
+- **THEN** вопрос закрыт, вариант по умолчанию записан в «Допущения», стори доступна диспетчеру
+
+#### Scenario: Модель не ответила
+- **WHEN** роль дважды не смогла разобрать задачу
+- **THEN** стори идёт в работу как написана, в комментариях — почему
diff --git a/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md
new file mode 100644
index 00000000..b076e47e
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md
@@ -0,0 +1,5 @@
+- [x] 1 core/intake.ts: настройки, состояние, контекст, промпты, разбор ответов, текст стори
+- [x] 2 runner/intake.ts: `intakeTick`, вопросы и срок, ответ PM, отказоустойчивость; диспетчер ждёт; `releaseIntake`
+- [x] 3 Веб: настройка проекта, метка на доске, плашка и реплики в стори, Markdown описания; чат проекта
+- [x] 4 Новый проект: уточнение включено, своя подписка назначается сама; `claudePrint` без входа машины
+- [x] 5 mock-intake, `intake.test.ts`, прогон на настоящей модели (SBX-2), `openspec validate`
diff --git a/openspec/specs/story-planning/spec.md b/openspec/specs/story-planning/spec.md
index eba2c707..ceb3227e 100644
--- a/openspec/specs/story-planning/spec.md
+++ b/openspec/specs/story-planning/spec.md
@@ -34,3 +34,38 @@ Claude на подписке пула проекта предлагать спи
#### Scenario: Планировщик ответил мусором
- **WHEN** ответ планировщика не JSON со списком стори
- **THEN** PM видит «планировщик ответил не по формату», стори не созданы
+
+### Requirement: Продакт и аналитик уточняют стори
+В проекте с включённым уточнением новая стори в бэклоге SHALL сначала пройти роль «продакт»
+(цель, урезание до минимальной версии, деление на стори) и роль «аналитик» (описание,
+критерии приёмки, что вне задачи, допущения). Роли SHALL получать стандарты, память, эпики и
+другие стори проекта, писать без похвалы и не спрашивать разрешений. Диспетчер SHALL NOT
+брать стори, пока уточнение не закончено.
+
+#### Scenario: Стори уточнена
+- **GIVEN** проект с включённым уточнением
+- **WHEN** продакт создаёт стори «Корзина» с текстом «хочу складывать товары»
+- **THEN** в комментариях стори появляются реплики «Продакт» и «Аналитик», в описании — «Критерии приёмки» и «Исходный запрос» с его словами
+
+#### Scenario: Запрос больше одной стори
+- **WHEN** продакт-агент решает, что запрос «сделай интернет-магазин» — три задачи
+- **THEN** исходная стори переименована в первую из них, две другие созданы в бэклоге и проходят аналитика
+
+### Requirement: Аналитик не ждёт
+Аналитик SHALL задавать не больше трёх вопросов, каждый с вариантом по умолчанию, и по
+истечении срока ожидания (по умолчанию 30 минут; ночью — до конца тихих часов проекта)
+принимать варианты по умолчанию как допущения и отдавать стори в работу.
+
+#### Scenario: Ответ получен
+- **GIVEN** аналитик спросил «Нужна ли мобильная версия? По умолчанию: да»
+- **WHEN** продакт отвечает «не нужна»
+- **THEN** аналитик дописывает стори с учётом ответа, вопросов больше нет, стори доступна диспетчеру
+
+#### Scenario: Ответа нет
+- **GIVEN** вопрос аналитика без ответа
+- **WHEN** проходит 30 минут
+- **THEN** вопрос закрыт, вариант по умолчанию записан в «Допущения», стори доступна диспетчеру
+
+#### Scenario: Модель не ответила
+- **WHEN** роль дважды не смогла разобрать задачу
+- **THEN** стори идёт в работу как написана, в комментариях — почему
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 282248e9..237c0808 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-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 }),
started: () => ({ text: "▶️ Агент запущен" }),
resumed: () => ({ text: "🔁 Агент продолжает работу" }),
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 6e3457b0..e8663891 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -22,6 +22,7 @@ export * from "./ci.ts";
export * from "./egov.ts";
export * from "./team.ts";
export * from "./progress.ts";
+export * from "./intake.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";
diff --git a/packages/core/src/intake.ts b/packages/core/src/intake.ts
new file mode 100644
index 00000000..690e6163
--- /dev/null
+++ b/packages/core/src/intake.ts
@@ -0,0 +1,310 @@
+// PEP-84: «продакт» and «аналитик» — two short LLM roles a new story passes before any developer
+// agent touches it. The product manager asks why and cuts the scope; the analyst writes what
+// exactly must come out (acceptance criteria, out of scope, assumptions) and asks at most three
+// questions, each with the default it will take if nobody answers. They do not flatter, see the
+// project's context, and never wait for permission: no answer in time — they go by the defaults.
+// State lives in `settings` (`intake.task:`, `project.intake:`): no schema change.
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { events, goals, tasks, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, asc, desc, eq, inArray, isNull } from "drizzle-orm";
+import { actorColumns } from "./actor.ts";
+import { readMemory } from "./memory.ts";
+import { notify } from "./notify.ts";
+import type { Project } from "./projects.ts";
+import { getSetting, setSetting } from "./settings.ts";
+import type { Task } from "./tasks.ts";
+
+export type IntakeRole = "product" | "analyst";
+export const INTAKE_ROLE_RU: Record = { product: "Продакт", analyst: "Аналитик" };
+export const INTAKE_EVENT = "intake_note";
+export const INTAKE_MAX_QUESTIONS = 3;
+export const INTAKE_MAX_SPLIT = 4;
+
+export interface IntakeSettings {
+ enabled: boolean;
+ /** Minutes the analyst waits for the PM's answers before going by its defaults. */
+ waitMin: number;
+ /** Stories created before this moment are left alone (ISO). */
+ since: string | null;
+}
+export const DEFAULT_INTAKE: IntakeSettings = { enabled: false, waitMin: 30, since: null };
+const projectKey = (projectId: number) => `project.intake:${projectId}`;
+
+export async function getIntakeSettings(db: Db, projectId: number): Promise {
+ return { ...DEFAULT_INTAKE, ...((await getSetting>(db, projectKey(projectId))) ?? {}) };
+}
+
+export async function setIntakeSettings(db: Db, projectId: number, patch: { enabled?: boolean; waitMin?: number }, now = new Date()): Promise {
+ const cur = await getIntakeSettings(db, projectId);
+ const next: IntakeSettings = { ...cur };
+ if (patch.waitMin !== undefined) next.waitMin = Math.min(24 * 60, Math.max(0, Math.round(patch.waitMin) || 0));
+ if (patch.enabled !== undefined && patch.enabled !== cur.enabled) {
+ next.enabled = patch.enabled;
+ // Turning it on does not drag the old backlog through the roles.
+ if (patch.enabled) next.since = now.toISOString();
+ }
+ await setSetting(db, projectKey(projectId), next);
+ return next;
+}
+
+export interface IntakeQuestion {
+ q: string;
+ /** What the analyst does if nobody answers. */
+ default: string;
+}
+
+export type IntakeStage = "product" | "analyst" | "waiting" | "finalize" | "done";
+
+export interface IntakeState {
+ stage: IntakeStage;
+ /** The PM's words as they were written. */
+ original: { title: string; description: string };
+ product?: ProductNote;
+ analyst?: AnalystNote;
+ questionId?: number;
+ /** When the analyst stops waiting (ms). */
+ deadline?: number;
+ /** The PM's answer to the questions (stage "finalize"). */
+ answer?: string;
+ attempts: number;
+ /** Why the roles were skipped or gave up, if they did. */
+ note?: string;
+}
+const taskKey = (taskId: number) => `intake.task:${taskId}`;
+
+export async function getIntakeState(db: Db, taskId: number): Promise {
+ return getSetting(db, taskKey(taskId));
+}
+export async function setIntakeState(db: Db, taskId: number, state: IntakeState): Promise {
+ await setSetting(db, taskKey(taskId), state);
+ await notify(db, { type: "task_updated", taskId });
+}
+
+/** Does this backlog story still belong to the roles (the dispatcher must not take it)? */
+export function intakePending(settings: IntakeSettings, task: Pick, state: IntakeState | null): boolean {
+ if (!settings.enabled || task.status !== "backlog") return false;
+ if (state) return state.stage !== "done";
+ return !!settings.since && task.createdAt.getTime() >= Date.parse(settings.since);
+}
+
+/** Backlog stories of the project the roles have not finished with: taskId → stage ("new" = not started). */
+export async function intakePendingTasks(db: Db, projectId: number): Promise> {
+ const out = new Map();
+ const settings = await getIntakeSettings(db, projectId);
+ if (!settings.enabled) return out;
+ const backlog = await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "backlog"), isNull(tasks.archivedAt)));
+ for (const t of backlog) {
+ const state = await getIntakeState(db, t.id);
+ if (intakePending(settings, t, state)) out.set(t.id, state?.stage ?? "new");
+ }
+ return out;
+}
+
+// ── what the roles see ───────────────────────────────────────────────────────────
+
+const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}\n…(обрезано)` : s);
+
+/** The project as the roles know it: standards, memory, epics, what was done and what is planned. */
+export async function intakeContext(db: Db, project: Project, task: Pick): Promise {
+ const agentsMd = existsSync(join(project.workspacePath, "AGENTS.md")) ? readFileSync(join(project.workspacePath, "AGENTS.md"), "utf8").trim() : "";
+ const memory = readMemory(project.workspacePath).trim();
+ const epics = await db.select().from(goals).where(and(eq(goals.projectId, project.id), eq(goals.status, "open"))).orderBy(asc(goals.id));
+ const stories = (await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt))).orderBy(desc(tasks.id)).limit(60)).filter((t) => t.id !== task.id);
+ const epic = epics.find((e) => e.id === task.goalId);
+ const line = (t: (typeof stories)[number]) => `- ${formatTaskKey(project.key, t.number)} [${t.status}] ${t.title}`;
+ return [
+ `Проект: ${project.key} — ${project.name}`,
+ "",
+ "## Стандарты проекта (AGENTS.md)",
+ agentsMd ? clip(agentsMd, 6000) : "(нет)",
+ "",
+ "## Память проекта",
+ memory ? clip(memory, 4000) : "(пусто)",
+ "",
+ "## Эпики",
+ epics.length ? epics.map((e) => `- #${e.id} ${e.title}${e.description ? ` — ${clip(e.description.replace(/\s+/g, " "), 300)}` : ""}`).join("\n") : "(нет)",
+ ...(epic ? ["", `Эта стори относится к эпику «${epic.title}».`] : []),
+ "",
+ "## Другие стори проекта (новые сверху)",
+ stories.length ? stories.map(line).join("\n") : "(нет — это первая стори проекта)",
+ ].join("\n");
+}
+
+const TONE = [
+ "Тон: коллега, а не помощник. Не хвали и не благодари, без «отличная идея» и восклицаний. Слабое место называй прямо и коротко.",
+ "Пиши для продакт-менеджера, который не программист: простые слова, без жаргона (PR, CI, API — только если без них нельзя).",
+ "Ты не спрашиваешь разрешений и не предлагаешь «могу сделать» — ты решаешь и пишешь, что решено.",
+].join("\n");
+
+export interface ProductNote {
+ /** What the PM actually wants, in one or two sentences. */
+ goal: string;
+ /** Plain words to the PM: what is cut, what is risky, what is unclear. */
+ comment: string;
+ /** A better title for this story (the smallest useful version), or the same one. */
+ title: string;
+ /** Other stories this request breaks into (besides this one). */
+ split: Array<{ title: string; description: string }>;
+}
+
+export function productPrompt(context: string, story: { title: string; description: string }): string {
+ return [
+ "Ты — продакт-менеджер софтвер-фабрики. К тебе пришло сырое пожелание. Реши, что из него делать.",
+ "1. Пойми цель: для кого это и какую проблему решает. Если пожелание не решает проблему — скажи.",
+ "2. Урежь до самой маленькой версии, которая уже полезна. Назови, что отложено.",
+ `3. Если это несколько задач — раздели: одна стори — один результат, который можно показать. Не больше ${INTAKE_MAX_SPLIT} дополнительных стори; мелкое не дроби.`,
+ "4. Проверь по списку стори проекта: не сделано ли уже, не противоречит ли, не нужно ли сначала другое.",
+ TONE,
+ "",
+ context,
+ "",
+ "## Пожелание",
+ `Название: ${story.title}`,
+ "Текст:",
+ story.description.trim() || "(только название)",
+ "",
+ 'Ответь ОДНОЙ строкой JSON без пояснений: {"goal":"…","comment":"…","title":"…","split":[{"title":"…","description":"…"}]}',
+ "goal — цель одной-двумя фразами. comment — 2–5 коротких фраз продакту: что берём, что режем, что настораживает. title — название этой стори после урезания (до 80 символов). split — остальные стори (пустой список, если делить не надо).",
+ ].join("\n");
+}
+
+export interface AnalystNote {
+ /** The story as the developer agent gets it. */
+ description: string;
+ criteria: string[];
+ outOfScope: string[];
+ assumptions: string[];
+ questions: IntakeQuestion[];
+ /** Plain words to the PM: what is contradictory or missing. */
+ comment: string;
+}
+
+export function analystPrompt(context: string, story: { title: string; description: string }, product: ProductNote | undefined, answers?: { questions: IntakeQuestion[]; answer: string }): string {
+ return [
+ "Ты — системный аналитик софтвер-фабрики. Преврати задачу в постановку, по которой ИИ-разработчик сделает ровно то, что нужно, а продакт сможет проверить результат.",
+ "1. Описание: что должно получиться и для кого — 3–8 фраз, без способа реализации.",
+ "2. Критерии приёмки: проверяемые снаружи утверждения («на странице каталога у товара видны фото, цена и кнопка „Купить“»), 3–8 штук.",
+ "3. Вне задачи: что сюда не входит, чтобы разработчик не сделал лишнего.",
+ "4. Сверь со стандартами, памятью и другими стори проекта: противоречия и пропущенные случаи назови в comment.",
+ `5. Вопросы — только те, от ответа на которые результат будет другим; не больше ${INTAKE_MAX_QUESTIONS}. У каждого — «default»: что ты сделаешь, если ответа не будет. Всё остальное реши сам и запиши в assumptions.`,
+ ...(answers ? ["6. Продакт ответил на твои вопросы — учти ответ, новых вопросов не задавай (questions — пустой список)."] : []),
+ TONE,
+ "",
+ context,
+ "",
+ "## Задача",
+ `Название: ${story.title}`,
+ "Текст продакта:",
+ story.description.trim() || "(только название)",
+ ...(product ? ["", "Решение продакт-менеджера фабрики:", `Цель: ${product.goal}`, product.comment] : []),
+ ...(answers ? ["", "Твои вопросы:", ...answers.questions.map((q, i) => `${i + 1}. ${q.q} (по умолчанию: ${q.default})`), "Ответ продакта:", answers.answer.trim()] : []),
+ "",
+ 'Ответь ОДНОЙ строкой JSON без пояснений: {"description":"…","criteria":["…"],"out_of_scope":["…"],"assumptions":["…"],"questions":[{"q":"…","default":"…"}],"comment":"…"}',
+ ].join("\n");
+}
+
+/** The first balanced JSON object of the text that has `field`. */
+function findJson(text: string, field: string): Record | null {
+ for (let i = text.indexOf("{"); i >= 0; i = text.indexOf("{", i + 1)) {
+ let depth = 0;
+ let inStr = false;
+ for (let j = i; j < text.length; j++) {
+ const c = text[j];
+ if (inStr) {
+ if (c === "\\") j++;
+ else if (c === '"') inStr = false;
+ continue;
+ }
+ if (c === '"') inStr = true;
+ else if (c === "{") depth++;
+ else if (c === "}" && --depth === 0) {
+ try {
+ const o = JSON.parse(text.slice(i, j + 1)) as Record;
+ if (o && typeof o === "object" && field in o) return o;
+ } catch {}
+ break;
+ }
+ }
+ }
+ return null;
+}
+
+const str = (v: unknown, max: number) => String(v ?? "").trim().slice(0, max);
+const list = (v: unknown, max: number, each = 500) => (Array.isArray(v) ? v.map((x) => str(x, each)).filter(Boolean).slice(0, max) : []);
+
+export function parseProductNote(text: string, fallbackTitle: string): ProductNote | null {
+ const o = findJson(text, "goal");
+ if (!o) return null;
+ const split = (Array.isArray(o.split) ? o.split : [])
+ .map((s) => ({ title: str((s as { title?: unknown })?.title, 200), description: str((s as { description?: unknown })?.description, 4000) }))
+ .filter((s) => s.title.length >= 3)
+ .slice(0, INTAKE_MAX_SPLIT);
+ const title = str(o.title, 200);
+ return { goal: str(o.goal, 1000), comment: str(o.comment, 3000), title: title.length >= 3 ? title : fallbackTitle, split };
+}
+
+export function parseAnalystNote(text: string): AnalystNote | null {
+ const o = findJson(text, "criteria");
+ if (!o) return null;
+ const criteria = list(o.criteria, 12);
+ const description = str(o.description, 6000);
+ if (!description || !criteria.length) return null;
+ const questions = (Array.isArray(o.questions) ? o.questions : [])
+ .map((q) => ({ q: str((q as { q?: unknown })?.q, 500), default: str((q as { default?: unknown })?.default, 500) }))
+ .filter((q) => q.q && q.default)
+ .slice(0, INTAKE_MAX_QUESTIONS);
+ return { description, criteria, outOfScope: list(o.out_of_scope ?? o.outOfScope, 10), assumptions: list(o.assumptions, 10), questions, comment: str(o.comment, 3000) };
+}
+
+/** The story text the developer agent works from. */
+export function intakeDescription(original: { title: string; description: string }, a: AnalystNote, decided: string[] = []): string {
+ const bullets = (items: string[]) => items.map((x) => `- ${x}`).join("\n");
+ return [
+ a.description,
+ "",
+ "## Критерии приёмки",
+ bullets(a.criteria),
+ ...(a.outOfScope.length ? ["", "## Вне задачи", bullets(a.outOfScope)] : []),
+ ...(a.assumptions.length || decided.length ? ["", "## Допущения", bullets([...a.assumptions, ...decided])] : []),
+ "",
+ "## Исходный запрос",
+ original.title + (original.description.trim() ? `\n\n${original.description.trim()}` : ""),
+ ].join("\n");
+}
+
+/** What the PM reads from the roles. */
+export function productMessage(p: ProductNote, splitKeys: string[]): string {
+ return [`Цель: ${p.goal}`, p.comment, ...(splitKeys.length ? [`Разделил на стори: эта и ${splitKeys.join(", ")}.`] : [])].filter(Boolean).join("\n\n");
+}
+export function analystMessage(a: AnalystNote): string {
+ const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n");
+ return [
+ a.comment,
+ `Критерии приёмки:\n${bullets(a.criteria)}`,
+ ...(a.assumptions.length ? [`Решил сам:\n${bullets(a.assumptions)}`] : []),
+ ...(a.questions.length ? ["Есть вопросы — отдельным сообщением. Не ответите — сделаю по вариантам по умолчанию."] : ["Вопросов нет — стори готова к работе."]),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+}
+export function questionsText(key: string, qs: IntakeQuestion[], waitMin: number): string {
+ return [
+ `Аналитик уточняет ${key}. Ответьте одним сообщением — или не отвечайте: через ${waitMin} мин возьму варианты по умолчанию.`,
+ ...qs.map((q, i) => `${i + 1}. ${q.q}\n По умолчанию: ${q.default}`),
+ ].join("\n\n");
+}
+
+/** A role's note on the story: an event shown among the story's comments and in the project chat. */
+export async function addIntakeNote(db: Db, task: Pick, role: IntakeRole, text: string): Promise {
+ await db.insert(events).values({ projectId: task.projectId, taskId: task.id, type: INTAKE_EVENT, payload: { role, text }, ...actorColumns() });
+ await notify(db, { type: "task_updated", taskId: task.id });
+}
+
+/** Ids of the tasks among `ids` that have intake notes (for tests and badges). */
+export async function tasksWithIntakeNotes(db: Db, ids: number[]): Promise> {
+ if (!ids.length) return new Set();
+ const rows = await db.select({ taskId: events.taskId }).from(events).where(and(inArray(events.taskId, ids), eq(events.type, INTAKE_EVENT)));
+ return new Set(rows.map((r) => r.taskId!));
+}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 1958bb6d..d74cee7e 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -253,6 +253,8 @@ export interface StoryComment {
login: string;
text: string;
createdAt: Date;
+ /** PEP-84: a note of «продакт» / «аналитик» rather than a person's comment. */
+ role?: "product" | "analyst";
}
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
@@ -269,9 +271,10 @@ export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number
}
export async function storyComments(db: Db, taskId: number): Promise {
- const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, COMMENT_EVENT))).orderBy(asc(events.id));
+ const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), inArray(events.type, [COMMENT_EVENT, "intake_note"]))).orderBy(asc(events.id));
return rows.map((e) => {
- const p = (e.payload ?? {}) as { login?: string; text?: string };
+ const p = (e.payload ?? {}) as { login?: string; text?: string; role?: "product" | "analyst" };
+ if (e.type === "intake_note") return { id: e.id, login: p.role === "product" ? "Продакт" : "Аналитик", text: p.text ?? "", createdAt: e.createdAt, role: p.role ?? "analyst" };
return { id: e.id, login: p.login ?? "?", text: p.text ?? "", createdAt: e.createdAt };
});
}
diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts
index dcb8b267..983793fb 100644
--- a/packages/runner/src/autonomy.ts
+++ b/packages/runner/src/autonomy.ts
@@ -32,6 +32,7 @@ import {
type Task,
type TaskRef,
projectAgentWarning,
+ intakePendingTasks,
} from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -288,7 +289,9 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
export async function readyBacklog(db: Db, projectId: number, backlog?: T[]): Promise {
const list = backlog ?? ((await listTasks(db, { projectId, statuses: ["backlog"] })) as unknown as T[]);
const blocked = await blockedTaskIds(db, projectId);
- return list.filter((t) => !blocked.has(t.id));
+ // 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));
}
/** Sessions that hold a WIP slot: their story is being worked on (not in review). */
diff --git a/packages/runner/src/claude-print.ts b/packages/runner/src/claude-print.ts
index d77fe847..4002e856 100644
--- a/packages/runner/src/claude-print.ts
+++ b/packages/runner/src/claude-print.ts
@@ -5,8 +5,9 @@ import { spawn } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { claudeTokenForProject, type Project } from "@peppa/core";
-import type { Db } from "@peppa/db";
+import { claudeTokenForProject, mayUseMachineLogin, type Project } from "@peppa/core";
+import { projects, type Db } from "@peppa/db";
+import { eq } from "drizzle-orm";
export interface ClaudePrintOptions {
bin: string;
@@ -31,6 +32,12 @@ export function envelopeText(stdout: string): string | null {
export async function claudePrint(db: Db, project: Pick, o: ClaudePrintOptions): Promise {
const token = await claudeTokenForProject(db, project).catch(() => null);
+ // PEP-84: without a Claude subscription in the pool the CLI would run on this machine's own
+ // login — fine for the platform's and allowlisted owners' projects, never for a self-registered one.
+ if (!token) {
+ const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, project.id));
+ if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) return { ok: false, error: `${o.who}: у проекта нет подписки Claude` };
+ }
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
try {
diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts
index a1e9e65b..68eea1bc 100644
--- a/packages/runner/src/flow.ts
+++ b/packages/runner/src/flow.ts
@@ -1,4 +1,5 @@
// PM-side moves on the task board and review acceptance (web and Telegram use these).
+import { releaseIntake } from "./intake.ts";
import { answerQuestion, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
import { tasks, projects, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -45,6 +46,8 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
const from = columnOf(ref.task.status);
let stopped = 0;
if (to === "in_progress") {
+ // PEP-84: the PM took the story before the roles finished — they let it go.
+ await releaseIntake(db, ref.task.id);
if ((await activeSessions(db, ref.task.id)).length === 0) await assertBudgetOpen(db, ref.task.id);
if (from !== "in_progress") await updateTask(db, ref, { status: "in_progress" });
// PEP-10: by the runner settings — a new runner, or a free/queued runner of the project.
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index 693525a8..7dfea5ca 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -21,6 +21,7 @@ export * from "./platform-build.ts";
export * from "./code.ts";
export * from "./agents-md.ts";
export * from "./project-subscription.ts";
+export * from "./intake.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
diff --git a/packages/runner/src/intake.ts b/packages/runner/src/intake.ts
new file mode 100644
index 00000000..cf666ecb
--- /dev/null
+++ b/packages/runner/src/intake.ts
@@ -0,0 +1,180 @@
+// PEP-84: runs «продакт» and «аналитик» over new backlog stories (see core/intake.ts). The
+// watchdog calls `intakeTick`; each story moves through product → analyst → (waiting for the
+// PM's answers | done). LLM calls run in the background of the tick (one story at a time per
+// process), so a slow model never holds the watchdog. The dispatcher skips stories the roles
+// have not finished with (`readyBacklog`), a PM who drags the card to work overrides them.
+import {
+ addIntakeNote,
+ analystMessage,
+ analystPrompt,
+ answerQuestion,
+ askPm,
+ createTask,
+ getAutonomy,
+ getIntakeSettings,
+ getIntakeState,
+ inAutonomyQuietHours,
+ intakeContext,
+ intakeDescription,
+ intakePending,
+ listTasks,
+ parseAnalystNote,
+ parseProductNote,
+ productMessage,
+ productPrompt,
+ questionsText,
+ setIntakeState,
+ updateTask,
+ type IntakeState,
+ type Project,
+ type Question,
+ type TaskRef,
+} from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { projects } from "@peppa/db";
+import { claudePrint } from "./claude-print.ts";
+import { onAnswer, resolveTaskById } from "./sessions.ts";
+
+const MAX_ATTEMPTS = 2;
+const inFlight = new Set();
+
+const ask = (db: Db, project: Project, prompt: string, who: string) =>
+ claudePrint(db, project, {
+ bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
+ model: process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
+ timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
+ prompt,
+ who,
+ });
+
+/** When the analyst stops waiting: `waitMin` from now, moved past the project's quiet hours. */
+function deadline(now: Date, waitMin: number, quiet: { quietFrom: number | null; quietTo: number | null }): number {
+ const at = new Date(now.getTime() + waitMin * 60_000);
+ if (quiet.quietTo != null && inAutonomyQuietHours(quiet, at)) {
+ const morning = new Date(at);
+ morning.setHours(quiet.quietTo, 0, 0, 0);
+ if (morning <= at) morning.setDate(morning.getDate() + 1);
+ return morning.getTime();
+ }
+ return at.getTime();
+}
+
+/** One step of a story; returns the new state. Throws on a model failure (the caller counts attempts). */
+async function step(db: Db, ref: TaskRef, state: IntakeState, now: Date): Promise {
+ const { project, task } = ref;
+ const context = await intakeContext(db, project, task);
+ if (state.stage === "product") {
+ const out = await ask(db, project, productPrompt(context, state.original), "продакт");
+ if (!out.ok) throw new Error(out.error);
+ const note = parseProductNote(out.text, state.original.title);
+ if (!note) throw new Error("продакт ответил не по формату");
+ const splitKeys: string[] = [];
+ for (const s of note.split) {
+ const extra = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: s.description });
+ // A split story is already cut by the product manager: the analyst takes it from here.
+ await setIntakeState(db, extra.task.id, { stage: "analyst", original: { title: s.title, description: s.description }, product: { ...note, title: s.title, split: [] }, attempts: 0 });
+ splitKeys.push(extra.key);
+ }
+ if (note.title !== task.title) await updateTask(db, ref, { title: note.title });
+ await addIntakeNote(db, task, "product", productMessage(note, splitKeys));
+ return { ...state, stage: "analyst", product: note, attempts: 0 };
+ }
+ if (state.stage === "analyst" || state.stage === "finalize") {
+ const answers = state.stage === "finalize" && state.analyst ? { questions: state.analyst.questions, answer: state.answer ?? "" } : undefined;
+ const out = await ask(db, project, analystPrompt(context, { title: task.title, description: state.original.description }, state.product, answers), "аналитик");
+ if (!out.ok) throw new Error(out.error);
+ const note = parseAnalystNote(out.text);
+ if (!note) throw new Error("аналитик ответил не по формату");
+ if (answers) note.questions = [];
+ await updateTask(db, ref, { description: intakeDescription(state.original, note) });
+ await addIntakeNote(db, task, "analyst", answers ? `Учёл ответ. ${analystMessage(note)}` : analystMessage(note));
+ if (!note.questions.length) return { ...state, stage: "done", analyst: note, attempts: 0 };
+ const settings = await getIntakeSettings(db, project.id);
+ const q = await askPm(db, ref, { kind: "question", text: questionsText(ref.key, note.questions, settings.waitMin) });
+ return { ...state, stage: "waiting", analyst: note, questionId: q.id, deadline: deadline(now, settings.waitMin, await getAutonomy(db, project.id)), attempts: 0 };
+ }
+ return state;
+}
+
+/** Nobody answered in time: the analyst's defaults become decisions, the story is ready. */
+async function goByDefaults(db: Db, ref: TaskRef, state: IntakeState): Promise {
+ const a = state.analyst!;
+ const decided = a.questions.map((q) => `${q.q} — ${q.default} (ответа не было, взят вариант по умолчанию)`);
+ await updateTask(db, ref, { description: intakeDescription(state.original, a, decided) });
+ if (state.questionId) await answerQuestion(db, state.questionId, "(ответа не было — аналитик взял варианты по умолчанию)", "system").catch(() => {});
+ await addIntakeNote(db, ref.task, "analyst", `Ответа не было — иду по вариантам по умолчанию:\n${a.questions.map((q) => `• ${q.q} → ${q.default}`).join("\n")}\nСтори готова к работе.`);
+ await setIntakeState(db, ref.task.id, { ...state, stage: "done" });
+}
+
+async function advance(db: Db, taskId: number, now: Date, log: (m: string) => void): Promise {
+ const ref = await resolveTaskById(db, taskId).catch(() => null);
+ if (!ref) return;
+ const settings = await getIntakeSettings(db, ref.project.id);
+ let state = await getIntakeState(db, taskId);
+ if (!intakePending(settings, ref.task, state)) return;
+ state ??= { stage: "product", original: { title: ref.task.title, description: ref.task.description ?? "" }, attempts: 0 };
+ if (state.stage === "waiting") {
+ if ((state.deadline ?? 0) <= now.getTime()) {
+ await goByDefaults(db, ref, state);
+ log(`${ref.key}: intake — no answer, defaults taken`);
+ }
+ return;
+ }
+ try {
+ // Several steps in a row: product → analyst without waiting for the next tick.
+ for (let i = 0; i < 3 && state.stage !== "waiting" && state.stage !== "done"; i++) {
+ state = await step(db, ref, state, now);
+ await setIntakeState(db, taskId, state);
+ log(`${ref.key}: intake → ${state.stage}`);
+ }
+ } catch (e) {
+ const attempts = state.attempts + 1;
+ // The roles must never hold a story for ever: after a couple of failures it goes on as written.
+ if (attempts >= MAX_ATTEMPTS) {
+ await setIntakeState(db, taskId, { ...state, stage: "done", attempts, note: (e as Error).message });
+ await addIntakeNote(db, ref.task, state.stage === "product" ? "product" : "analyst", `Не смог разобрать задачу (${(e as Error).message}) — стори идёт в работу как написана.`);
+ } else await setIntakeState(db, taskId, { ...state, attempts });
+ log(`${ref.key}: intake failed (${attempts}): ${(e as Error).message}`);
+ }
+}
+
+export interface IntakeTickOptions {
+ now?: Date;
+ log?: (m: string) => void;
+ /** Tests: wait for the model calls instead of leaving them in the background. */
+ wait?: boolean;
+}
+
+export async function intakeTick(db: Db, opts: IntakeTickOptions = {}): Promise {
+ const now = opts.now ?? new Date();
+ const log = opts.log ?? (() => {});
+ const jobs: Promise[] = [];
+ for (const { id } of await db.select({ id: projects.id }).from(projects)) {
+ const settings = await getIntakeSettings(db, id);
+ if (!settings.enabled) continue;
+ for (const t of await listTasks(db, { projectId: id, statuses: ["backlog"] })) {
+ if (inFlight.has(t.id) || !intakePending(settings, t, await getIntakeState(db, t.id))) continue;
+ inFlight.add(t.id);
+ jobs.push(advance(db, t.id, now, log).catch((e) => log(`intake ${t.id}: ${(e as Error).message}`)).finally(() => inFlight.delete(t.id)));
+ }
+ }
+ if (opts.wait) await Promise.all(jobs);
+}
+
+/** The PM answered the analyst's questions: the analyst finishes the story with the answer. */
+export async function onIntakeAnswer(db: Db, q: Question, answer: string): Promise {
+ if (!q.taskId) return false;
+ const state = await getIntakeState(db, q.taskId);
+ if (!state || state.stage !== "waiting" || state.questionId !== q.id) return false;
+ await setIntakeState(db, q.taskId, { ...state, stage: "finalize", answer, attempts: 0 });
+ return true;
+}
+onAnswer(onIntakeAnswer);
+
+/** The PM dragged the card to work (or the story left the backlog): the roles let it go. */
+export async function releaseIntake(db: Db, taskId: number): Promise {
+ const state = await getIntakeState(db, taskId);
+ if (!state || state.stage === "done") return;
+ if (state.questionId) await answerQuestion(db, state.questionId, "(стори взята в работу без ответа)", "system").catch(() => {});
+ await setIntakeState(db, taskId, { ...state, stage: "done", note: "взята в работу вручную" });
+}
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index c8e511de..68f9d6ae 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -4,7 +4,7 @@
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { createProject, NEW_PROJECT_AUTONOMY, setAutonomy, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
+import { createProject, NEW_PROJECT_AUTONOMY, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { eq, or } from "drizzle-orm";
@@ -131,6 +131,11 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise log(`ci: ${(e as Error).message}`));
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index bdd5fe10..2d820d20 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -32,6 +32,7 @@ import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
+import { intakeTick } from "./intake.ts";
import { budgetTick } from "./budgets.ts";
import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
import { serveRunnerCommands, type RunnerService } from "./runner-service.ts";
@@ -83,6 +84,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise {
// 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}`));
// 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}`));
// 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}`));
diff --git a/packages/testkit/bin/mock-intake b/packages/testkit/bin/mock-intake
new file mode 100755
index 00000000..df81e6e7
--- /dev/null
+++ b/packages/testkit/bin/mock-intake
@@ -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-intake.ts" "$@"
diff --git a/packages/testkit/src/mock-intake.ts b/packages/testkit/src/mock-intake.ts
new file mode 100644
index 00000000..6245965d
--- /dev/null
+++ b/packages/testkit/src/mock-intake.ts
@@ -0,0 +1,44 @@
+// mock-intake (PEP-84): stands in for `claude -p --output-format json` as «продакт» and «аналитик».
+// Reads the prompt on stdin and answers with the CLI's JSON envelope. The role is read off the
+// prompt's first line. Behaviour comes from MOCK_INTAKE_SCENARIO (a JSON file):
+// { "product": {goal, comment, title, split[]}, "analyst": {description, criteria[], out_of_scope[],
+// assumptions[], questions[{q, default}], comment}, "garbage": false, "fail": false }
+// Without a scenario: the product manager keeps the story as is, the analyst asks one question
+// (none once the prompt carries the PM's answer). Every call is appended to .log.jsonl.
+import { appendFileSync, existsSync, readFileSync } from "node:fs";
+
+interface Scenario {
+ product?: object;
+ analyst?: { questions?: unknown[] } & Record;
+ garbage?: boolean;
+ fail?: boolean;
+}
+
+const file = process.env.MOCK_INTAKE_SCENARIO;
+const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
+const prompt = readFileSync(0, "utf8");
+const role = prompt.startsWith("Ты — продакт-менеджер") ? "product" : "analyst";
+const answered = /Ответ продакта:\n/.test(prompt);
+const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? "";
+if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
+if (!process.argv.includes("-p")) {
+ console.error("mock-intake: expected -p (non-interactive print mode)");
+ process.exit(2);
+}
+if (sc.fail) {
+ console.error("mock-intake: API Error: 529 overloaded");
+ process.exit(1);
+}
+const product = sc.product ?? { goal: `Сделать: ${title}`, comment: "Берём как есть. Лишнего нет.", title, split: [] };
+const analyst = {
+ description: `Нужно: ${title}.`,
+ criteria: ["Результат виден пользователю", "Ошибки показаны понятным текстом"],
+ out_of_scope: ["Оформление сверх необходимого"],
+ assumptions: ["Язык интерфейса — русский"],
+ questions: [{ q: "Нужна ли мобильная версия?", default: "Да, страница открывается с телефона" }],
+ comment: "В запросе не сказано, кто пользователь.",
+ ...sc.analyst,
+};
+if (answered) analyst.questions = [];
+const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "product" ? product : analyst);
+process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n");
diff --git a/packages/testkit/test/intake.test.ts b/packages/testkit/test/intake.test.ts
new file mode 100644
index 00000000..2e235a7b
--- /dev/null
+++ b/packages/testkit/test/intake.test.ts
@@ -0,0 +1,165 @@
+// PEP-84: «продакт» and «аналитик» refine a new story before the dispatcher takes it (mock-intake).
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, before, describe, test } from "node:test";
+import { core, db, runner, teardown } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
+const TMP = mkdtempSync(join(tmpdir(), "peppa-intake-"));
+const scenario = join(TMP, "scenario.json");
+const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; title: string; answered: boolean; answer: string | null; hasContext: boolean; prompt: string });
+const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s));
+
+type User = Awaited>;
+let pm: User;
+let seq = 0;
+before(async () => {
+ process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
+ process.env.MOCK_INTAKE_SCENARIO = scenario;
+ setScenario({});
+ pm = await core.upsertUserFromGitea(db, { id: 8401, login: "mock-pm-8401" }, { access_token: "x" });
+});
+after(teardown);
+
+async function intakeProject() {
+ const n = ++seq;
+ const ws = join(TMP, `ws${n}`);
+ mkdirSync(join(ws, ".peppa"), { recursive: true });
+ writeFileSync(join(ws, "AGENTS.md"), "# AGENTS.md\n\n## Соглашения\n- Интерфейс на русском\n");
+ writeFileSync(join(ws, ".peppa/memory.md"), "# Память проекта\n\n## Решения\n- Оплата только картой\n");
+ const p = await core.createProject(db, { slug: `mock-intake-${n}`, key: `MIN${String.fromCharCode(64 + n)}`, name: `Intake ${n}`, giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
+ await core.setIntakeSettings(db, p.id, { enabled: true });
+ return p;
+}
+const tick = (now?: Date) => runner.intakeTick(db, { wait: true, now });
+const story = async (key: string) => (await core.resolveTask(db, key)).task;
+
+describe("Продакт и аналитик", () => {
+ test("Scenario: стори проходит продакта и аналитика; вопрос с вариантом по умолчанию; ответ PM учитывается", async () => {
+ const p = await intakeProject();
+ const done = await core.createTask(db, { projectId: p.id, title: "Каталог товаров" });
+ await core.setIntakeState(db, done.task.id, { stage: "done", original: { title: "", description: "" }, attempts: 0 });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Корзина", description: "Хочу чтобы можно было складывать товары" });
+ assert.deepEqual([...(await core.intakePendingTasks(db, p.id)).entries()], [[ref.task.id, "new"]]);
+ assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [done.task.id], "the dispatcher does not see a story the roles hold");
+
+ await tick();
+ let state = (await core.getIntakeState(db, ref.task.id))!;
+ assert.equal(state.stage, "waiting");
+ const mine = calls().filter((c) => c.title === "Корзина");
+ assert.deepEqual(mine.map((c) => c.role), ["product", "analyst"]);
+ assert.ok(mine.every((c) => c.hasContext), "the roles get the project's context");
+ assert.match(mine[0]!.prompt, /Интерфейс на русском/, "AGENTS.md");
+ assert.match(mine[0]!.prompt, /Оплата только картой/, "memory");
+ assert.match(mine[0]!.prompt, /\[backlog\] Каталог товаров/, "other stories");
+ assert.match(mine[0]!.prompt, /Не хвали/, "no flattery");
+
+ let t = await story(ref.key);
+ assert.match(t.description!, /## Критерии приёмки\n- Результат виден пользователю/);
+ assert.match(t.description!, /## Исходный запрос\nКорзина\n\nХочу чтобы можно было складывать товары/, "the PM's words are kept");
+ const comments = await core.storyComments(db, ref.task.id);
+ assert.deepEqual(comments.map((c) => c.role), ["product", "analyst"]);
+ assert.equal(comments[0]!.login, "Продакт");
+ const [q] = await core.pendingQuestions(db, p.id);
+ assert.equal(q!.id, state.questionId);
+ assert.match(q!.text, /Нужна ли мобильная версия\?\n\s+По умолчанию: Да, страница открывается с телефона/);
+
+ // 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");
+ await tick();
+ state = (await core.getIntakeState(db, ref.task.id))!;
+ assert.equal(state.stage, "done");
+ const last = calls().at(-1)!;
+ assert.equal(last.answered, true);
+ assert.equal(last.answer, "Мобильная не нужна, только ноутбук");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0);
+ assert.deepEqual((await runner.readyBacklog(db, p.id)).map((x) => x.id).sort(), [done.task.id, ref.task.id].sort(), "now the dispatcher may take it");
+ t = await story(ref.key);
+ assert.match(t.description!, /## Критерии приёмки/);
+ });
+
+ test("Scenario: PM молчит — после срока аналитик идёт по вариантам по умолчанию и не ждёт", async () => {
+ const p = await intakeProject();
+ await core.setIntakeSettings(db, p.id, { waitMin: 30 });
+ await core.setAutonomy(db, p.id, { quietFrom: null, quietTo: null });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" });
+ const t0 = new Date("2026-11-16T10:00:00");
+ await tick(t0);
+ const waiting = (await core.getIntakeState(db, ref.task.id))!;
+ assert.equal(waiting.stage, "waiting");
+ assert.equal(waiting.deadline, t0.getTime() + 30 * 60_000);
+ await tick(new Date(t0.getTime() + 29 * 60_000));
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "waiting", "still waiting before the deadline");
+ const before = calls().length;
+ await tick(new Date(t0.getTime() + 31 * 60_000));
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done");
+ assert.equal(calls().length, before, "no extra model call for the defaults");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the question is closed");
+ assert.match((await story(ref.key)).description!, /## Допущения[\s\S]*Нужна ли мобильная версия\? — Да, страница открывается с телефона \(ответа не было/);
+ assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /Ответа не было — иду по вариантам по умолчанию/);
+
+ // Night: the deadline moves to the morning of the project's quiet hours.
+ await core.setAutonomy(db, p.id, { quietFrom: 22, quietTo: 9 });
+ const night = await core.createTask(db, { projectId: p.id, title: "Ночная" });
+ await tick(new Date("2026-11-16T23:50:00"));
+ assert.equal(new Date((await core.getIntakeState(db, night.task.id))!.deadline!).toISOString(), new Date("2026-11-17T09:00:00").toISOString());
+ });
+
+ test("Scenario: продакт делит запрос на стори и переименовывает; без вопросов стори сразу готова", async () => {
+ const p = await intakeProject();
+ setScenario({
+ product: { goal: "Продавать онлайн", comment: "Это три задачи. Доставку откладываю.", title: "Каталог: список товаров", split: [{ title: "Тележка", description: "Сложить товары" }, { title: "Оплата картой", description: "Оплатить заказ" }] },
+ analyst: { questions: [] },
+ });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Сделай интернет-магазин" });
+ await tick();
+ const all = await core.listTasks(db, { projectId: p.id });
+ assert.deepEqual(all.map((t) => t.title).sort(), ["Каталог: список товаров", "Оплата картой", "Тележка"]);
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done");
+ assert.match((await core.storyComments(db, ref.task.id))[0]!.text, /Разделил на стори: эта и MIN\w-2, MIN\w-3/);
+ // The split stories skip the product manager: the analyst takes them on the next tick.
+ await tick();
+ for (const t of all) assert.equal((await core.getIntakeState(db, t.id))!.stage, "done");
+ assert.equal(calls().filter((c) => c.role === "product" && ["Тележка", "Оплата картой"].includes(c.title)).length, 0);
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0);
+ setScenario({});
+ });
+
+ test("роли не держат стори: сбой модели, ручной запуск, выключенное уточнение, старый бэклог", async () => {
+ const p = await intakeProject();
+ setScenario({ garbage: true });
+ const broken = await core.createTask(db, { projectId: p.id, title: "Сломанная" });
+ await tick();
+ assert.equal((await core.getIntakeState(db, broken.task.id))!.stage, "product", "one failure — try again");
+ await tick();
+ const gaveUp = (await core.getIntakeState(db, broken.task.id))!;
+ assert.equal(gaveUp.stage, "done");
+ assert.match(gaveUp.note!, /не по формату/);
+ assert.equal((await story(broken.key)).description ?? "", "", "the story goes on as written");
+ assert.match((await core.storyComments(db, broken.task.id)).at(-1)!.text, /стори идёт в работу как написана/);
+ setScenario({});
+
+ // The PM takes the story to work while the analyst waits: the question is closed.
+ const manual = await core.createTask(db, { projectId: p.id, title: "Ручная" });
+ await tick();
+ assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "waiting");
+ await runner.releaseIntake(db, manual.task.id);
+ assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "done");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0);
+
+ // Off by default; turning it on leaves the old backlog alone.
+ const off = await core.createProject(db, { slug: "mock-intake-off", key: "MINOFF", name: "Off", giteaOwner: "x", workspacePath: join(TMP, "off"), ownerId: pm.id });
+ const old = await core.createTask(db, { projectId: off.id, title: "Старая" });
+ assert.equal((await core.getIntakeSettings(db, off.id)).enabled, false);
+ await core.setIntakeSettings(db, off.id, { enabled: true }, new Date(Date.now() + 1000));
+ const n = calls().length;
+ await tick();
+ assert.equal(calls().length, n);
+ assert.equal(await core.getIntakeState(db, old.task.id), null);
+ });
+});
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 9b710bff..365405f7 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -202,3 +202,17 @@ describe("PEP-77: прогресс по всем проектам", () => {
}
});
});
+
+describe("новый проект: настройки по умолчанию", () => {
+ test("подписка владельца подключается сама; стори берутся сами; продакт и аналитик включены", async () => {
+ const first = await provision({ slug: "mock-defaults-a", key: "MDFA" });
+ assert.equal(await core.projectPool(db, first.id), null, "no own subscription yet");
+ assert.equal(core.autonomyLevel(await core.getAutonomy(db, first.id)), "self");
+ assert.equal((await core.getIntakeSettings(db, first.id)).enabled, true);
+
+ const sub = await core.createSubscription(db, { provider: "claude", name: "mock-defaults Claude", authKind: "oauth", secret: "sk-ant-oat01-" + "d".repeat(40), createdBy: alice.id });
+ const pool = await core.createPool(db, { name: "mock-defaults pool", subscriptionIds: [sub.id], createdBy: alice.id });
+ const second = await provision({ slug: "mock-defaults-b", key: "MDFB" });
+ assert.equal((await core.projectPool(db, second.id))!.id, pool.id, "connected once — not asked again");
+ });
+});
--
2.45.2
From 01d58973abc0b51549841d0c10da3673366a0426 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 22:57:07 +0500
Subject: [PATCH 021/428] =?UTF-8?q?PEP-85:=20every=20user's=20own=20Telegr?=
=?UTF-8?q?am=20bot=20=E2=80=94=20token=20from=20BotFather,=20polled=20and?=
=?UTF-8?q?=20answered=20through=20it?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/bot/src/bot.ts | 105 +-
apps/web/app/(app)/actions.ts | 26 +-
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/settings/page.tsx | 113 +-
.../proposal.md | 18 +
.../specs/telegram-bot/spec.md | 24 +
.../tasks.md | 5 +
openspec/specs/telegram-bot/spec.md | 23 +
packages/core/src/onboarding.ts | 6 +-
packages/core/src/secrets-audit.ts | 1 +
packages/core/src/telegram.ts | 89 +-
.../db/migrations/0016_user_telegram_bot.sql | 2 +
.../db/migrations/meta/0016_snapshot.json | 4120 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 4 +
packages/testkit/src/mock-telegram.ts | 6 +-
packages/testkit/test/own-bot.test.ts | 118 +
18 files changed, 4633 insertions(+), 36 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md
create mode 100644 packages/db/migrations/0016_user_telegram_bot.sql
create mode 100644 packages/db/migrations/meta/0016_snapshot.json
create mode 100644 packages/testkit/test/own-bot.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index a87fd48f..cff9faae 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,6 +41,7 @@
- **Своя подписка (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`)
+- **Свой 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-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`
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 551720cd..419df6e8 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -12,6 +12,7 @@ import {
beat,
checkServices,
claimUpdate,
+ userBots,
dueOutbox,
enqueueTelegram,
finishUpdate,
@@ -66,6 +67,7 @@ import {
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
+import { AsyncLocalStorage } from "node:async_hooks";
import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
@@ -88,6 +90,10 @@ export interface BotOptions {
heartbeatIntervalMs?: number;
// How often to check PRAGMA data_version for writes the notify() poke missed.
changesIntervalMs?: number;
+ /** PEP-85: API client of a user's own bot (tests point it at a second mock). */
+ userApi?: (token: string) => TelegramApi;
+ /** How often the list of users' own bots is re-read. */
+ userBotsIntervalMs?: number;
log?: (msg: string) => void;
}
@@ -120,9 +126,81 @@ function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null;
}
export function createBot(o: BotOptions) {
- const { db, api } = o;
+ const { db } = o;
const log = o.log ?? (() => {});
const abort = new AbortController();
+
+ // ── PEP-85: users' own bots ────────────────────────────────────────────────────
+ // Every bot is polled by its own loop; an update is handled inside `via.run(bot)`, so replies
+ // go out through the bot the message came to. Outside an update (outbox, digests) the bot is
+ // picked by the chat: the owner's private chat belongs to their bot, everything else — the
+ // platform's shared bot.
+ interface OwnBot {
+ userId: number;
+ token: string;
+ api: TelegramApi;
+ stop: AbortController;
+ }
+ const via = new AsyncLocalStorage();
+ const ownBots = new Map();
+ const ownByChat = new Map();
+ const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
+ /** The same surface as TelegramApi, routed to the right bot per call. */
+ const api = {
+ call: (method: string, params: Record = {}, timeoutMs?: number) => pick(params.chat_id).call(method, params, timeoutMs),
+ sendMessage: (chatId: number, text: string, extra: Record = {}) => pick(chatId).sendMessage(chatId, text, extra),
+ answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text),
+ getFile: (fileId: string) => pick().getFile(fileId),
+ downloadFile: (filePath: string) => pick().downloadFile(filePath),
+ getMe: () => o.api.getMe(),
+ getUpdates: (offset: number, timeoutSec: number, signal?: AbortSignal) => o.api.getUpdates(offset, timeoutSec, signal),
+ };
+
+ /** Re-reads the connected bots: starts a poll loop for a new one, stops a removed or re-issued one. */
+ async function syncOwnBots(): Promise {
+ const list = await userBots(db);
+ const seen = new Set();
+ ownByChat.clear();
+ for (const b of list) {
+ seen.add(b.userId);
+ let bot = ownBots.get(b.userId);
+ if (bot && bot.token !== b.token) {
+ bot.stop.abort();
+ bot = undefined;
+ }
+ if (!bot) {
+ bot = { userId: b.userId, token: b.token, api: (o.userApi ?? ((t) => new TelegramApi(t, process.env.TELEGRAM_API_URL)))(b.token), stop: new AbortController() };
+ ownBots.set(b.userId, bot);
+ log(`own bot @${b.username} of user #${b.userId}: polling`);
+ void ownPollLoop(bot);
+ }
+ if (b.chatId != null) ownByChat.set(b.chatId, bot);
+ }
+ for (const [userId, bot] of ownBots) {
+ if (seen.has(userId)) continue;
+ bot.stop.abort();
+ ownBots.delete(userId);
+ log(`own bot of user #${userId}: stopped`);
+ }
+ }
+
+ async function ownPollLoop(bot: OwnBot): Promise {
+ while (!abort.signal.aborted && !bot.stop.signal.aborted) {
+ try {
+ let offset = await getOffset(db, bot.userId);
+ const updates = await bot.api.getUpdates(offset, o.pollTimeoutSec ?? 25, bot.stop.signal);
+ for (const u of updates) {
+ await via.run(bot, () => handleUpdate(u));
+ offset = u.update_id + 1;
+ await setOffset(db, offset, bot.userId);
+ }
+ } catch (e) {
+ // A revoked token (401) keeps failing: back off instead of hammering Telegram.
+ log(`own bot #${bot.userId} poll: ${(e as Error).message}`);
+ await sleep(e instanceof TelegramError && e.code === 401 ? 60_000 : 3000);
+ }
+ }
+ }
let reconcileQueued = false;
let wakeOutbox: (() => void) | null = null;
@@ -495,8 +573,9 @@ export function createBot(o: BotOptions) {
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
- const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username });
+ 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}`);
scheduleReconcile();
return "done";
@@ -506,6 +585,9 @@ export function createBot(o: BotOptions) {
}
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
if (!user) return "ignored";
+ // PEP-85: a user's own bot serves its owner only.
+ const own = via.getStore();
+ if (own && own.userId !== user.id) return "ignored";
// PEP-48: what follows is done by this user through Telegram.
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
@@ -612,13 +694,14 @@ export function createBot(o: BotOptions) {
}
async function handleUpdate(u: TgUpdate): Promise {
- if (!(await claimUpdate(db, u.update_id))) return;
+ const botUserId = via.getStore()?.userId;
+ if (!(await claimUpdate(db, u.update_id, botUserId))) return;
try {
const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored";
- await finishUpdate(db, u.update_id, r);
+ await finishUpdate(db, u.update_id, r, botUserId);
} catch (e) {
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
- await finishUpdate(db, u.update_id, "failed");
+ await finishUpdate(db, u.update_id, "failed", botUserId);
}
}
@@ -675,6 +758,13 @@ export function createBot(o: BotOptions) {
}
}
+ async function ownBotsLoop() {
+ while (!abort.signal.aborted) {
+ await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
+ await sleep(o.userBotsIntervalMs ?? 10_000);
+ }
+ }
+
async function monitorLoop() {
while (!abort.signal.aborted) {
try {
@@ -694,16 +784,19 @@ export function createBot(o: BotOptions) {
reconcile,
flushOutbox,
handleUpdate,
+ syncOwnBots,
async start() {
const me = await api.getMe();
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
log(`bot @${me.username} started`);
unlisten = await listenEvents("bot", () => scheduleReconcile());
- loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]);
+ await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
+ loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop(), ownBotsLoop()]);
return me;
},
async stop() {
abort.abort();
+ for (const b of ownBots.values()) b.stop.abort();
wakeOutbox?.();
await unlisten?.().catch(() => {});
await loops;
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 815c0d41..29f6a15c 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -21,6 +21,8 @@ import {
updateIncidentSettings,
setReviewSettings,
setIntakeSettings,
+ setUserBot,
+ clearUserBot,
type IncidentPolicy,
getUser,
isSuperadmin,
@@ -419,9 +421,10 @@ export async function pairTelegram(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const token = loadEnv().TELEGRAM_BOT_TOKEN;
- const bot = await getSetting<{ username: string }>(db, "telegram.bot");
- if (!token || !bot) throw new PeppaError("Telegram-бот Пеппы не запущен");
- return `https://t.me/${bot.username}?start=${await createPairingCode(db, token, user.id)}`;
+ // 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-бот Пеппы не запущен");
+ return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
});
}
@@ -705,3 +708,20 @@ export async function saveIntakeSettingsAction(f: FormData) {
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
});
}
+
+// ── PEP-85: the user's own Telegram bot ────────────────────────────────────────────
+export async function connectOwnBotAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await setUserBot(db, user.id, String(f.get("token") ?? ""));
+ return "/settings?bot=connected#telegram";
+ });
+}
+
+export async function disconnectOwnBotAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await clearUserBot(db, user.id);
+ return "/settings#telegram";
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 5917c083..fd64b22f 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -72,6 +72,7 @@ export default async function Help() {
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
+ Telegram — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда /newbot ), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.
Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index b64fb563..29b61f42 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -1,6 +1,6 @@
import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
-import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
+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";
@@ -8,12 +8,20 @@ import { EgovSign } from "@/components/EgovSign";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
+import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
const back = { back: "/settings" };
+function StepNum({ n, done }: { n: number; done: boolean }) {
+ return (
+
+ {done ? "✓" : n}
+
+ );
+}
+
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
@@ -27,9 +35,10 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
);
}
-export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string }> }) {
+export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string; bot?: string }> }) {
const user = await requireUser();
- const { error, egov, notify } = await searchParams;
+ const { error, egov, notify, bot } = await searchParams;
+ const hasBot = !!user.telegramBotUsername;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
const apps = await connectedApps(db, user.id);
@@ -38,6 +47,76 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const myProjects = await listUserProjects(db, user.id);
const pushSubs = await userPushSubscriptions(db, user.id);
const vapid = await vapidPublicKey(db);
+ // PEP-85: the three steps of connecting an own bot (shown when Telegram is not paired, or to switch).
+ const ownBotSteps = (
+
+
+ Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
+
+
+
+
+
+
Создайте бота в Telegram
+
+ Откройте @BotFather (официальный бот Telegram), отправьте ему /newbot , придумайте название и адрес — адрес должен заканчиваться на bot , например{" "}
+ my_factory_bot .
+
+ {!hasBot && (
+
+ Открыть BotFather
+
+ )}
+
+
+
+
+
+ Вставьте токен бота
+ {hasBot ? (
+
+ Подключён @{user.telegramBotUsername} . Токен хранится зашифрованным.
+
+ ) : (
+ <>
+ BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
+
+
+
+ Подключить бота
+
+ >
+ )}
+
+
+
+
+
+ Откройте своего бота и нажмите Start
+ Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.
+ {hasBot && (
+
+
+ Открыть @{user.telegramBotUsername}
+
+ )}
+
+
+
+ {hasBot ? (
+
+
+ Отключить этого бота
+
+ ) : (
+
+
+ Не хотите создавать бота?
+ Использовать общего бота Пеппы
+
+ )}
+
+ );
return (
@@ -111,6 +190,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
{user.egovIin && egov === "linked" &&
eGov привязан — теперь можно входить по QR }
+ {bot === "connected" && Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start. }
{user.telegramChatId ? (
}
>
- Вопросы агентов из ваших и общих проектов приходят в этот чат.
+ Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота @{user.telegramBotUsername} > : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
) : (
-
-
- Привязать Telegram
-
- }
- >
- Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
-
+ ownBotSteps
+ )}
+ {user.telegramChatId && !hasBot && (
+
+ {ownBotSteps}
+
+ )}
+ {user.telegramChatId && hasBot && (
+
+
+ Отключить бота @{user.telegramBotUsername}
+
)}
diff --git a/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md
new file mode 100644
index 00000000..ed14bcef
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md
@@ -0,0 +1,18 @@
+# PEP-85: свой Telegram-бот у каждого пользователя
+
+## Why
+PM: у каждого пользователя должен быть свой Telegram-бот, через который он управляет своей фабрикой. Сейчас бот один на
+всех (`TELEGRAM_BOT_TOKEN`), у пользователей с ним только личные чаты.
+
+## What Changes
+- `users.telegram_bot_token_enc` (шифруется, входит в ротацию `PEPPA_SECRET`) и `telegram_bot_username` — миграция 0016.
+- core/telegram.ts: `verifyBotToken` (getMe у Telegram), `setUserBot` (проверка, один бот — один пользователь, сброс привязки чата),
+ `clearUserBot`, `userBots`. Код привязки, пришедший через свой бот, привязывает только его владельца; общий бот не привязывает
+ того, у кого есть свой. Offset и id обновлений — отдельные на каждого бота.
+- Бот-процесс: `syncOwnBots` раз в 10 с запускает и останавливает опрос своих ботов; обновление обрабатывается «через» бота,
+ в который пришло (AsyncLocalStorage); исходящие (вопросы, «готово», дайджест) уходят через бота владельца чата, остальное —
+ через общий. Свой бот отвечает только владельцу. Отозванный токен (401) — пауза минуту между попытками.
+- Веб «Настройки → Telegram»: три шага (BotFather → токен → Start в своём боте); общий бот — запасной вариант; у привязанных
+ к общему — «Перейти на своего бота». Шаг онбординга переименован.
+
+Вне scope: группы и каналы через свой бот (остаются на общем), вебхуки вместо опроса. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md
new file mode 100644
index 00000000..a55d9ddd
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md
@@ -0,0 +1,24 @@
+## ADDED Requirements
+
+### Requirement: Свой бот пользователя
+Пользователь SHALL подключать собственного Telegram-бота, вставив его токен в
+«Настройки → Telegram»; токен проверяется у Telegram и хранится зашифрованным. Вопросы
+агентов и сообщения его проектов SHALL приходить ему из его бота, а его ответы — приниматься
+через него. Свой бот SHALL отвечать только владельцу.
+
+#### Scenario: Подключение
+- **WHEN** пользователь вставляет токен от BotFather и затем нажимает Start в своём боте по ссылке из Пеппы
+- **THEN** чат привязан, следующий вопрос агента приходит из его бота, из общего бота — ничего
+
+#### Scenario: Неверный токен
+- **WHEN** пользователь вставляет строку, которую Telegram не принимает
+- **THEN** бот не подключён, показано, что токен нужно скопировать целиком
+
+#### Scenario: Чужой человек
+- **WHEN** в бот пользователя пишет другой человек или приходит чужой код привязки
+- **THEN** бот не привязывает его и на команды не отвечает
+
+#### Scenario: Общий бот
+- **GIVEN** пользователь без своего бота, привязанный к общему
+- **WHEN** агент его проекта задаёт вопрос
+- **THEN** вопрос приходит из общего бота, как раньше
diff --git a/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md
new file mode 100644
index 00000000..f0e7d2ab
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md
@@ -0,0 +1,5 @@
+- [x] 1 Схема и миграция 0016, шифрованная колонка в ревизии секретов
+- [x] 2 core: проверка токена, подключение и отключение, привязка только владельца, offset и id по ботам
+- [x] 3 Бот-процесс: опрос своих ботов, маршрутизация ответов и исходящих
+- [x] 4 Веб: шаги подключения, действия, онбординг
+- [x] 5 `own-bot.test.ts` на двух mock-telegram, регресс `bot.test.ts`, `openspec validate`
diff --git a/openspec/specs/telegram-bot/spec.md b/openspec/specs/telegram-bot/spec.md
index cd6cd845..4dd57dcd 100644
--- a/openspec/specs/telegram-bot/spec.md
+++ b/openspec/specs/telegram-bot/spec.md
@@ -81,3 +81,26 @@ Telegram-бот Пеппы: однократная обработка updates,
- **GIVEN** у пользователя в проектах работают 2 сессии и открыт 1 вопрос
- **WHEN** он пишет `/status`
- **THEN** бот отвечает «Активные сессии: 2» со списком и «Открытых вопросов: 1»
+
+### Requirement: Свой бот пользователя
+Пользователь SHALL подключать собственного Telegram-бота, вставив его токен в
+«Настройки → Telegram»; токен проверяется у Telegram и хранится зашифрованным. Вопросы
+агентов и сообщения его проектов SHALL приходить ему из его бота, а его ответы — приниматься
+через него. Свой бот SHALL отвечать только владельцу.
+
+#### Scenario: Подключение
+- **WHEN** пользователь вставляет токен от BotFather и затем нажимает Start в своём боте по ссылке из Пеппы
+- **THEN** чат привязан, следующий вопрос агента приходит из его бота, из общего бота — ничего
+
+#### Scenario: Неверный токен
+- **WHEN** пользователь вставляет строку, которую Telegram не принимает
+- **THEN** бот не подключён, показано, что токен нужно скопировать целиком
+
+#### Scenario: Чужой человек
+- **WHEN** в бот пользователя пишет другой человек или приходит чужой код привязки
+- **THEN** бот не привязывает его и на команды не отвечает
+
+#### Scenario: Общий бот
+- **GIVEN** пользователь без своего бота, привязанный к общему
+- **WHEN** агент его проекта задаёт вопрос
+- **THEN** вопрос приходит из общего бота, как раньше
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index d92056f6..03126708 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -53,9 +53,9 @@ export async function onboardingChecklist(db: Db, user: Pick db.select({ id: users.id, enc: users.accessTokenEnc }).from(users).where(isNotNull(users.accessTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ accessTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "users", column: "refresh_token_enc", rows: () => db.select({ id: users.id, enc: users.refreshTokenEnc }).from(users).where(isNotNull(users.refreshTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ refreshTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "users", column: "claude_token_enc", rows: () => db.select({ id: users.id, enc: users.claudeTokenEnc }).from(users).where(isNotNull(users.claudeTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ claudeTokenEnc: enc }).where(eq(users.id, id)) },
+ { table: "users", column: "telegram_bot_token_enc", rows: () => db.select({ id: users.id, enc: users.telegramBotTokenEnc }).from(users).where(isNotNull(users.telegramBotTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ telegramBotTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "subscriptions", column: "secret_enc", rows: () => db.select({ id: subscriptions.id, enc: subscriptions.secretEnc }).from(subscriptions).where(isNotNull(subscriptions.secretEnc)), set: (id: number, enc: string) => db.update(subscriptions).set({ secretEnc: enc }).where(eq(subscriptions.id, id)) },
{ table: "project_secrets", column: "value_enc", rows: () => db.select({ id: projectSecrets.id, enc: projectSecrets.valueEnc }).from(projectSecrets), set: (id: number, enc: string) => db.update(projectSecrets).set({ valueEnc: enc }).where(eq(projectSecrets.id, id)) },
];
diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts
index f14ef30e..39ac1194 100644
--- a/packages/core/src/telegram.ts
+++ b/packages/core/src/telegram.ts
@@ -2,6 +2,8 @@ import { createHmac, randomBytes } from "node:crypto";
import { projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db";
import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+import { decrypt, encrypt } from "./crypto.ts";
+import { PeppaError } from "./errors.ts";
import type { User } from "./users.ts";
export type OutboxRow = typeof telegramOutbox.$inferSelect;
@@ -24,13 +26,19 @@ export async function acceptPairing(
db: Db,
secret: string,
code: string,
- who: { chatId: number; userId: number; username?: string | null },
+ who: { chatId: number; userId: number; username?: string | null; /** PEP-85: the owner of the bot the code came through (absent = the shared bot). */ botUserId?: number },
): Promise {
const key = pairKey(code, secret);
const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key);
if (!saved) return null;
await deleteSetting(db, key);
if (Date.now() >= saved.expiresAt) return null;
+ // A user's own bot pairs only its owner; the shared bot never pairs someone who has their own.
+ if (who.botUserId != null && who.botUserId !== saved.userId) return null;
+ if (who.botUserId == null) {
+ const [owner] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, saved.userId));
+ if (owner?.own) return null;
+ }
await db
.update(users)
.set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
@@ -65,21 +73,88 @@ export async function questionRecipients(db: Db, projectId: number): Promise (await getSetting(db, OFFSET)) ?? 0;
-export const setOffset = (db: Db, offset: number) => setSetting(db, OFFSET, offset);
+// PEP-85: every bot has its own update ids and offset. `botUserId` = the owner of a user's bot;
+// absent = the platform's shared bot (ids and the offset key as before).
+const offsetKey = (botUserId?: number) => (botUserId ? `${OFFSET}:u${botUserId}` : OFFSET);
+export const getOffset = async (db: Db, botUserId?: number) => (await getSetting(db, offsetKey(botUserId))) ?? 0;
+export const setOffset = (db: Db, offset: number, botUserId?: number) => setSetting(db, offsetKey(botUserId), offset);
+/** Update ids of different bots must not collide in `telegram_updates`. */
+const updateKey = (updateId: number, botUserId?: number) => (botUserId ? botUserId * 2 ** 36 + updateId : updateId);
/** Claims an update before acting on it. False = already taken (don't replay). */
-export async function claimUpdate(db: Db, updateId: number): Promise {
+export async function claimUpdate(db: Db, updateId: number, botUserId?: number): Promise {
const rows = await db
.insert(telegramUpdates)
- .values({ updateId, status: "dispatching" })
+ .values({ updateId: updateKey(updateId, botUserId), status: "dispatching" })
.onConflictDoNothing()
.returning();
return rows.length > 0;
}
-export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed"): Promise {
- await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateId));
+export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed", botUserId?: number): Promise {
+ await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateKey(updateId, botUserId)));
+}
+
+// ── PEP-85: the user's own bot ───────────────────────────────────────────────────
+
+export const BOT_TOKEN_RE = /^\d{5,15}:[A-Za-z0-9_-]{30,60}$/;
+
+export interface UserBot {
+ userId: number;
+ token: string;
+ username: string;
+ /** The chat the owner started the bot in (null until they press Start). */
+ chatId: number | null;
+}
+
+/** Asks Telegram who the token belongs to (`TELEGRAM_API_URL` for the mock). */
+export async function verifyBotToken(token: string): Promise<{ id: number; username: string }> {
+ const t = token.trim();
+ if (!BOT_TOKEN_RE.test(t)) throw new PeppaError("Это не похоже на токен бота. Он выглядит так: 1234567890:AAH… — скопируйте его целиком из сообщения BotFather");
+ let body: { ok?: boolean; result?: { id: number; username?: string; is_bot?: boolean }; description?: string };
+ try {
+ const res = await fetch(`${process.env.TELEGRAM_API_URL ?? "https://api.telegram.org"}/bot${t}/getMe`, { signal: AbortSignal.timeout(15_000) });
+ body = (await res.json()) as typeof body;
+ } catch {
+ throw new PeppaError("Telegram не ответил — попробуйте ещё раз через минуту");
+ }
+ if (!body.ok || !body.result?.username) throw new PeppaError("Telegram не принял этот токен — проверьте, что скопировали его целиком, или получите новый в BotFather (/token)");
+ return { id: body.result.id, username: body.result.username };
+}
+
+/** Connects the user's own bot. The chat pairing is dropped: the owner presses Start in the new bot. */
+export async function setUserBot(db: Db, userId: number, token: string): Promise<{ username: string }> {
+ const me = await verifyBotToken(token);
+ const taken = (await db.select({ id: users.id, username: users.telegramBotUsername }).from(users).where(isNotNull(users.telegramBotUsername))).find((u) => u.id !== userId && u.username?.toLowerCase() === me.username.toLowerCase());
+ if (taken) throw new PeppaError("Этот бот уже подключён другим пользователем — создайте своего в BotFather");
+ await db
+ .update(users)
+ .set({ telegramBotTokenEnc: encrypt(token.trim()), telegramBotUsername: me.username, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
+ .where(eq(users.id, userId));
+ return { username: me.username };
+}
+
+/** Back to the platform's shared bot (the chat pairing is dropped too). */
+export async function clearUserBot(db: Db, userId: number): Promise {
+ await db
+ .update(users)
+ .set({ telegramBotTokenEnc: null, telegramBotUsername: null, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
+ .where(eq(users.id, userId));
+}
+
+/** Every connected own bot (the bot process polls them and sends through them). */
+export async function userBots(db: Db): Promise {
+ const rows = await db.select().from(users).where(isNotNull(users.telegramBotTokenEnc));
+ const out: UserBot[] = [];
+ for (const u of rows) {
+ if (u.disabledAt) continue;
+ try {
+ out.push({ userId: u.id, token: decrypt(u.telegramBotTokenEnc!), username: u.telegramBotUsername ?? "", chatId: u.telegramChatId });
+ } catch {
+ // Unreadable after a key rotation gone wrong: skipped, the secrets audit shows it.
+ }
+ }
+ return out;
}
/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */
diff --git a/packages/db/migrations/0016_user_telegram_bot.sql b/packages/db/migrations/0016_user_telegram_bot.sql
new file mode 100644
index 00000000..40aaf827
--- /dev/null
+++ b/packages/db/migrations/0016_user_telegram_bot.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `users` ADD `telegram_bot_token_enc` text;--> statement-breakpoint
+ALTER TABLE `users` ADD `telegram_bot_username` text;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0016_snapshot.json b/packages/db/migrations/meta/0016_snapshot.json
new file mode 100644
index 00000000..041ac7f8
--- /dev/null
+++ b/packages/db/migrations/meta/0016_snapshot.json
@@ -0,0 +1,4120 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "adc91e4e-2273-4fb3-aaa1-fd9d3dc11061",
+ "prevId": "a95c0441-3ac0-47f1-a36d-b0caea076cbd",
+ "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
+ },
+ "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
+ }
+ },
+ "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 cc8db5f4..d91b73ba 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -113,6 +113,13 @@
"when": 1794665444878,
"tag": "0015_chats",
"breakpoints": true
+ },
+ {
+ "idx": 16,
+ "version": "6",
+ "when": 1794678698233,
+ "tag": "0016_user_telegram_bot",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index cdbc71d2..6521db13 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -31,6 +31,10 @@ export const users = sqliteTable("users", {
telegramUserId: integer("telegram_user_id"),
telegramUsername: text("telegram_username"),
telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
+ // PEP-85: the user's own bot (created in BotFather): its token, AES-256-GCM like every secret,
+ // and its @username. Null = the platform's shared bot.
+ telegramBotTokenEnc: text("telegram_bot_token_enc"),
+ telegramBotUsername: text("telegram_bot_username"),
// 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" }),
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 61a7bb33..26ea05bd 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -23,7 +23,11 @@ const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
export class MockTelegram {
readonly token = "mock-123:TOKEN";
- readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
+ /** PEP-85: a second instance stands in for a user's own bot — give it its own identity. */
+ constructor(bot: { id?: number; username?: string } = {}) {
+ this.bot = { id: bot.id ?? 999, username: bot.username ?? "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
+ }
+ readonly bot: { id: number; username: string; is_bot: boolean; first_name: string };
readonly messages = new Map();
readonly callbackAnswers: Array<{ id: string; text?: string }> = [];
readonly calls: Array<{ method: string; params: Record }> = [];
diff --git a/packages/testkit/test/own-bot.test.ts b/packages/testkit/test/own-bot.test.ts
new file mode 100644
index 00000000..cf463dff
--- /dev/null
+++ b/packages/testkit/test/own-bot.test.ts
@@ -0,0 +1,118 @@
+// PEP-85: a user's own Telegram bot — the token from BotFather, pairing by Start in that bot,
+// questions arrive from it, the shared bot keeps serving everybody else. Two mock-telegram
+// instances: the platform's bot and the user's.
+import assert from "node:assert/strict";
+import { after, before, describe, test } from "node:test";
+import { core, db, teardown, waitFor } from "./helpers.ts";
+import { MockTelegram } from "../src/mock-telegram.ts";
+import type { Bot } from "@peppa/bot";
+
+const { createBot } = await import("@peppa/bot");
+const { TelegramApi } = await import("@peppa/bot/telegram");
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const shared = await new MockTelegram().start();
+const own = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot" }).start();
+const OWN_TOKEN = "1234567890:" + "A".repeat(35);
+const ALICE = { id: 601, chatId: 601, username: "alice" };
+const BOB = { id: 602, chatId: 602, username: "bob" };
+const EVE = { id: 666, chatId: 666, username: "eve" };
+let bot: Bot;
+let alice: Awaited>;
+let bob: typeof alice;
+
+before(async () => {
+ alice = await core.upsertUserFromGitea(db, { id: 8501, login: "mock-own-alice" }, { access_token: "x" });
+ bob = await core.upsertUserFromGitea(db, { id: 8502, login: "mock-own-bob" }, { access_token: "y" });
+ bot = createBot({
+ db,
+ api: new TelegramApi(shared.token, shared.url),
+ userApi: (token) => new TelegramApi(token, own.url),
+ secret: shared.token,
+ webUrl: "http://peppa.test",
+ pollTimeoutSec: 1,
+ outboxIntervalMs: 100,
+ reconcileIntervalMs: 400,
+ userBotsIntervalMs: 200,
+ });
+ await bot.start();
+});
+after(async () => {
+ await bot.stop();
+ await shared.stop();
+ await own.stop();
+ await teardown();
+});
+
+describe("свой Telegram-бот", () => {
+ test("Scenario: токен проверяется у Telegram; привязка — Start в своём боте; вопрос приходит из него", async () => {
+ await assert.rejects(core.setUserBot(db, alice.id, "не токен"), /не похоже на токен бота/);
+ process.env.TELEGRAM_API_URL = own.url;
+ try {
+ own.failNext("getMe", 401);
+ await assert.rejects(core.setUserBot(db, alice.id, OWN_TOKEN), /Telegram не принял этот токен/);
+ assert.deepEqual(await core.setUserBot(db, alice.id, OWN_TOKEN), { username: "mock_alice_factory_bot" });
+ await assert.rejects(core.setUserBot(db, bob.id, OWN_TOKEN), /уже подключён другим пользователем/);
+ } finally {
+ delete process.env.TELEGRAM_API_URL;
+ }
+ const saved = (await core.getUser(db, alice.id))!;
+ assert.equal(saved.telegramBotUsername, "mock_alice_factory_bot");
+ assert.ok(saved.telegramBotTokenEnc && !saved.telegramBotTokenEnc.includes(OWN_TOKEN), "stored encrypted");
+ assert.deepEqual((await core.userBots(db)).map((b) => [b.userId, b.token, b.chatId]), [[alice.id, OWN_TOKEN, null]]);
+ await bot.syncOwnBots();
+
+ // The owner's code works only in her own bot.
+ const code = await core.createPairingCode(db, shared.token, alice.id);
+ shared.userSends(ALICE, `/start ${code}`);
+ await waitFor("the shared bot refuses", async () => shared.botMessages(ALICE.chatId).some((m) => /неверный или истёк/.test(m.text)));
+ assert.equal((await core.getUser(db, alice.id))!.telegramChatId, null);
+
+ // Somebody else's code does not work in her bot either.
+ own.userSends(EVE, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`);
+ await waitFor("her bot refuses a stranger", async () => own.botMessages(EVE.chatId).some((m) => /неверный или истёк/.test(m.text)));
+ assert.equal((await core.getUser(db, bob.id))!.telegramChatId, null);
+
+ own.userSends(ALICE, `/start ${await core.createPairingCode(db, shared.token, alice.id)}`);
+ await waitFor("paired in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => /Привязано/.test(m.text)));
+ assert.equal((await core.getUser(db, alice.id))!.telegramChatId, ALICE.chatId);
+
+ // A question of her project comes from her bot, not from the shared one.
+ const p = await core.createProject(db, { slug: "mock-own-a", key: "MOWNA", name: "Own A", giteaOwner: "x", workspacePath: "/tmp/mock-own-a", ownerId: alice.id });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Каталог" });
+ const sharedBefore = shared.botMessages(ALICE.chatId).length;
+ const q = await core.askPm(db, ref, { kind: "question", text: "Нужна ли мобильная версия?" });
+ await waitFor("question in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => m.text.includes("Нужна ли мобильная версия?")));
+ assert.equal(shared.botMessages(ALICE.chatId).length, sharedBefore, "nothing through the shared bot");
+
+ // She answers by a reply in her bot.
+ const msg = own.botMessages(ALICE.chatId).find((m) => m.text.includes("Нужна ли мобильная версия?"))!;
+ own.userSends(ALICE, "Не нужна", msg.message_id);
+ await waitFor("answered", async () => !!(await core.getQuestion(db, q.id)).answeredAt);
+ assert.equal((await core.getQuestion(db, q.id)).answer, "Не нужна");
+ });
+
+ test("Scenario: общий бот продолжает работать для остальных; чужому свой бот не отвечает", async () => {
+ shared.userSends(BOB, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`);
+ await waitFor("bob paired with the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => /Привязано/.test(m.text)));
+ const p = await core.createProject(db, { slug: "mock-own-b", key: "MOWNB", name: "Own B", giteaOwner: "x", workspacePath: "/tmp/mock-own-b", ownerId: bob.id });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" });
+ await core.askPm(db, ref, { kind: "question", text: "Какая валюта?" });
+ await waitFor("bob's question in the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => m.text.includes("Какая валюта?")));
+ assert.equal(own.botMessages(BOB.chatId).length, 0);
+
+ // Bob writes to Alice's bot: it serves its owner only.
+ const n = own.botMessages(BOB.chatId).length;
+ own.userSends(BOB, "/status");
+ await new Promise((r) => setTimeout(r, 1500));
+ assert.equal(own.botMessages(BOB.chatId).length, n);
+ });
+
+ test("отключение своего бота: опрос останавливается, привязка сбрасывается", async () => {
+ await core.clearUserBot(db, alice.id);
+ await bot.syncOwnBots();
+ const u = (await core.getUser(db, alice.id))!;
+ assert.deepEqual([u.telegramBotTokenEnc, u.telegramBotUsername, u.telegramChatId], [null, null, null]);
+ assert.deepEqual(await core.userBots(db), []);
+ });
+});
--
2.45.2
From 54182d0637383b08e0a1ab1e064bcf7474ae467f 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:04:25 +0500
Subject: [PATCH 022/428] PEP-86: connecting your own Telegram bot is the first
step, right on the Home page
Co-Authored-By: Claude Fable 5.2
---
apps/web/app/(app)/actions.ts | 5 +-
apps/web/app/(app)/page.tsx | 2 +-
apps/web/app/(app)/settings/page.tsx | 82 +----------------------
apps/web/components/Onboarding.tsx | 10 ++-
apps/web/components/OwnBotSteps.tsx | 97 ++++++++++++++++++++++++++++
packages/core/src/onboarding.ts | 2 +-
6 files changed, 113 insertions(+), 85 deletions(-)
create mode 100644 apps/web/components/OwnBotSteps.tsx
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 29f6a15c..e7e1b0ef 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -714,7 +714,8 @@ export async function connectOwnBotAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await setUserBot(db, user.id, String(f.get("token") ?? ""));
- return "/settings?bot=connected#telegram";
+ // On the Home page the next step (Start) shows right there.
+ return str(f, "back") === "/" ? "/" : "/settings?bot=connected#telegram";
});
}
@@ -722,6 +723,6 @@ export async function disconnectOwnBotAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await clearUserBot(db, user.id);
- return "/settings#telegram";
+ return str(f, "back") === "/" ? "/" : "/settings#telegram";
});
}
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 454e7bd9..7d80470d 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -20,7 +20,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}
- {onboarding.visible && }
+ {onboarding.visible && }
{items.map((q) => )}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 29b61f42..f57ba0ce 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -5,23 +5,16 @@ import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
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 { connectOwnBotAction, disconnectOwnBotAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
+import { disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
const back = { back: "/settings" };
-function StepNum({ n, done }: { n: number; done: boolean }) {
- return (
-
- {done ? "✓" : n}
-
- );
-}
-
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
@@ -47,76 +40,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const myProjects = await listUserProjects(db, user.id);
const pushSubs = await userPushSubscriptions(db, user.id);
const vapid = await vapidPublicKey(db);
- // PEP-85: the three steps of connecting an own bot (shown when Telegram is not paired, or to switch).
- const ownBotSteps = (
-
-
- Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
-
-
-
-
-
-
Создайте бота в Telegram
-
- Откройте @BotFather (официальный бот Telegram), отправьте ему /newbot , придумайте название и адрес — адрес должен заканчиваться на bot , например{" "}
- my_factory_bot .
-
- {!hasBot && (
-
- Открыть BotFather
-
- )}
-
-
-
-
-
- Вставьте токен бота
- {hasBot ? (
-
- Подключён @{user.telegramBotUsername} . Токен хранится зашифрованным.
-
- ) : (
- <>
- BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
-
-
-
- Подключить бота
-
- >
- )}
-
-
-
-
-
- Откройте своего бота и нажмите Start
- Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.
- {hasBot && (
-
-
- Открыть @{user.telegramBotUsername}
-
- )}
-
-
-
- {hasBot ? (
-
-
- Отключить этого бота
-
- ) : (
-
-
- Не хотите создавать бота?
- Использовать общего бота Пеппы
-
- )}
-
- );
+ const ownBotSteps = ;
return (
diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx
index e9959ceb..66f0ee1e 100644
--- a/apps/web/components/Onboarding.tsx
+++ b/apps/web/components/Onboarding.tsx
@@ -5,9 +5,10 @@ import type { Onboarding } from "@peppa/core";
import { dismissOnboardingAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
+import { OwnBotSteps } from "@/components/OwnBotSteps";
import { cn } from "@/lib/utils";
-export function OnboardingChecklist({ data }: { data: Onboarding }) {
+export function OnboardingChecklist({ data, botUsername = null }: { data: Onboarding; botUsername?: string | null }) {
const next = data.steps.find((s) => !s.done && !s.optional);
const fresh = data.done === 0;
return (
@@ -53,7 +54,12 @@ export function OnboardingChecklist({ data }: { data: Onboarding }) {
{s.title}
{!s.done &&
{s.hint} }
- {current && (
+ {current && s.id === "telegram" ? (
+ // PEP-85: the first thing to do — right here, not behind a link to Settings.
+
+
+
+ ) : current && (
{s.action}
diff --git a/apps/web/components/OwnBotSteps.tsx b/apps/web/components/OwnBotSteps.tsx
new file mode 100644
index 00000000..10c8e0e4
--- /dev/null
+++ b/apps/web/components/OwnBotSteps.tsx
@@ -0,0 +1,97 @@
+import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram } from "@/app/(app)/actions";
+import { Hidden } from "@/components/cards";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { cn } from "@/lib/utils";
+
+function StepNum({ n, done }: { n: number; done: boolean }) {
+ return (
+
+ {done ? "✓" : n}
+
+ );
+}
+
+/**
+ * PEP-85: connecting the user's own Telegram bot in three plain steps (BotFather → token →
+ * Start). Shown on the Home page as the first thing a new user does, and in Settings.
+ */
+export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: string | null; back: string; bare?: boolean }) {
+ const hasBot = !!botUsername;
+ const fields = { back };
+ return (
+
+ {!bare && (
+
+ Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
+
+ )}
+
+
+
+
+
Создайте бота в Telegram
+ {!hasBot && (
+ <>
+
+ Откройте @BotFather (официальный бот Telegram), отправьте ему /newbot , придумайте название и адрес — адрес должен заканчиваться на bot , например{" "}
+ my_factory_bot .
+
+
+ Открыть BotFather
+
+ >
+ )}
+
+
+
+
+
+ Вставьте токен бота
+ {hasBot ? (
+
+ Подключён @{botUsername} . Токен хранится зашифрованным.
+
+ ) : (
+ <>
+
+ BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
+
+
+
+
+ Подключить бота
+
+ >
+ )}
+
+
+
+
+
+ Откройте своего бота и нажмите Start
+ Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.
+ {hasBot && (
+
+
+ Открыть @{botUsername}
+
+ )}
+
+
+
+ {hasBot ? (
+
+
+ Отключить этого бота
+
+ ) : (
+
+
+ Не хотите создавать бота?
+ Использовать общего бота Пеппы
+
+ )}
+
+ );
+}
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index 03126708..c63929c4 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -54,7 +54,7 @@ export async function onboardingChecklist(db: Db, user: Pick
Date: Sat, 14 Nov 2026 23:04:42 +0500
Subject: [PATCH 023/428] PEP-86: the Home page shows only the user's own
projects
Co-Authored-By: Claude Fable 5.2
---
apps/web/components/ProgressOverview.tsx | 15 +++------------
1 file changed, 3 insertions(+), 12 deletions(-)
diff --git a/apps/web/components/ProgressOverview.tsx b/apps/web/components/ProgressOverview.tsx
index 88eddb60..d74a196d 100644
--- a/apps/web/components/ProgressOverview.tsx
+++ b/apps/web/components/ProgressOverview.tsx
@@ -1,7 +1,7 @@
import Link from "next/link";
import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";
-import { Disclosure, Empty, Key } from "@/components/common";
+import { Empty, Key } from "@/components/common";
import { cn } from "@/lib/utils";
const PARTS = [
@@ -85,9 +85,9 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
);
}
-/** PEP-77: progress of all stories and projects on the Home page. */
+/** PEP-77: progress of the user's own projects on the Home page (other people's projects — on «Проекты», for a superadmin). */
export function ProgressOverview({ data }: { data: Overview }) {
- if (!data.mine.length && !data.others.length) return Проектов пока нет — прогресс появится с первой стори. ;
+ if (!data.mine.length) return Проектов пока нет — прогресс появится с первой стори. ;
const t = data.totals;
return (
@@ -108,15 +108,6 @@ export function ProgressOverview({ data }: { data: Overview }) {
))}
- {data.others.length > 0 && (
-
-
- {data.others.map((p) => (
-
- ))}
-
-
- )}
);
}
--
2.45.2
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 024/428] 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 025/428] 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 14177684d4fcf6dc197718529fe260a9ada53d9c 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:48:34 +0500
Subject: [PATCH 026/428] PEP-88: a superadmin manages any project like its
owner
Co-Authored-By: Claude Fable 5.2
---
apps/web/app/(app)/actions.ts | 4 +--
apps/web/app/(app)/p/[key]/page.tsx | 3 ++-
.../proposal.md | 13 ++++++++++
.../specs/web-auth/spec.md | 15 +++++++++++
.../tasks.md | 3 +++
openspec/specs/web-auth/spec.md | 14 ++++++++++
packages/runner/src/share.ts | 14 +++++++---
packages/testkit/test/web.test.ts | 26 +++++++++++++++++++
8 files changed, 85 insertions(+), 7 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index e7e1b0ef..29671a88 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -59,7 +59,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -507,7 +507,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 (p.ownerId !== user.id) throw new PeppaError("Подключает владелец проекта");
+ if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта");
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
});
}
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index b8121705..a2e8619c 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -99,9 +99,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const noRepoAccess = (login: string) =>
repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
const missingAccess = team.members.some((m) => noRepoAccess(m.login));
- const isOwner = p.ownerId === user.id;
// PEP-67: default subscription pool; only a superadmin changes it.
const superadmin = await isSuperadmin(db, user);
+ // PEP-88: a superadmin manages any project like its owner.
+ const isOwner = p.ownerId === user.id || superadmin;
const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
// PEP-10/27: runner settings of the project over the system ones.
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
diff --git a/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md
new file mode 100644
index 00000000..170b47a9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md
@@ -0,0 +1,13 @@
+# PEP-88: суперадмин управляет любым проектом как владелец
+
+## Why
+Модель доступа: каждый видит своё пространство и свои проекты; суперадмин видит всё и управляет всем. После PEP-74
+суперадмин открывал чужой проект с правами участника, но участниками, видимостью репозитория и подключением
+отслеживания ошибок управлял только владелец.
+
+## What Changes
+- `managesProject(db, actor, project)` (runner/share.ts): владелец или суперадмин. На нём — `shareProject`, `unshareProject`,
+ `grantRepoAccess`, `setProjectVisibility`, действие подключения отслеживания ошибок.
+- Страница проекта: блоки владельца показываются и суперадмину.
+
+Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md
new file mode 100644
index 00000000..98933f44
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md
@@ -0,0 +1,15 @@
+## ADDED Requirements
+
+### Requirement: Суперадмин управляет любым проектом
+Суперадмин SHALL выполнять в любом проекте действия владельца: добавлять и убирать
+участников, менять видимость репозитория, подключать отслеживание ошибок. Обычный
+пользователь SHALL управлять только своими проектами.
+
+#### Scenario: Суперадмин добавляет участника
+- **GIVEN** проект «PAY» пользователя «dana» и суперадмин «asel»
+- **WHEN** asel добавляет в «PAY» участника «kate»
+- **THEN** kate видит проект «PAY»
+
+#### Scenario: Посторонний
+- **WHEN** пользователь, не владелец и не суперадмин, пытается добавить участника в «PAY»
+- **THEN** действие отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md
new file mode 100644
index 00000000..94eb0188
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `managesProject` и проверки в share.ts, действие отслеживания ошибок
+- [x] 2 Страница проекта: блоки владельца для суперадмина
+- [x] 3 Тест в `web.test.ts`, `openspec validate`
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index 49332709..a81a41df 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -179,3 +179,17 @@ nonce, созданные сервером для этого потока; по
- **GIVEN** пользователь «kate» не суперадмин и не участник «TZK»
- **WHEN** она открывает `/p/TZK`
- **THEN** она получает «не найдено», секции «Проекты других» у неё нет
+
+### Requirement: Суперадмин управляет любым проектом
+Суперадмин SHALL выполнять в любом проекте действия владельца: добавлять и убирать
+участников, менять видимость репозитория, подключать отслеживание ошибок. Обычный
+пользователь SHALL управлять только своими проектами.
+
+#### Scenario: Суперадмин добавляет участника
+- **GIVEN** проект «PAY» пользователя «dana» и суперадмин «asel»
+- **WHEN** asel добавляет в «PAY» участника «kate»
+- **THEN** kate видит проект «PAY»
+
+#### Scenario: Посторонний
+- **WHEN** пользователь, не владелец и не суперадмин, пытается добавить участника в «PAY»
+- **THEN** действие отклонено
diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts
index 4d5abdc2..2affa770 100644
--- a/packages/runner/src/share.ts
+++ b/packages/runner/src/share.ts
@@ -14,6 +14,7 @@ import {
type RepoInfo,
type Project,
type User,
+ isSuperadmin,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
@@ -33,6 +34,11 @@ export async function repoAdmins(db: Db, project: Project): Promise): Promise {
+ return project.ownerId === actor.id || (await isSuperadmin(db, actor));
+}
+
export interface ShareResult {
login: string;
status: "added" | "invited";
@@ -42,7 +48,7 @@ export interface ShareResult {
/** Owner adds a person (by Gitea login) to the project and to its repo (write). */
export async function shareProject(db: Db, actor: User, project: Project, loginInput: string): Promise {
- if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта");
+ if (!(await managesProject(db, actor, project))) throw new PeppaError("Участниками управляет только владелец проекта");
const login = loginInput.trim().replace(/^@/, "");
if (!login) throw new PeppaError("Укажите логин Gitea");
// PEP-68: a local Peppa user (no Gitea account) becomes a member without repo access.
@@ -74,7 +80,7 @@ export async function shareProject(db: Db, actor: User, project: Project, loginI
export async function unshareProject(db: Db, actor: User, project: Project, loginInput: string): Promise {
const login = loginInput.trim().replace(/^@/, "");
const self = actor.login.toLowerCase() === login.toLowerCase();
- if (project.ownerId !== actor.id && !self) throw new PeppaError("Участниками управляет только владелец проекта");
+ if (!self && !(await managesProject(db, actor, project))) throw new PeppaError("Участниками управляет только владелец проекта");
if (!(await removeMember(db, project.id, login))) throw new PeppaError(`«${login}» не участник проекта`);
describeCache.delete(project.id);
if (await localUser(db, login)) return; // not a Gitea collaborator; the same Gitea login may be someone else
@@ -93,7 +99,7 @@ async function localUser(db: Db, login: string): Promise {
/** Owner adds every member (not pending invites) as a repo collaborator; returns who failed. */
export async function grantRepoAccess(db: Db, actor: User, project: Project): Promise<{ granted: string[]; failed: string[] }> {
- if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта");
+ if (!(await managesProject(db, actor, project))) throw new PeppaError("Участниками управляет только владелец проекта");
const clients = await repoAdmins(db, project);
const { members } = await listMembers(db, project);
const granted: string[] = [];
@@ -122,7 +128,7 @@ export type Visibility = "public" | "private";
*/
export async function setProjectVisibility(db: Db, project: Project, visibility: Visibility, opts: { actor?: User } = {}): Promise {
if (visibility !== "public" && visibility !== "private") throw new PeppaError(`Видимость: public или private, не «${visibility}»`);
- if (opts.actor && project.ownerId !== opts.actor.id) throw new PeppaError("Видимость репозитория меняет только владелец проекта");
+ if (opts.actor && !(await managesProject(db, opts.actor, project))) throw new PeppaError("Видимость репозитория меняет только владелец проекта");
const fullName = `${project.giteaOwner}/${project.giteaRepo}`;
const clients = await repoAdmins(db, project);
if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново");
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 365405f7..bc693c83 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -216,3 +216,29 @@ describe("новый проект: настройки по умолчанию",
assert.equal((await core.projectPool(db, second.id))!.id, pool.id, "connected once — not asked again");
});
});
+
+describe("PEP-88: суперадмин управляет любым проектом", () => {
+ test("участники и видимость чужого проекта — суперадмину можно, постороннему нельзя", async () => {
+ const owner = await core.upsertUserFromGitea(db, { id: 8801, login: "mock-p88-owner" }, { access_token: "x" });
+ const boss = await core.upsertUserFromGitea(db, { id: 8802, login: "mock-p88-boss" }, { access_token: "x" });
+ // A Peppa account without Gitea: it becomes a member without a repo collaborator call.
+ const other = await core.registerEgovUser(db, { iin: "850505400058", name: "ДРУГОЙ УЧАСТНИК" });
+ const p = await core.createProject(db, { slug: "mock-p88", key: "MPMNG", name: "P88", giteaOwner: "x", workspacePath: "/tmp/mock-p88", ownerId: owner.id });
+ assert.equal(await runner.managesProject(db, owner, p), true);
+ assert.equal(await runner.managesProject(db, other, p), false);
+ assert.equal(await runner.managesProject(db, boss, p), false);
+ await assert.rejects(runner.shareProject(db, boss, p, other.login), /только владелец/);
+ await core.setPlatformAdmins(db, ["mock-p88-boss"]);
+ try {
+ assert.equal(await runner.managesProject(db, boss, p), true);
+ const r = await runner.shareProject(db, boss, p, other.login);
+ assert.equal(r.login, other.login);
+ assert.ok((await core.userProjectIds(db, other.id)).includes(p.id));
+ await runner.unshareProject(db, boss, p, other.login);
+ assert.ok(!(await core.userProjectIds(db, other.id)).includes(p.id));
+ await assert.rejects(runner.shareProject(db, other, p, "mock-p88-boss"), /только владелец/);
+ } finally {
+ await core.setPlatformAdmins(db, null);
+ }
+ });
+});
--
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 027/428] =?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 028/428] 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 029/428] =?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