From 424ab65a958d1ff237d3e9e16c549bd5fc95c482 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 15:31:20 +0500 Subject: [PATCH 1/3] =?UTF-8?q?PEP-109:=20proposal=20=E2=80=94=20chat=20Te?= =?UTF-8?q?legram=20groups=20through=20the=20user's=20own=20bot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../pep-109-chat-groups-own-bot/design.md | 15 +++++ .../pep-109-chat-groups-own-bot/proposal.md | 16 ++++++ .../specs/project-chats/spec.md | 57 +++++++++++++++++++ .../pep-109-chat-groups-own-bot/tasks.md | 6 ++ 4 files changed, 94 insertions(+) create mode 100644 openspec/changes/pep-109-chat-groups-own-bot/design.md create mode 100644 openspec/changes/pep-109-chat-groups-own-bot/proposal.md create mode 100644 openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md create mode 100644 openspec/changes/pep-109-chat-groups-own-bot/tasks.md diff --git a/openspec/changes/pep-109-chat-groups-own-bot/design.md b/openspec/changes/pep-109-chat-groups-own-bot/design.md new file mode 100644 index 00000000..3f827d84 --- /dev/null +++ b/openspec/changes/pep-109-chat-groups-own-bot/design.md @@ -0,0 +1,15 @@ +# Design: PEP-109 + +## Решения +- **Через какого бота связана группа — колонка `chats.tg_bot_user_id`** (владелец бота; null — общий бот платформы), а не вывод из `tg_linked_by`: связавший может позже подключить/сменить бота, а суперадмин без своего бота связывает через общий. Миграция 0018, одна nullable-колонка со ссылкой на `users` (`on delete set null`). +- **Код связки привязан к боту при выдаче**: в настройке кода сохраняется `botUserId` (id выдавшего, если у него свой бот; иначе null). `acceptChatLink` принимает код только от того же бота (`via.getStore()?.userId`), как `acceptPairing` в PEP-85. Чужой бот отвечает «код неверный или истёк» и код не сжигает — иначе второй бот в той же группе испортил бы связку (команда без `@бота` приходит всем ботам группы). +- **Кто может связать**: любой с доступом к чату (`chatForUser`) и своим ботом; суперадмин без своего бота — через общий, как было. Остальным — `PeppaError` с подсказкой подключить бота. +- **Маршрутизация исходящих**: `ownByChat` в боте (chat_id → свой бот) дополняется группами (`chatGroupBots`), обновляется в `syncOwnBots` (раз в 10 с и сразу после связки). Очередь отправки не меняется — бот выбирается по `chat_id`, как для личных чатов. +- **Входящие из группы**: сообщение/кнопку связанной группы обрабатывает только бот связки; остальные боты её игнорируют (без ответов), чтобы два бота в одной группе не отвечали дважды. +- **Автор в группе** — как раньше: пользователь Пеппы с привязанным Telegram-аккаунтом (`telegramAccountUser`) и доступом к чату; привязка может быть сделана через любого бота. +- **Отключение/замена бота** (`clearUserBot`, `setUserBot` с другим ботом) отвязывает группы этого бота: новый бот в группе не состоит, слать туда нечем. +- Секрет хэша кода — по-прежнему токен общего бота (он есть и у веба, и у процесса бота). + +## Не делаем +- Не переносим уже связанные через общий бот группы (на живой системе это только группы суперадмина). +- Отключённый пользователь: его бот не опрашивается, сообщения группе не уйдут (ошибка в очереди) — отдельной обработки нет. diff --git a/openspec/changes/pep-109-chat-groups-own-bot/proposal.md b/openspec/changes/pep-109-chat-groups-own-bot/proposal.md new file mode 100644 index 00000000..39f31089 --- /dev/null +++ b/openspec/changes/pep-109-chat-groups-own-bot/proposal.md @@ -0,0 +1,16 @@ +# Proposal: PEP-109 — Telegram-группы чатов через свой бот пользователя + +## Why +«Связать с Telegram» в чатах добавляет в группу общего бота платформы. По требованию PM (PEP-108) общий бот пользователям не предлагается нигде: после PEP-106 связка групп осталась только суперадмину, а обычный пользователь подключить группу не может вовсе. У пользователя есть собственный бот (PEP-85) — группа должна подключаться через него. + +## What Changes +- «Связать с Telegram» в мастер-чате и чате проекта доступно каждому, у кого подключён свой бот: ссылка «Добавить @мой_бот в группу» (или `/link <код>` в группе, где этот бот уже есть). +- Группа запоминает бота, через которого связана (`chats.tg_bot_user_id`): сообщения чата, вопросы, кнопки и ответы на реплаи идут через него; команды и реплаи группы принимает только он. +- Код связки принимает только бот того, кто его выдал; общий бот принимает код только суперадмина без своего бота (как раньше). +- Без своего бота (и не суперадмин) — вместо кнопки подсказка подключить бота в «Настройки → Telegram». +- Владелец отключил или заменил своего бота — группы, связанные через него, отвязываются. +- Справка и тексты чата обновлены. + +## Impact +- Спека `project-chats` (требование «Связка чата с Telegram-группой»). +- `packages/db` (миграция 0018: колонка), `packages/core` (chats.ts, telegram.ts), `apps/bot`, `apps/web` (чаты, справка), тест `chats-own-bot.test.ts`. diff --git a/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md b/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md new file mode 100644 index 00000000..63dcf593 --- /dev/null +++ b/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md @@ -0,0 +1,57 @@ +## MODIFIED Requirements + +### Requirement: Связка чата с Telegram-группой +Чат проекта и мастер-чат SHALL связываться с обычной Telegram-группой по одноразовому коду +(10 минут) через собственного бота пользователя, который связывает: веб SHALL предлагать +ссылку «Добавить @его_бот в группу», а код SHALL приниматься только этим ботом. Общий бот +платформы пользователям SHALL NOT предлагаться; через него группу связывает только суперадмин +без своего бота. Пользователю без своего бота веб SHALL показывать подсказку подключить бота +вместо связки. Сообщения связанного чата SHALL дублироваться в группу через бота связки, тред — +цепочкой реплаев на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и +обрабатываться как сообщение из веба; принимать его SHALL только бот связки и только от +пользователя Пеппы с привязанным Telegram и доступом к проекту (в мастер-группе — от владельца +мастер-чата). Когда владелец отключает или заменяет своего бота, группы, связанные через него, +SHALL отвязываться. + +#### Scenario: Связать группу +- **GIVEN** «anna» подключила своего бота «@anna_factory_bot», открыла чат PAY и нажала «Связать с Telegram» +- **WHEN** в группе «PAY team» боту «@anna_factory_bot» отправлено `/link <код>` до истечения кода +- **THEN** чат PAY связан с «PAY team», «@anna_factory_bot» подтверждает это в группе +- **AND** веб показывает название группы и «@anna_factory_bot» + +#### Scenario: Сообщения группы идут через бота связки +- **GIVEN** чат PAY связан с группой «PAY team» через «@anna_factory_bot» +- **WHEN** агент задаёт вопрос по стори PAY-7 +- **THEN** вопрос приходит в группу от «@anna_factory_bot», от общего бота в группе ничего нет + +#### Scenario: Код в общем боте +- **GIVEN** «anna» со своим ботом получила код связки чата PAY +- **WHEN** `/link <код>` получает общий бот платформы +- **THEN** общий бот отвечает, что код неверный или истёк, чат не связан +- **AND** тот же код после этого принимает «@anna_factory_bot» + +#### Scenario: Нет своего бота +- **GIVEN** «boris» без своего бота и не суперадмин +- **WHEN** он запрашивает код связки чата PAY +- **THEN** код не выдан, показано «подключите своего бота в Настройках → Telegram» + +#### Scenario: Просроченный код +- **GIVEN** код связки выдан 11 минут назад +- **WHEN** в группе отправлено `/link <код>` +- **THEN** бот отвечает, что код неверный или истёк, чат не связан + +#### Scenario: Ответ реплаем из группы +- **GIVEN** чат PAY связан с группой через «@anna_factory_bot», вопрос PAY-7 пришёл в группу +- **AND** «boris» привязал Telegram и участник PAY +- **WHEN** «boris» отвечает реплаем на вопрос «точка с запятой» +- **THEN** вопрос отвечен, в веб-треде PAY-7 видно его сообщение с пометкой Telegram + +#### Scenario: Посторонний в группе +- **GIVEN** в группе PAY есть человек без привязки Telegram в Пеппе +- **WHEN** он отвечает реплаем на вопрос PAY-7 +- **THEN** вопрос не отвечен, сообщения в чате нет, бот подсказывает привязать Telegram + +#### Scenario: Бот отключён +- **GIVEN** чат PAY связан с группой через «@anna_factory_bot» +- **WHEN** «anna» отключает своего бота в Настройках +- **THEN** чат PAY больше не связан с группой diff --git a/openspec/changes/pep-109-chat-groups-own-bot/tasks.md b/openspec/changes/pep-109-chat-groups-own-bot/tasks.md new file mode 100644 index 00000000..0bfcb8ba --- /dev/null +++ b/openspec/changes/pep-109-chat-groups-own-bot/tasks.md @@ -0,0 +1,6 @@ +- [ ] 1.1 Колонка `chats.tg_bot_user_id` + миграция 0018 +- [ ] 1.2 core: код связки с ботом (`createChatLinkCode`/`acceptChatLink`), `chatGroupBots`, отвязка групп при отключении/замене бота +- [ ] 1.3 бот: связка и сообщения группы через свой бот, маршрутизация исходящих, чужой бот молчит +- [ ] 1.4 веб: «Связать с Telegram» для пользователя со своим ботом, подсказка без бота, справка +- [ ] 1.5 тесты `chats-own-bot.test.ts` по сценариям, typecheck, полный прогон проверок +- [ ] 1.6 AGENTS.md, память проекта From f9a4b3c56e50a30ee2923ed92cbe79a96c07a0da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 15:34:31 +0500 Subject: [PATCH 2/3] PEP-109: a chat's Telegram group is linked through the user's own bot Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 1 + apps/bot/src/bot.ts | 28 +- apps/web/app/(app)/chats/[chat]/page.tsx | 73 +- apps/web/app/(app)/chats/actions.ts | 10 +- apps/web/app/(app)/help/page.tsx | 8 +- .../pep-109-chat-groups-own-bot/design.md | 2 +- .../specs/project-chats/spec.md | 2 +- .../pep-109-chat-groups-own-bot/tasks.md | 8 +- packages/core/src/chats.ts | 51 +- packages/core/src/telegram.ts | 13 +- .../0018_lumpy_dreaming_celestial.sql | 1 + .../db/migrations/meta/0018_snapshot.json | 4168 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 2 + packages/testkit/test/chats-own-bot.test.ts | 163 + packages/testkit/test/chats.test.ts | 4 +- 16 files changed, 4484 insertions(+), 57 deletions(-) create mode 100644 packages/db/migrations/0018_lumpy_dreaming_celestial.sql create mode 100644 packages/db/migrations/meta/0018_snapshot.json create mode 100644 packages/testkit/test/chats-own-bot.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3887a5c5..0ade5d1c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,7 @@ - **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx` - **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана» - **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts` +- **Группы чатов через свой бот (PEP-109)**: «Связать с Telegram» в чате — через собственного бота пользователя (PEP-85): `chats.tg_bot_user_id` (миграция 0018; null — общий бот, им связывает только суперадмин без своего бота: `createChatLinkCode(…, { sharedBot })`, остальным без бота — отказ с подсказкой). Код привязан к боту (`botUserId` в настройке кода): `acceptChatLink` принимает только от него и чужим ботом не сжигается; на `/link` без `@бота` с чужим кодом бот молчит (`chatLinkCodeBot`). Бот: `ownByChat` дополняется группами (`chatGroupBots` в `syncOwnBots`) — исходящие в группу идут через бота связки; входящие сообщения и кнопки группы обрабатывает только он (`linkedHere`). `clearUserBot` / `setUserBot` с другим ботом отвязывают его группы. Тест `chats-own-bot.test.ts` - **Обсуждение проекта (PEP-106)**: чат проекта открывается на «Обсуждении» — только сообщения людей в канале (`discussionMessages`: `thread_key` null, `kind` user, не команда); события агентов — `/chats/KEY?thread=feed`. `markDiscussionRead`/`discussionUnread` (`chat.read::`) → счётчик `navCounts.chats`, плашки чатов, ссылка «Обсуждение» после «Доски» на странице проекта. `postToChat` в канал проекта уведомляет остальных (`projectAudience`) событием уведомлений `chat`. `pruneChats` обсуждение не удаляет. Агентам обсуждение не уходит. Тест `discussion.test.ts` - **Чат с аналитиком (PEP-110)**: сообщение человека в обсуждении проекта (PEP-106) → `analystChatTick` в тике вачдога (`runner/analyst-chat.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`, `PEPPA_ANALYST_CHAT_MODEL`), контекст `core/analyst-chat.ts` (`intakeContext` + `projectStatusBlock` со ссылками «где что смотреть»), ответ `{reply, create[]}` → сообщение `kind: user, authorKind: agent, authorLogin: «Аналитик»` в то же обсуждение + событие уведомлений `chat`; стори из `create` — только по явной просьбе, intake у них `done`. Курсор `chat.analyst:`, `analystPending` («печатает…»), сообщения старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) пропускаются, сбой — одна заметка без повторов, `PEPPA_ANALYST_CHAT=off`. Мок — роль `chat` в `mock-intake`; тест `analyst-chat.test.ts` - **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx` diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 4e92aca2..e90405c7 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -50,6 +50,8 @@ import { type Question, type SessionView, acceptChatLink, + chatGroupBots, + chatLinkCodeBot, chatByTelegram, chatMessageByTelegram, chatMessagesAfter, @@ -178,6 +180,11 @@ export function createBot(o: BotOptions) { } if (b.chatId != null) ownByChat.set(b.chatId, bot); } + // PEP-109: a group linked through somebody's own bot is written to by that bot. + for (const g of await chatGroupBots(db)) { + const bot = ownBots.get(g.botUserId); + if (bot && seen.has(g.botUserId)) ownByChat.set(g.tgChatId, bot); + } for (const [userId, bot] of ownBots) { if (seen.has(userId)) continue; bot.stop.abort(); @@ -526,20 +533,31 @@ export function createBot(o: BotOptions) { return "Неизвестная кнопка"; } + /** Is the update being handled by the bot this chat's group is linked through? */ + const linkedHere = (chat: Chat) => (chat.tgBotUserId ?? null) === (via.getStore()?.userId ?? null); + /** 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); + 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 }); + const code = link[2]!; + // PEP-109: a command without @bot reaches every bot of the group — a code issued for + // another bot is that bot's business, this one keeps quiet. + const codeBot = isChatLinkCode(code) ? await chatLinkCodeBot(db, o.secret, code) : undefined; + if (!link[1] && codeBot !== undefined && codeBot !== (via.getStore()?.userId ?? null)) return "ignored"; + if (!isChatLinkCode(code)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done"); + const chat = await acceptChatLink(db, o.secret, code, { tgChatId: m.chat.id, title: m.chat.title ?? null, botUserId: via.getStore()?.userId }); if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done"); + await syncOwnBots().catch(() => {}); // the group now belongs to this bot 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"; + // PEP-109: the group is served by the bot it is linked through; another bot in it stays silent. + if (!linkedHere(chat)) 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); @@ -569,6 +587,7 @@ export function createBot(o: BotOptions) { 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); + await syncOwnBots().catch(() => {}); return "done"; } if (m.chat.type !== "private") return onGroupMessage(m); @@ -627,7 +646,8 @@ export function createBot(o: BotOptions) { 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 found = await chatByTelegram(db, c.message.chat.id); + const chat = found && linkedHere(found) ? found : null; const who = chat ? await telegramAccountUser(db, c.from.id) : null; if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who; } diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index a3d5f9bd..b0ac3a90 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -1,7 +1,7 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react"; -import { analystPending, isSuperadmin, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core"; +import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, 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"; @@ -62,9 +62,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi return p.thread ? `${base}?thread=${encodeURIComponent(p.thread)}` : base; }; const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) }); - // The platform's bot (groups) is the superadmin's: users never see it — their own bot notifies them. + // PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's + // (users never see it) and links groups only for a superadmin without a bot of their own. const superadmin = await isSuperadmin(db, user); - const bot = superadmin ? ((await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null) : null; + const bot = user.telegramBotUsername ?? (superadmin ? ((await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null) : null); + const mayLink = !!user.telegramBotUsername || superadmin; + const groupBot = chat.tgTitle ? await chatGroupBotName(db, chat.id) : null; const ttlDays = Math.round(chatTtlMs() / 86_400_000); const taskThread = thread?.startsWith("task:"); const placeholder = master @@ -79,28 +82,33 @@ export default async function ChatPage({ params, searchParams }: { params: Promi const aside = (
- {!superadmin && ( -
-

Telegram

-

- {user.telegramBotUsername ? ( - <> - Новые сообщения обсуждения и вопросы агентов приходят в ваш бот @{user.telegramBotUsername}. - - ) : ( - <> - Чтобы новые сообщения приходили в Telegram, подключите своего бота: Настройки → Telegram. - - )} -

-
- )} -
-

Telegram-группа (суперадмин)

+
+

Telegram

+

+ {user.telegramBotUsername ? ( + <> + Новые сообщения обсуждения и вопросы агентов приходят в ваш бот @{user.telegramBotUsername}. + + ) : ( + <> + Чтобы новые сообщения приходили в Telegram, подключите своего бота: Настройки → Telegram. + + )} +

+
+
+

Telegram-группа

{chat.tgTitle ? ( <>

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

@@ -110,6 +118,11 @@ export default async function ChatPage({ params, searchParams }: { params: Promi + ) : !mayLink ? ( +

+ {master ? "Мастер-чат можно связать с группой Telegram — туда пойдёт всё важное по вашим проектам." : "Чат проекта можно связать с группой команды в Telegram."} Группа подключается через вашего собственного бота — сначала подключите его:{" "} + Настройки → Telegram. +

) : link ? (

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

@@ -118,12 +131,20 @@ export default async function ChatPage({ params, searchParams }: { params: Promi Добавить @{bot} в группу → )} -

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

- /link {link} +

Или добавьте {bot ? @{bot} : "бота"} в группу сами и отправьте там:

+ /link{bot ? `@${bot}` : ""} {link}
) : ( <> -

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

+

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

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

diff --git a/apps/web/app/(app)/chats/actions.ts b/apps/web/app/(app)/chats/actions.ts index 713735bf..06d88638 100644 --- a/apps/web/app/(app)/chats/actions.ts +++ b/apps/web/app/(app)/chats/actions.ts @@ -35,16 +35,16 @@ export async function postChatAction(f: FormData) { }); } -/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link that sends it. */ +/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link of the user's bot 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-бот Пеппы не настроен"); - // PEP-106: groups work through the platform's bot only — that bot is the superadmin's, not the users'. - if (!(await isSuperadmin(db, user))) throw new PeppaError("Группы Telegram подключает только суперадмин"); + 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); + // PEP-109: the group is linked through the user's own bot; the platform's bot is the + // superadmin's (PEP-106) and serves only a superadmin who has no bot of their own. + const code = await createChatLinkCode(db, token, user, chat.id, { sharedBot: await isSuperadmin(db, user) }); const back = str(f, "back") || "/chats"; return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`; }); diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index b3f3e7df..d4dd9b94 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -219,10 +219,12 @@ export default async function Help() { /move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней.

- Любой чат можно связать с группой Telegram: «Связать с Telegram» в чате → добавьте бота в группу по ссылке (или - отправьте в группе /link код). Сообщения чата придут в группу, тред — цепочкой + Любой чат можно связать с группой Telegram через вашего собственного бота (подключается в Настройках → + Telegram): «Связать с Telegram» в чате → добавьте своего бота в группу по ссылке (или отправьте в группе{" "} + /link код). Сообщения чата придут в группу от вашего бота, тред — цепочкой ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в - Настройках и имеет доступ к проекту (в мастер-группе — только владелец). + Настройках и имеет доступ к проекту (в мастер-группе — только владелец). Отключите или замените бота — группа + отвяжется.

diff --git a/openspec/changes/pep-109-chat-groups-own-bot/design.md b/openspec/changes/pep-109-chat-groups-own-bot/design.md index 3f827d84..caae891b 100644 --- a/openspec/changes/pep-109-chat-groups-own-bot/design.md +++ b/openspec/changes/pep-109-chat-groups-own-bot/design.md @@ -2,7 +2,7 @@ ## Решения - **Через какого бота связана группа — колонка `chats.tg_bot_user_id`** (владелец бота; null — общий бот платформы), а не вывод из `tg_linked_by`: связавший может позже подключить/сменить бота, а суперадмин без своего бота связывает через общий. Миграция 0018, одна nullable-колонка со ссылкой на `users` (`on delete set null`). -- **Код связки привязан к боту при выдаче**: в настройке кода сохраняется `botUserId` (id выдавшего, если у него свой бот; иначе null). `acceptChatLink` принимает код только от того же бота (`via.getStore()?.userId`), как `acceptPairing` в PEP-85. Чужой бот отвечает «код неверный или истёк» и код не сжигает — иначе второй бот в той же группе испортил бы связку (команда без `@бота` приходит всем ботам группы). +- **Код связки привязан к боту при выдаче**: в настройке кода сохраняется `botUserId` (id выдавшего, если у него свой бот; иначе null). `acceptChatLink` принимает код только от того же бота (`via.getStore()?.userId`), как `acceptPairing` в PEP-85. Чужой бот код не сжигает: на команду, адресованную ему (`/link@бот`), отвечает «код неверный или истёк», на команду без адреса молчит — иначе второй бот в той же группе испортил бы связку (команда без `@бота` приходит всем ботам группы). - **Кто может связать**: любой с доступом к чату (`chatForUser`) и своим ботом; суперадмин без своего бота — через общий, как было. Остальным — `PeppaError` с подсказкой подключить бота. - **Маршрутизация исходящих**: `ownByChat` в боте (chat_id → свой бот) дополняется группами (`chatGroupBots`), обновляется в `syncOwnBots` (раз в 10 с и сразу после связки). Очередь отправки не меняется — бот выбирается по `chat_id`, как для личных чатов. - **Входящие из группы**: сообщение/кнопку связанной группы обрабатывает только бот связки; остальные боты её игнорируют (без ответов), чтобы два бота в одной группе не отвечали дважды. diff --git a/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md b/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md index 63dcf593..d580175b 100644 --- a/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md +++ b/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md @@ -26,7 +26,7 @@ SHALL отвязываться. #### Scenario: Код в общем боте - **GIVEN** «anna» со своим ботом получила код связки чата PAY -- **WHEN** `/link <код>` получает общий бот платформы +- **WHEN** в группе общему боту платформы отправлено `/link@peppa_bot <код>` - **THEN** общий бот отвечает, что код неверный или истёк, чат не связан - **AND** тот же код после этого принимает «@anna_factory_bot» diff --git a/openspec/changes/pep-109-chat-groups-own-bot/tasks.md b/openspec/changes/pep-109-chat-groups-own-bot/tasks.md index 0bfcb8ba..359e2e93 100644 --- a/openspec/changes/pep-109-chat-groups-own-bot/tasks.md +++ b/openspec/changes/pep-109-chat-groups-own-bot/tasks.md @@ -1,6 +1,6 @@ -- [ ] 1.1 Колонка `chats.tg_bot_user_id` + миграция 0018 -- [ ] 1.2 core: код связки с ботом (`createChatLinkCode`/`acceptChatLink`), `chatGroupBots`, отвязка групп при отключении/замене бота -- [ ] 1.3 бот: связка и сообщения группы через свой бот, маршрутизация исходящих, чужой бот молчит -- [ ] 1.4 веб: «Связать с Telegram» для пользователя со своим ботом, подсказка без бота, справка +- [x] 1.1 Колонка `chats.tg_bot_user_id` + миграция 0018 +- [x] 1.2 core: код связки с ботом (`createChatLinkCode`/`acceptChatLink`), `chatGroupBots`, отвязка групп при отключении/замене бота +- [x] 1.3 бот: связка и сообщения группы через свой бот, маршрутизация исходящих, чужой бот молчит +- [x] 1.4 веб: «Связать с Telegram» для пользователя со своим ботом, подсказка без бота, справка - [ ] 1.5 тесты `chats-own-bot.test.ts` по сценариям, typecheck, полный прогон проверок - [ ] 1.6 AGENTS.md, память проекта diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index 0901819d..1c194624 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -475,33 +475,66 @@ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise `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 { +const UNLINKED = { tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null, tgBotUserId: null }; + +/** + * One-time code (10 minutes) that links a Telegram group to this chat. PEP-109: the group is + * linked through the user's own bot — the code is bound to it and only that bot accepts it. + * `sharedBot` (the superadmin without an own bot) binds the code to the platform's bot instead. + */ +export async function createChatLinkCode(db: Db, secret: string, user: Pick, chatId: number, o: { sharedBot?: boolean } = {}): Promise { await chatForUser(db, user, chatId); + const [u] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, user.id)); + if (!u?.own && !o.sharedBot) throw new PeppaError("Чтобы связать чат с группой, подключите своего бота: Настройки → Telegram"); const code = `c${randomBytes(12).toString("base64url")}`; - await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, expiresAt: Date.now() + LINK_TTL_MS }); + await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, botUserId: u?.own ? user.id : null, 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 { +/** + * Links the group the code was sent from. A group linked to another chat moves to this one. + * `botUserId` — the owner of the bot the code came to (absent = the shared bot): a code is + * accepted only by the bot it was issued for; another bot leaves it intact (a command without + * @bot reaches every bot of the group). + */ +export async function acceptChatLink(db: Db, secret: string, code: string, group: { tgChatId: number; title: string | null; botUserId?: number }, now = Date.now()): Promise { const key = linkKey(code, secret); - const saved = await getSetting<{ chatId: number; userId: number; expiresAt: number }>(db, key); + const saved = await getSetting<{ chatId: number; userId: number; botUserId?: number | null; expiresAt: number }>(db, key); if (!saved) return null; + const botUserId = saved.botUserId ?? null; + if (botUserId !== (group.botUserId ?? null)) 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; + tx.update(chats).set(UNLINKED).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, tgBotUserId: botUserId }).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)); + await db.update(chats).set(UNLINKED).where(eq(chats.id, chatId)); +} + +/** Whose bot a pending link code is for: a user id, null — the shared bot, undefined — no such code. */ +export async function chatLinkCodeBot(db: Db, secret: string, code: string): Promise { + const saved = await getSetting<{ botUserId?: number | null }>(db, linkKey(code, secret)); + return saved ? (saved.botUserId ?? null) : undefined; +} + +/** The @username of the own bot the chat's group is linked through (null — the shared bot). */ +export async function chatGroupBotName(db: Db, chatId: number): Promise { + const [u] = await db.select({ username: users.telegramBotUsername }).from(chats).innerJoin(users, eq(chats.tgBotUserId, users.id)).where(eq(chats.id, chatId)); + return u?.username ?? null; +} + +/** PEP-109: groups linked through users' own bots (the bot process routes their messages). */ +export async function chatGroupBots(db: Db): Promise> { + const rows = await db.select({ tgChatId: chats.tgChatId, botUserId: chats.tgBotUserId }).from(chats).where(and(isNotNull(chats.tgChatId), isNotNull(chats.tgBotUserId))); + return rows.map((r) => ({ tgChatId: r.tgChatId!, botUserId: r.botUserId! })); } /** A group became a supergroup: Telegram gives it a new id. */ diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts index 39ac1194..73c8df8b 100644 --- a/packages/core/src/telegram.ts +++ b/packages/core/src/telegram.ts @@ -1,5 +1,5 @@ import { createHmac, randomBytes } from "node:crypto"; -import { projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db"; +import { chats, projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db"; import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { decrypt, encrypt } from "./crypto.ts"; @@ -127,6 +127,9 @@ export async function setUserBot(db: Db, userId: number, token: string): Promise const me = await verifyBotToken(token); const taken = (await db.select({ id: users.id, username: users.telegramBotUsername }).from(users).where(isNotNull(users.telegramBotUsername))).find((u) => u.id !== userId && u.username?.toLowerCase() === me.username.toLowerCase()); if (taken) throw new PeppaError("Этот бот уже подключён другим пользователем — создайте своего в BotFather"); + const [before] = await db.select({ username: users.telegramBotUsername }).from(users).where(eq(users.id, userId)); + // PEP-109: another bot is not a member of the groups linked through the old one. + if (before?.username && before.username.toLowerCase() !== me.username.toLowerCase()) await unlinkBotGroups(db, userId); await db .update(users) .set({ telegramBotTokenEnc: encrypt(token.trim()), telegramBotUsername: me.username, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) @@ -134,8 +137,14 @@ export async function setUserBot(db: Db, userId: number, token: string): Promise return { username: me.username }; } -/** Back to the platform's shared bot (the chat pairing is dropped too). */ +/** PEP-109: groups linked through this user's bot lose the link together with the bot. */ +async function unlinkBotGroups(db: Db, userId: number): Promise { + await db.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null, tgBotUserId: null }).where(eq(chats.tgBotUserId, userId)); +} + +/** Back to the platform's shared bot (the chat pairing and the groups of the bot are dropped too). */ export async function clearUserBot(db: Db, userId: number): Promise { + await unlinkBotGroups(db, userId); await db .update(users) .set({ telegramBotTokenEnc: null, telegramBotUsername: null, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) diff --git a/packages/db/migrations/0018_lumpy_dreaming_celestial.sql b/packages/db/migrations/0018_lumpy_dreaming_celestial.sql new file mode 100644 index 00000000..05ceb1c7 --- /dev/null +++ b/packages/db/migrations/0018_lumpy_dreaming_celestial.sql @@ -0,0 +1 @@ +ALTER TABLE `chats` ADD `tg_bot_user_id` integer REFERENCES users(id) ON DELETE set null; \ No newline at end of file diff --git a/packages/db/migrations/meta/0018_snapshot.json b/packages/db/migrations/meta/0018_snapshot.json new file mode 100644 index 00000000..6f67b9cd --- /dev/null +++ b/packages/db/migrations/meta/0018_snapshot.json @@ -0,0 +1,4168 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "e8c300db-a064-4aee-b918-5d296675ceb5", + "prevId": "be145d37-3842-4e43-b7b7-8435001d71eb", + "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 + }, + "tg_bot_user_id": { + "name": "tg_bot_user_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": { + "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" + }, + "chats_tg_bot_user_id_users_id_fk": { + "name": "chats_tg_bot_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_bot_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_agent_id_agents_id_fk": { + "name": "sessions_agent_id_agents_id_fk", + "tableFrom": "sessions", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "telegram_outbox_chat_message_id_chat_messages_id_fk": { + "name": "telegram_outbox_chat_message_id_chat_messages_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_token_enc": { + "name": "telegram_bot_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_username": { + "name": "telegram_bot_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_sub": { + "name": "google_sub", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_email": { + "name": "google_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_linked_at": { + "name": "google_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + }, + "users_google_sub_unique": { + "name": "users_google_sub_unique", + "columns": [ + "google_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 3f6e63e3..16545985 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -127,6 +127,13 @@ "when": 1794727874686, "tag": "0017_lowly_ghost_rider", "breakpoints": true + }, + { + "idx": 18, + "version": "6", + "when": 1794738714712, + "tag": "0018_lumpy_dreaming_celestial", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 467f6084..ac97d939 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -511,6 +511,8 @@ export const chats = sqliteTable("chats", { tgTitle: text("tg_title"), tgLinkedAt: integer("tg_linked_at", { mode: "timestamp_ms" }), tgLinkedBy: integer("tg_linked_by").references(() => users.id, { onDelete: "set null" }), + // PEP-109: the owner of the bot the group is linked through (null — the platform's shared bot). + tgBotUserId: integer("tg_bot_user_id").references(() => users.id, { onDelete: "set null" }), createdAt: createdAt(), }); diff --git a/packages/testkit/test/chats-own-bot.test.ts b/packages/testkit/test/chats-own-bot.test.ts new file mode 100644 index 00000000..bd628714 --- /dev/null +++ b/packages/testkit/test/chats-own-bot.test.ts @@ -0,0 +1,163 @@ +// PEP-109: a chat's Telegram group is linked through the user's own bot (PEP-85) — the code is +// accepted only by that bot, the chat's messages and questions go out through it, replies and +// buttons of the group come back through it. Two mock-telegram instances: the platform's bot +// and the user's. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { core, db, teardown, waitFor } from "./helpers.ts"; +import { MockTelegram } from "../src/mock-telegram.ts"; +import { 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 shared = await new MockTelegram().start(); +const own = await new MockTelegram({ id: 4343, username: "mock_anna_factory_bot" }).start(); +const OWN_TOKEN = "1234567891:" + "B".repeat(35); +const ANNA = { id: 801, chatId: 801, username: "anna" }; +const BORIS = { id: 802, chatId: 802, username: "boris" }; +const STRANGER = { id: 809, chatId: 809, username: "stranger" }; +const GROUP = { id: -100900, title: "PAY team" }; +let bot: Bot; +let anna: Awaited>; +let boris: typeof anna; +let project: Awaited>; +let chat: Awaited>; + +const pause = (ms: number) => new Promise((r) => setTimeout(r, ms)); +async function connectOwnBot() { + process.env.TELEGRAM_API_URL = own.url; + try { + await core.setUserBot(db, anna.id, OWN_TOKEN); + } finally { + delete process.env.TELEGRAM_API_URL; + } + await bot.syncOwnBots(); +} + +before(async () => { + anna = await core.upsertUserFromGitea(db, { id: 10901, login: "mock-anna" }, { access_token: "x" }); + boris = await core.upsertUserFromGitea(db, { id: 10902, login: "mock-boris" }, { access_token: "y" }); + // Boris paired his personal Telegram (through whatever bot): that is who he is in a group. + await db.update(users).set({ telegramChatId: BORIS.chatId, telegramUserId: BORIS.id }).where(eq(users.id, boris.id)); + project = await core.createProject(db, { slug: "mock-pay109", key: "PAYG", name: "Pay", giteaOwner: "x", workspacePath: "/tmp/mock-pay109", ownerId: anna.id }); + await core.addMember(db, project, boris.login, anna.id); + chat = await core.ensureProjectChat(db, project.id); + bot = createBot({ + db, + api: new TelegramApi(shared.token, shared.url), + userApi: (token) => new TelegramApi(token, own.url), + secret: shared.token, + webUrl: "http://peppa.test", + pollTimeoutSec: 1, + outboxIntervalMs: 100, + reconcileIntervalMs: 300, + changesIntervalMs: 200, + userBotsIntervalMs: 200, + log: (m) => process.env.MOCK_DEBUG && console.log(m), + }); + await bot.start(); + await bot.reconcile(); // first start: mirroring begins from here +}); +after(async () => { + await bot.stop(); + await shared.stop(); + await own.stop(); + await teardown(); +}); + +describe("Telegram-группа чата через свой бот", () => { + test("Scenario: Нет своего бота — код не выдан", async () => { + await assert.rejects(core.createChatLinkCode(db, shared.token, boris, chat.id), /подключите своего бота/); + await assert.rejects(core.createChatLinkCode(db, shared.token, anna, chat.id), /подключите своего бота/); + // The superadmin without an own bot links through the platform's bot, as before. + const code = await core.createChatLinkCode(db, shared.token, anna, chat.id, { sharedBot: true }); + assert.equal(await core.chatLinkCodeBot(db, shared.token, code), null); + }); + + test("Scenario: Код в общем боте не принимается; Связать группу — через своего бота", async () => { + await connectOwnBot(); + const code = await core.createChatLinkCode(db, shared.token, anna, chat.id); + assert.equal(await core.chatLinkCodeBot(db, shared.token, code), anna.id); + + // Addressed to the platform's bot: refused, the code stays valid. + shared.userSendsInGroup(ANNA, GROUP, `/link@mock_peppa_bot ${code}`); + await waitFor("the shared bot refuses", async () => shared.botMessages(GROUP.id).some((m) => /неверный или истёк/.test(m.text))); + assert.equal((await core.getChat(db, chat.id)).tgChatId, null); + // Not addressed (every bot of the group gets it): the platform's bot keeps quiet. + const n = shared.botMessages(GROUP.id).length; + shared.userSendsInGroup(ANNA, GROUP, `/link ${code}`); + await pause(1500); + assert.equal(shared.botMessages(GROUP.id).length, n); + + own.userSendsInGroup(ANNA, GROUP, `/start@mock_anna_factory_bot ${code}`); + await waitFor("linked through the own bot", async () => own.botMessages(GROUP.id).some((m) => /Группа связана с чатом проекта PAYG/.test(m.text))); + const linked = await core.getChat(db, chat.id); + assert.deepEqual([linked.tgChatId, linked.tgTitle, linked.tgBotUserId, linked.tgLinkedBy], [GROUP.id, GROUP.title, anna.id, anna.id]); + assert.equal(await core.chatGroupBotName(db, chat.id), "mock_anna_factory_bot"); + assert.deepEqual(await core.chatGroupBots(db), [{ tgChatId: GROUP.id, botUserId: anna.id }]); + }); + + test("Scenario: Сообщения группы идут через бота связки; Ответ реплаем из группы; Посторонний в группе", async () => { + const sharedBefore = shared.botMessages(GROUP.id).length; + const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: project.id, title: "Экспорт" })).key); + const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?", options: ["запятая", "точка с запятой"] }); + const qMsg = await waitFor("question from the own bot", async () => own.botMessages(GROUP.id).find((m) => m.text.includes("Какой разделитель?"))); + assert.equal(shared.botMessages(GROUP.id).length, sharedBefore, "nothing from the platform's bot"); + + // The same group seen by the platform's bot: not its group, the reply is ignored. + shared.userSendsInGroup(BORIS, GROUP, "запятая", qMsg.message_id); + await pause(1500); + assert.equal((await core.getQuestion(db, q.id)).answeredAt, null); + assert.equal(shared.botMessages(GROUP.id).length, sharedBefore); + + own.userSendsInGroup(STRANGER, GROUP, "запятая", qMsg.message_id); + await waitFor("stranger hint", async () => own.botMessages(GROUP.id).some((m) => /Не знаю тебя в Пеппе/.test(m.text))); + assert.equal((await core.getQuestion(db, q.id)).answeredAt, null); + + own.userSendsInGroup(BORIS, 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.deepEqual([answered.answer, answered.answeredVia], ["точка с запятой", "telegram"]); + const thread = await core.chatMessagesView(db, chat.id, { threadKey: `task:${ref.task.id}` }); + assert.ok(thread.some((m) => m.kind === "user" && m.via === "telegram" && m.authorLogin === boris.login)); + // Peppa's note about the answer goes out through the same bot, into the thread. + const note = await waitFor("note in the thread", async () => own.botMessages(GROUP.id).find((m) => /Ответ (ушёл агенту|сохранён)/.test(m.text))); + assert.equal(note.reply_to, qMsg.message_id); + assert.equal(shared.botMessages(GROUP.id).length, sharedBefore); + }); + + test("Кнопка вопроса в группе своего бота", async () => { + const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: project.id, title: "Кнопки" })).key); + const q = await core.askPm(db, ref, { kind: "question", text: "Кнопкой?", options: ["да", "нет"] }); + const qMsg = await waitFor("question in the group", async () => own.botMessages(GROUP.id).find((m) => m.text.includes("Кнопкой?"))); + own.userClicks(BORIS, 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("Scenario: Бот отключён или заменён — группа отвязана", async () => { + // Replaced: the stored bot is another one than the token's. + await db.update(users).set({ telegramBotUsername: "mock_old_bot" }).where(eq(users.id, anna.id)); + await connectOwnBot(); + assert.deepEqual([(await core.getChat(db, chat.id)).tgChatId, (await core.getChat(db, chat.id)).tgBotUserId], [null, null]); + + // The same bot connected again keeps its groups; disconnecting drops them. + const code = await core.createChatLinkCode(db, shared.token, anna, chat.id); + assert.ok(await core.acceptChatLink(db, shared.token, code, { tgChatId: GROUP.id, title: GROUP.title, botUserId: anna.id })); + await connectOwnBot(); + assert.equal((await core.getChat(db, chat.id)).tgChatId, GROUP.id); + await core.clearUserBot(db, anna.id); + const c = await core.getChat(db, chat.id); + assert.deepEqual([c.tgChatId, c.tgTitle, c.tgBotUserId], [null, null, null]); + assert.deepEqual(await core.chatGroupBots(db), []); + }); +}); diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts index 7b7a0c60..752b61cc 100644 --- a/packages/testkit/test/chats.test.ts +++ b/packages/testkit/test/chats.test.ts @@ -169,9 +169,9 @@ describe("Telegram group", () => { }); test("Просроченный код и связка группы", async () => { - const code = await core.createChatLinkCode(db, tg.token, pm, chat.id); + const code = await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true }); // A stale code: accepted 11 minutes later. - const stale = await core.createChatLinkCode(db, tg.token, pm, chat.id); + const stale = await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true }); 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))); From 312c1365c8ec4cd5132711096d4e586a95ed74f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 15:43:27 +0500 Subject: [PATCH 3/3] PEP-109: archive change, project memory Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 4 ++ .../design.md | 0 .../proposal.md | 0 .../specs/project-chats/spec.md | 0 .../tasks.md | 4 +- openspec/specs/project-chats/spec.md | 50 +++++++++++++++---- 6 files changed, 45 insertions(+), 13 deletions(-) rename openspec/changes/{pep-109-chat-groups-own-bot => archive/2026-11-15-pep-109-chat-groups-own-bot}/design.md (100%) rename openspec/changes/{pep-109-chat-groups-own-bot => archive/2026-11-15-pep-109-chat-groups-own-bot}/proposal.md (100%) rename openspec/changes/{pep-109-chat-groups-own-bot => archive/2026-11-15-pep-109-chat-groups-own-bot}/specs/project-chats/spec.md (100%) rename openspec/changes/{pep-109-chat-groups-own-bot => archive/2026-11-15-pep-109-chat-groups-own-bot}/tasks.md (85%) diff --git a/.peppa/memory.md b/.peppa/memory.md index dd5b8246..8d2c954b 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -15,4 +15,8 @@ - Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents. - tmux-сервер по умолчанию: newSession чистит его глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69; при PEPPA_TMUX_SOCKET не трогает); агенту нужное — только через new-session -e. - Вход через Google (PEP-90): идентичность — google_sub, по почте учётки не склеиваем; без GOOGLE_CLIENT_ID/SECRET кнопки нет; в тестах эндпоинты подменяет GOOGLE_OAUTH_BASE (mock-google). `pnpm typecheck` в apps/web может падать на устаревших .next/types (auth/callback, auth/start) — не от правок. +<<<<<<< HEAD - Подписки без остановок (PEP-107): ротация claude↔codex, когда нет того же провайдера (PEPPA_ROTATE_CROSS=off выключает, OpenCode не участвует); займы суперадмина и отметки предупреждений — строки settings (`subscription.loan::`, `subscription.warned::`), без миграций; картина пула — `poolOverview` в core/subscription-care.ts. +======= +- Группы чатов (PEP-109) связываются через свой бот пользователя: `chats.tg_bot_user_id` (null — общий бот, только суперадмин без своего бота); код связки привязан к боту и чужим ботом не сжигается; новые исходящие в группу маршрутизируются по chat_id через `ownByChat` (`chatGroupBots`) — отдельный outbox не нужен. +>>>>>>> da5eb5c (PEP-109: archive change, project memory) diff --git a/openspec/changes/pep-109-chat-groups-own-bot/design.md b/openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/design.md similarity index 100% rename from openspec/changes/pep-109-chat-groups-own-bot/design.md rename to openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/design.md diff --git a/openspec/changes/pep-109-chat-groups-own-bot/proposal.md b/openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/proposal.md similarity index 100% rename from openspec/changes/pep-109-chat-groups-own-bot/proposal.md rename to openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/proposal.md diff --git a/openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md b/openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/specs/project-chats/spec.md similarity index 100% rename from openspec/changes/pep-109-chat-groups-own-bot/specs/project-chats/spec.md rename to openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/specs/project-chats/spec.md diff --git a/openspec/changes/pep-109-chat-groups-own-bot/tasks.md b/openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/tasks.md similarity index 85% rename from openspec/changes/pep-109-chat-groups-own-bot/tasks.md rename to openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/tasks.md index 359e2e93..76ad5d4d 100644 --- a/openspec/changes/pep-109-chat-groups-own-bot/tasks.md +++ b/openspec/changes/archive/2026-11-15-pep-109-chat-groups-own-bot/tasks.md @@ -2,5 +2,5 @@ - [x] 1.2 core: код связки с ботом (`createChatLinkCode`/`acceptChatLink`), `chatGroupBots`, отвязка групп при отключении/замене бота - [x] 1.3 бот: связка и сообщения группы через свой бот, маршрутизация исходящих, чужой бот молчит - [x] 1.4 веб: «Связать с Telegram» для пользователя со своим ботом, подсказка без бота, справка -- [ ] 1.5 тесты `chats-own-bot.test.ts` по сценариям, typecheck, полный прогон проверок -- [ ] 1.6 AGENTS.md, память проекта +- [x] 1.5 тесты `chats-own-bot.test.ts` по сценариям, typecheck, полный прогон проверок +- [x] 1.6 AGENTS.md, память проекта diff --git a/openspec/specs/project-chats/spec.md b/openspec/specs/project-chats/spec.md index 10c091dd..c7018b65 100644 --- a/openspec/specs/project-chats/spec.md +++ b/openspec/specs/project-chats/spec.md @@ -65,15 +65,38 @@ TBD - created by archiving change pep-62-chats. Update Purpose after archive. ### Requirement: Связка чата с Telegram-группой Чат проекта и мастер-чат SHALL связываться с обычной Telegram-группой по одноразовому коду -(10 минут). Сообщения связанного чата SHALL дублироваться в группу, тред — цепочкой реплаев -на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и обрабатываться как -сообщение из веба; принимать его SHALL только от пользователя Пеппы с привязанным Telegram и -доступом к проекту (в мастер-группе — от владельца мастер-чата). +(10 минут) через собственного бота пользователя, который связывает: веб SHALL предлагать +ссылку «Добавить @его_бот в группу», а код SHALL приниматься только этим ботом. Общий бот +платформы пользователям SHALL NOT предлагаться; через него группу связывает только суперадмин +без своего бота. Пользователю без своего бота веб SHALL показывать подсказку подключить бота +вместо связки. Сообщения связанного чата SHALL дублироваться в группу через бота связки, тред — +цепочкой реплаев на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и +обрабатываться как сообщение из веба; принимать его SHALL только бот связки и только от +пользователя Пеппы с привязанным Telegram и доступом к проекту (в мастер-группе — от владельца +мастер-чата). Когда владелец отключает или заменяет своего бота, группы, связанные через него, +SHALL отвязываться. #### Scenario: Связать группу -- **GIVEN** участник открыл чат PAY и нажал «Связать с Telegram» -- **WHEN** в группе «PAY team» отправлено `/link <код>` до истечения кода -- **THEN** чат PAY связан с «PAY team», бот подтверждает это в группе, веб показывает название группы +- **GIVEN** «anna» подключила своего бота «@anna_factory_bot», открыла чат PAY и нажала «Связать с Telegram» +- **WHEN** в группе «PAY team» боту «@anna_factory_bot» отправлено `/link <код>` до истечения кода +- **THEN** чат PAY связан с «PAY team», «@anna_factory_bot» подтверждает это в группе +- **AND** веб показывает название группы и «@anna_factory_bot» + +#### Scenario: Сообщения группы идут через бота связки +- **GIVEN** чат PAY связан с группой «PAY team» через «@anna_factory_bot» +- **WHEN** агент задаёт вопрос по стори PAY-7 +- **THEN** вопрос приходит в группу от «@anna_factory_bot», от общего бота в группе ничего нет + +#### Scenario: Код в общем боте +- **GIVEN** «anna» со своим ботом получила код связки чата PAY +- **WHEN** в группе общему боту платформы отправлено `/link@peppa_bot <код>` +- **THEN** общий бот отвечает, что код неверный или истёк, чат не связан +- **AND** тот же код после этого принимает «@anna_factory_bot» + +#### Scenario: Нет своего бота +- **GIVEN** «boris» без своего бота и не суперадмин +- **WHEN** он запрашивает код связки чата PAY +- **THEN** код не выдан, показано «подключите своего бота в Настройках → Telegram» #### Scenario: Просроченный код - **GIVEN** код связки выдан 11 минут назад @@ -81,16 +104,21 @@ TBD - created by archiving change pep-62-chats. Update Purpose after archive. - **THEN** бот отвечает, что код неверный или истёк, чат не связан #### Scenario: Ответ реплаем из группы -- **GIVEN** чат PAY связан с группой, вопрос PAY-7 пришёл в группу -- **AND** «anna» привязала Telegram и участник PAY -- **WHEN** «anna» отвечает реплаем на вопрос «точка с запятой» -- **THEN** вопрос отвечен, в веб-треде PAY-7 видно её сообщение с пометкой Telegram +- **GIVEN** чат PAY связан с группой через «@anna_factory_bot», вопрос PAY-7 пришёл в группу +- **AND** «boris» привязал Telegram и участник PAY +- **WHEN** «boris» отвечает реплаем на вопрос «точка с запятой» +- **THEN** вопрос отвечен, в веб-треде PAY-7 видно его сообщение с пометкой Telegram #### Scenario: Посторонний в группе - **GIVEN** в группе PAY есть человек без привязки Telegram в Пеппе - **WHEN** он отвечает реплаем на вопрос PAY-7 - **THEN** вопрос не отвечен, сообщения в чате нет, бот подсказывает привязать Telegram +#### Scenario: Бот отключён +- **GIVEN** чат PAY связан с группой через «@anna_factory_bot» +- **WHEN** «anna» отключает своего бота в Настройках +- **THEN** чат PAY больше не связан с группой + ### Requirement: Короткое хранение переписки Сообщения чатов SHALL удаляться через `PEPPA_CHAT_TTL_DAYS` дней (по умолчанию 14); стори, вопросы, события, релизы и инциденты при этом SHALL оставаться.