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 1/6] 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";
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 2/6] =?UTF-8?q?PEP-62:=20bot=20=E2=80=94=20link=20groups?=
=?UTF-8?q?=20by=20code,=20mirror=20chat=20messages=20with=20reply=20threa?=
=?UTF-8?q?ds,=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;
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 3/6] =?UTF-8?q?PEP-62:=20web=20=C2=AB=D0=A7=D0=B0=D1=82?=
=?UTF-8?q?=D1=8B=C2=BB=20(master=20+=20project=20chats,=20threads,=20comp?=
=?UTF-8?q?oser,=20Telegram=20link),=20live=20scope,=20watchdog=20sync/TTL?=
=?UTF-8?q?,=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, "Старый вопрос");
+ });
+});
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 4/6] 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`
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 5/6] 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 остаётся в стори
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 6/6] 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;
}