From 54f242d0c592bc74a8cefceb009e66b8604a5823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:23:26 +0500 Subject: [PATCH 01/11] =?UTF-8?q?PEP-149:=20proposal=20=E2=80=94=20four=20?= =?UTF-8?q?kinds=20of=20agent=20messages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../.openspec.yaml | 2 + .../pep-149-agent-message-kinds/design.md | 31 ++++++ .../pep-149-agent-message-kinds/proposal.md | 30 +++++ .../specs/agent-messages/spec.md | 104 ++++++++++++++++++ .../pep-149-agent-message-kinds/tasks.md | 22 ++++ 5 files changed, 189 insertions(+) create mode 100644 openspec/changes/pep-149-agent-message-kinds/.openspec.yaml create mode 100644 openspec/changes/pep-149-agent-message-kinds/design.md create mode 100644 openspec/changes/pep-149-agent-message-kinds/proposal.md create mode 100644 openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md create mode 100644 openspec/changes/pep-149-agent-message-kinds/tasks.md diff --git a/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml b/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml new file mode 100644 index 00000000..90080a92 --- /dev/null +++ b/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/pep-149-agent-message-kinds/design.md b/openspec/changes/pep-149-agent-message-kinds/design.md new file mode 100644 index 00000000..2b5b8ea4 --- /dev/null +++ b/openspec/changes/pep-149-agent-message-kinds/design.md @@ -0,0 +1,31 @@ +# Design: PEP-149 + +## Context + +Сообщение пользователю сегодня — строка `questions` с `kind` (`question | permission | approval | attention`). `attention` — это и «готово к ревью», и сбой, и «агент закончил ход». Ход работы (`report_progress`) — событие `progress`, которое `syncChats` кладёт в тред задачи. + +## Decisions + +**1. Где хранится тип.** Две новые колонки `questions`: `msg_type` (`question | done | progress | blocker`, nullable) и `default_option` (текст варианта по умолчанию). `kind` не трогаем: на нём держатся хук разрешений, одобрение плана, «Принять», сбои. Сообщения, у которых нет строки вопроса, типизирует само событие: `progress` и новое `blocker` в `events` (их проекция в `chat_messages` идёт по типу события). Колонку в `chat_messages` не добавляем: у сообщения чата есть `question_id` или оно пришло из события — тип выводится. Альтернатива «расширить enum `kind`» отвергнута: десятки мест сравнивают `kind === "attention"`, в том числе в файлах соседних задач. + +**2. Тип новых и старых строк.** При вставке (`askPm`, `askPmProject`, `raiseSessionQuestion`) тип берётся из аргумента, иначе: не `attention` → `question`; `attention` с вариантами ответа → `question`. Остальные `attention` (сбои, лимиты, выкладки — тексты соседних задач) остаются без типа. Для чтения — одна функция `questionType(q, taskStatus)`: сохранённый тип → правило выше → `attention` у задачи в ревью = `done` → `null` («сообщение от фабрики»). Старые строки не переписываются — работают по тому же правилу. + +**3. Маршруты.** +- `question` и `done` — «ждут человека»: «Ждут вашего ответа» (только question), счётчики меню и `/api/attention` (question + done), push, Telegram с кнопками. Одно SQL-условие `NEEDS_PERSON` в `core/questions.ts` для счётчиков. +- `progress` — только событие → тред задачи в «Событиях агентов». Ни вопроса, ни Telegram, ни push. +- `blocker` — `report_blocker`: продуктовый (с вариантами и вариантом по умолчанию) создаёт question; непродуктовый — событие `blocker` в треде задачи и сообщение администраторам фабрики (`alertAdmins`), владельцу проекта ничего. Что делать с блокером дальше — задача про сбои. +- Сообщения без типа (сбои и т. п.) по-прежнему уходят в Telegram и чат проекта, но без кнопки «Продолжай», не в «Ждут вашего ответа», не в счётчик и без push. Их дальнейшая судьба — задача про сбои. + +**4. Конец хода.** Последняя ветка `turnEnd`: событие `progress` (`{text, auto: true}`) вместо вопроса; сессия → `idle` (не `waiting_input`: она не ждёт человека и не должна светиться в «ждут вас»). Чтобы такие сессии не висели вечно, `idleStopTick` останавливает и `idle`-сессии задач (одно условие, тексты не меняются). Открытые сообщения без типа больше не блокируют подталкивание агента — блокируют только question. + +**5. Кто будит агента.** Красные проверки, ревьюер, rebase и комментарии уже будят. Добавляется зелёный случай: отчёт о пройденной проверке, задача в работе, ход агента окончен, гейт ревью открыт → одно сообщение агенту на коммит («проверки прошли — переводи в review»), отметка `ci.woke:`. + +**6. `done`.** Только через `sendReviewCard` (гейт PEP-127 без изменений), тип `done`. Если в тексте нет ни одной ссылки — добавляется ссылка на страницу задачи. + +**7. `ask_pm`.** `options` (2–4) и `default` (текст одного из вариантов) проверяются в обработчике, а не схемой, чтобы агент получил объяснение, а не ошибку валидации. Вариант по умолчанию ставится первым и подсвечивается; под вопросом — «Если не ответите, агент продолжит по варианту …». + +## Risks / Trade-offs + +- Соседние задачи эпика тоже могут добавить миграцию → конфликт журнала drizzle при rebase: перегенерировать свою миграцию поверх main. +- Агент, который закончил ход и ничего не ждёт, остаётся без пинка до остановки по простою — сознательно: это «сбой», а не вопрос продакту (соседняя задача). +- Вопрос «проверки не проходят 3 раза» (`ci-feedback.ts`) остаётся вопросом без вариантов — его перепишет задача про сбои. diff --git a/openspec/changes/pep-149-agent-message-kinds/proposal.md b/openspec/changes/pep-149-agent-message-kinds/proposal.md new file mode 100644 index 00000000..db50313b --- /dev/null +++ b/openspec/changes/pep-149-agent-message-kinds/proposal.md @@ -0,0 +1,30 @@ +# PEP-149: четыре типа сообщений агента + +## Why + +Пользователь Peppa FACTORY — продакт. Сейчас любой конец хода агента превращается в «вопрос» с сырым текстом последней реплики и кнопкой «Продолжай» (PEP-147: девять одинаковых сообщений за 18 минут). В «Ждут вашего ответа» и в Telegram попадает всё подряд, и настоящие вопросы теряются. + +## What Changes + +- У сообщения агента пользователю появляется тип: **question**, **done**, **progress**, **blocker**. От типа зависит маршрут. +- Конец хода без смены статуса задачи больше не будит пользователя: реплика агента становится записью хода работы (`progress`) в «Событиях агентов». Агента, который ждёт проверок, будит платформа, когда проверки прошли. +- `ask_pm` требует 2–4 варианта ответа и вариант по умолчанию; без них — отказ с объяснением. Новый инструмент `report_blocker`. `report_progress` — тип progress. +- «Готово» (`done`) шлёт только платформа, только после зелёных проверок и всегда со ссылкой на результат. +- Кнопка «Продолжай» убрана из веба и бота. **BREAKING** для старых сообщений Telegram: кнопка на них больше не срабатывает. +- «Ждут вашего ответа», счётчики, напоминания и push считают только question (и done — как «ждёт „Принять“»). +- `template/RULES.md` и «Помощь» описывают четыре типа. + +## Capabilities + +### New Capabilities +- `agent-messages`: типы сообщений агента пользователю и маршрут каждого типа. + +### Modified Capabilities + +Нет: поведение прежних спецификаций (хуки, MCP, уведомления) описывается здесь одним новым контрактом; требования соседних возможностей про сбои и повторы не меняются. + +## Impact + +- БД: `questions.msg_type`, `questions.default_option` (миграция; применяет координатор). +- `packages/core` (новый `questions.ts`, `tasks.ts`, `sessions.ts`, `review-card.ts`, `notifications.ts`, строка в `EVENT_TEXT`), `packages/runner` (`hook.ts`, `ci-feedback.ts`, одно условие в `recovery.ts`), `packages/mcp` (`agent.ts`, `manager.ts`), `apps/web` (карточка вопроса, «Ждут вашего ответа», счётчики, «Помощь»), `apps/bot` (`render.ts`, `bot.ts`), `template/RULES.md`, переводы en/kk. +- Тексты сбоев (`recovery.ts`, `watchdog.ts`, `autonomy.ts`) и логика повторов в `core/chats.ts` не меняются — соседние задачи эпика. diff --git a/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md b/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md new file mode 100644 index 00000000..669e5093 --- /dev/null +++ b/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md @@ -0,0 +1,104 @@ +# Spec Delta + +## Purpose +Сообщения агента пользователю делятся на четыре типа — вопрос, готово, ход работы, блокер; от типа зависит, увидит ли его пользователь в «Ждут вашего ответа», в Telegram или только в «Событиях агентов». + +## ADDED Requirements + +### Requirement: Тип сообщения определяет маршрут +Система SHALL присваивать каждому новому сообщению агента пользователю один из типов `question`, `done`, `progress`, `blocker`. В «Ждут вашего ответа» SHALL попадать только `question`; счётчик «ждут вас», напоминания и push SHALL учитывать только `question` и `done`. + +#### Scenario: Вопрос попадает в «Ждут вашего ответа» +- **GIVEN** задача PEP-1 в работе +- **WHEN** агент задаёт вопрос «Какой цвет кнопки?» с вариантами «Синий» и «Зелёный», по умолчанию «Синий» +- **THEN** на Главной в «Ждут вашего ответа» есть этот вопрос с кнопками «Синий» и «Зелёный» и полем «Свой ответ» +- **AND** счётчик «ждут вас» равен 1 + +#### Scenario: Сообщение о сбое не попадает в «Ждут вашего ответа» +- **GIVEN** открытое сообщение фабрики без вариантов ответа «агент остановился с ошибкой» +- **WHEN** пользователь открывает Главную +- **THEN** в «Ждут вашего ответа» этого сообщения нет +- **AND** счётчик «ждут вас» равен 0 + +### Requirement: Конец хода — это ход работы, а не вопрос +Когда агент закончил ход, а статус задачи не изменился и подталкивания исчерпаны, система SHALL записать последнюю реплику агента как `progress` в «События агентов» и SHALL NOT создавать вопрос, отправлять Telegram или push. + +#### Scenario: Агент закончил ход, статус задачи тот же +- **GIVEN** задача PEP-1 в работе, агент уже дважды получил подталкивание +- **WHEN** агент заканчивает ход с текстом «Жду проверок» +- **THEN** в «Ждут вашего ответа» и в Telegram владельца ничего нового нет +- **AND** в «Событиях агентов» проекта, в треде PEP-1, есть запись «Жду проверок» + +#### Scenario: У агента есть открытый вопрос +- **GIVEN** агент задал вопрос с вариантами и не получил ответа +- **WHEN** агент заканчивает ход +- **THEN** новая запись хода работы не создаётся, вопрос остаётся в «Ждут вашего ответа» + +### Requirement: Платформа будит агента, когда проверки прошли +Когда все проверки последнего коммита задачи в работе прошли, а ход агента окончен, система SHALL один раз на коммит сообщить агенту, что задачу можно переводить в ревью. + +#### Scenario: Проверки прошли, агент ждал +- **GIVEN** задача PEP-1 в работе, агент закончил ход, проверки коммита `abc1234` ещё шли +- **WHEN** последняя проверка коммита `abc1234` проходит +- **THEN** агент получает сообщение «проверки прошли» + +#### Scenario: Повторный отчёт о том же коммите +- **GIVEN** агент уже получил сообщение о коммите `abc1234` +- **WHEN** приходит ещё один успешный отчёт по коммиту `abc1234` +- **THEN** второго сообщения агент не получает + +### Requirement: «Готово» шлёт платформа после проверок +Сообщение типа `done` SHALL отправляться только платформой, только когда проверки последнего коммита прошли и нет конфликта, и SHALL содержать ссылку на результат. + +#### Scenario: Проверки прошли +- **GIVEN** задача PEP-1 в ревью, проверки зелёные, результат `https://git.example/pulls/7` +- **WHEN** агент заканчивает ход +- **THEN** владелец получает сообщение «готова к ревью» типа `done` со ссылкой `https://git.example/pulls/7` и кнопкой «Принять» + +#### Scenario: Проверки ещё идут +- **GIVEN** задача PEP-1 в ревью, одна проверка не завершена +- **WHEN** агент заканчивает ход +- **THEN** владелец ничего не получает, пока проверки не пройдут + +### Requirement: Вопрос агента — с вариантами и вариантом по умолчанию +Инструмент `ask_pm` SHALL принимать вопрос только с 2–4 вариантами ответа и вариантом по умолчанию из их числа; иначе SHALL отклонять вызов с объяснением. + +#### Scenario: Вопрос с вариантами принят +- **WHEN** агент вызывает `ask_pm` с вариантами «Да», «Нет» и вариантом по умолчанию «Да» +- **THEN** вопрос отправлен, вариант «Да» показан первым и отмечен как выбранный по умолчанию + +#### Scenario Outline: Вопрос без вариантов отклонён +- **WHEN** агент вызывает `ask_pm` с вариантами <варианты> и вариантом по умолчанию <по умолчанию> +- **THEN** вызов отклонён с объяснением «<причина>», вопрос не создан + +| варианты | по умолчанию | причина | +|---|---|---| +| нет | нет | нужны 2–4 варианта | +| «Да» | «Да» | нужны 2–4 варианта | +| «Да», «Нет» | нет | нужен вариант по умолчанию | +| «Да», «Нет» | «Может быть» | вариант по умолчанию — один из вариантов | + +### Requirement: Блокер идёт по своему маршруту +Инструмент `report_blocker` SHALL принимать, что мешает и что агент уже пробовал. Продуктовый блокер SHALL идти пользователю как `question` с вариантами; непродуктовый SHALL записываться в «События агентов» и SHALL NOT отправляться владельцу проекта. + +#### Scenario: Непродуктовый блокер +- **WHEN** агент сообщает блокер «нет доступа к серверу сборки», пробовал «повторил три раза» +- **THEN** в треде задачи в «Событиях агентов» есть запись о блокере +- **AND** владелец не получает ни вопроса, ни сообщения в Telegram + +#### Scenario: Продуктовый блокер без вариантов +- **WHEN** агент сообщает продуктовый блокер без вариантов ответа +- **THEN** вызов отклонён с объяснением, что нужны варианты и вариант по умолчанию + +### Requirement: Нет кнопки «Продолжай» +Веб и Telegram-бот SHALL NOT показывать кнопку «Продолжай» ни у какого сообщения; у `question` SHALL быть кнопки вариантов и возможность своего ответа. + +#### Scenario: Сообщение фабрики в Telegram +- **GIVEN** открытое сообщение фабрики без вариантов ответа +- **WHEN** бот отправляет его в Telegram +- **THEN** у сообщения нет кнопки «Продолжай» + +#### Scenario: Старая кнопка «Продолжай» +- **GIVEN** старое сообщение в Telegram с кнопкой «Продолжай» +- **WHEN** пользователь нажимает её +- **THEN** агенту ничего не отправляется diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/pep-149-agent-message-kinds/tasks.md new file mode 100644 index 00000000..e470d634 --- /dev/null +++ b/openspec/changes/pep-149-agent-message-kinds/tasks.md @@ -0,0 +1,22 @@ +# Tasks: PEP-149 + +## 1. Ядро +- [ ] 1.1 Миграция: `questions.msg_type`, `questions.default_option` +- [ ] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion` +- [ ] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна +- [ ] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`) + +## 2. Агент +- [ ] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle` +- [ ] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит) +- [ ] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress` + +## 3. Веб и бот +- [ ] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике) +- [ ] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP +- [ ] 3.3 Переводы en/kk + +## 4. Правила, помощь, проверки +- [ ] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа +- [ ] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов +- [ ] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта From 45754f1f239856d4039ef166838f2ad7190d7c95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:26:41 +0500 Subject: [PATCH 02/11] =?UTF-8?q?PEP-149:=20message=20types=20=E2=80=94=20?= =?UTF-8?q?end=20of=20turn=20is=20progress,=20ask=5Fpm=20with=20options=20?= =?UTF-8?q?and=20default,=20report=5Fblocker,=20no=20=C2=ABcontinue=C2=BB?= =?UTF-8?q?=20button?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/bot/src/bot.ts | 15 ++++++-- apps/bot/src/render.ts | 18 +++++----- apps/web/app/(app)/page.tsx | 9 +++-- apps/web/components/cards.tsx | 9 ++--- apps/web/lib/queries.ts | 23 +++++++++--- packages/core/src/chats.ts | 7 ++-- packages/core/src/index.ts | 1 + packages/core/src/notifications.ts | 16 +++++---- packages/core/src/questions.ts | 56 ++++++++++++++++++++++++++++++ packages/core/src/review-card.ts | 6 ++-- packages/core/src/sessions.ts | 5 +-- packages/core/src/tasks.ts | 24 +++++++++++-- packages/db/src/schema.ts | 5 +++ packages/mcp/src/agent.ts | 48 +++++++++++++++++++++---- packages/mcp/src/manager.ts | 9 +++-- packages/runner/src/ci-feedback.ts | 29 ++++++++++++++++ packages/runner/src/hook.ts | 18 ++++++---- packages/runner/src/recovery.ts | 4 ++- 18 files changed, 249 insertions(+), 53 deletions(-) create mode 100644 packages/core/src/questions.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 6f0f0cad..851119d2 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -39,6 +39,7 @@ import { markOutboxRetry, markOutboxSent, pendingQuestions, + needsPerson, questionByTelegramMessage, setOffset, setSetting, @@ -305,12 +306,20 @@ export function createBot(o: BotOptions) { const waitingFor = async (userId: number) => { if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId))); const ids = projectsOf.get(userId)!; - return open.filter((x) => ids.has(x.projectId)).length; + return open.filter((x) => ids.has(x.projectId) && waits.has(x.id)).length; }; + // PEP-149: what waits for a person — questions and finished stories; only these push and count. + const ctxOf = new Map>>(); + const waits = new Set(); + for (const q of open) { + const c = await context(q); + ctxOf.set(q.id, c); + if (needsPerson(q, c.taskStatus)) waits.add(q.id); + } for (const q of open) { const audience = await projectAudience(db, q.projectId); if (!audience.length) continue; - const ctx = await context(q); + const ctx = ctxOf.get(q.id)!; const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status }); const r = renderQuestion(q, ctx); // A push is a "now" signal: questions older than this don't pop up on a fresh subscription. @@ -323,7 +332,7 @@ export function createBot(o: BotOptions) { dedupeKey: `q:${q.id}:${u.telegramChatId}`, pushKey: `q:${q.id}:u${u.id}`, telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } }, - push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined, + push: fresh && waits.has(q.id) ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined, urgency: event === "questions" || event === "failures" ? "high" : "normal", }); } diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 5536a560..dcff09a2 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -1,5 +1,5 @@ // Telegram message texts and buttons for PM questions. HTML parse mode. -import type { Question, SessionView } from "@peppa/core"; +import { questionType, type Question, type SessionView } from "@peppa/core"; import type { InlineButton } from "./telegram.ts"; import { m as tr } from "@peppa/shared/i18n"; @@ -31,6 +31,7 @@ export function renderQuestion( const lines = [head, KIND[q.kind], "", body]; const buttons: InlineButton[][] = []; + const type = questionType(q, ctx.taskStatus); if (q.kind === "approval") { buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]); lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием."))); @@ -40,23 +41,24 @@ export function renderQuestion( { text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` }, { text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` }, ]); - } else if (q.kind === "question") { + } else if (type === "question") { + // PEP-149: a question always comes with answers to tap; the default goes first. (q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }])); + if (q.kind === "attention") lines[1] = KIND.question; lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом."))); - } else if (ctx.taskStatus === "review") { + if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption })))); + } else if (type === "done") { lines[1] = tr("✅ Готово к ревью"); buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]); lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает."))); } else { + // A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button. const s = ctx.session; if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) { buttons.push([ { text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` }, { text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` }, ]); - } else { - buttons.push([{ text: tr("▶️ Продолжай"), callback_data: `q:${q.id}:cont` }]); - lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту."))); } } if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); @@ -75,8 +77,8 @@ export function renderAnswered(original: string, q: Question): string { export function choiceToAnswer(q: Question, choice: string): string | null { if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice; - if (q.kind === "attention" && choice === "cont") return "Продолжай."; // i18n-ignore: the answer goes to the agent + // PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing. const m = /^o(\d+)$/.exec(choice); - if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null; + if (m) return q.options?.[Number(m[1])] ?? null; return null; } diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 2148b466..6ce600d7 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -12,7 +12,7 @@ import { Workspace } from "@/components/Workspace"; import { requireUser, words } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; -import { activeSessions, inbox } from "@/lib/queries"; +import { acceptInbox, activeSessions, inbox } from "@/lib/queries"; export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -20,7 +20,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e const t = await getT(); const w = await words(); if (await claimWelcome(db, user.id)) redirect("/welcome"); - const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]); + const [items, ready, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), acceptInbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]); // PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here. const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : []; return ( @@ -33,6 +33,11 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e {items.map((q) => )} + {ready.length > 0 && ( +
+ {ready.map((q) => )} +
+ )} {reports.length > 0 && (
{t("все обращения")}}> {reports.slice(0, 5).map((f) => )} diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index ac09bb01..47eb7afe 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -37,7 +37,8 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal const t = await getT(); const review = q.kind === "attention" && taskStatus === "review"; const answered = !!q.answeredAt; - const k = KIND[q.kind]; + // PEP-149: a factory message with answers to choose from is a question for the person. + const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind]; const Icon = review ? CircleCheck : k.icon; // PEP-151: the same state came again — one message with the time it was last refreshed. const state = await questionState(db, q.id).catch(() => null); @@ -89,12 +90,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal )} {review && } - {/* i18n-ignore: the value is the message to the agent */} - {q.kind === "attention" && !review && } + {/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */} {(q.options ?? []).map((o) => ( - + ))} + {q.defaultOption &&

{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}

} {q.kind !== "permission" && (
diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index 4bd2a7e6..e5598a4e 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -1,4 +1,4 @@ -import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core"; +import { listSessions, needsPerson, questionType, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core"; import { events, projects, questions, sessions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { m } from "@peppa/shared/i18n"; @@ -7,8 +7,22 @@ import { db } from "./db"; export type InboxItem = Awaited>[number]; -/** Open PM questions across the user's projects, oldest first. */ +/** + * PEP-149: «Ждут вашего ответа» — open messages of type `question` across the user's projects, + * oldest first. Stories waiting for «Принять» (`done`) have their own block; progress, blockers + * and factory messages never land here. + */ export async function inbox(userId: number) { + return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "question"); +} + +/** PEP-149: finished stories waiting for «Принять» — open messages of type `done`. */ +export async function acceptInbox(userId: number) { + return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "done" && q.taskStatus === "review"); +} + +/** Every open message of the user's projects (any type), oldest first. */ +async function openMessages(userId: number) { const ids = await userProjectIds(db, userId); if (!ids.length) return []; const rows = await db @@ -65,11 +79,12 @@ export const isActiveSession = (status: string) => !["done", "failed"].includes( export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number; chats: number }> { const ids = await userProjectIds(db, userId); if (!ids.length) return { questions: 0, waitingRunners: 0, chats: 0 }; - const [q] = await db.select({ n: count() }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))); + // PEP-149: only what waits for the person — questions and finished stories to accept. + const q = { n: (await openMessages(userId)).filter((x) => needsPerson(x, x.taskStatus)).length }; const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input"))); // PEP-106: messages of other people in the projects' discussions the user has not read. const chats = [...(await discussionUnread(db, userId)).values()].reduce((a, b) => a + b, 0); - return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0, chats }; + return { questions: q.n, waitingRunners: r?.n ?? 0, chats }; } /** Latest events of one runner, newest first (runner details panel, PEP-38). */ diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index c9d1bc4e..7d1157da 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -10,6 +10,7 @@ import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, t import { PeppaError } from "./errors.ts"; import { getNotifyPrefs, projectAudience } from "./notifications.ts"; import { notify } from "./notify.ts"; +import { IS_QUESTION } from "./questions.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { projectForUser, userProjectIds, type User } from "./users.ts"; import type { OutboxRow } from "./telegram.ts"; @@ -84,7 +85,7 @@ export async function listChats(db: Db, user: Pick): Promise`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)]) + ? (await db.select({ p: questions.projectId, n: sql`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt), IS_QUESTION)).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)]) : [], ); const masterAt = [...last.values()].reduce((a, b) => (b && (!a || b > a) ? b : a), null); @@ -315,7 +316,7 @@ export async function chatThreads(db: Db, chatId: number, limit = 50): Promise`count(*)`, lastId: sql`max(${chatMessages.id})`, lastAt: sql`max(${chatMessages.createdAt})`, - open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`, + open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL AND ${IS_QUESTION} THEN 1 ELSE 0 END)`, }) .from(chatMessages) .leftJoin(questions, eq(chatMessages.questionId, questions.id)) @@ -367,6 +368,8 @@ const EVENT_TEXT: Record { text: string; important?: boolean; return { text: said[String(to)] ?? tr("• Статус: {to}", { to: statusRu(String(to)) }), important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) }; }, progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }), + // PEP-149: the agent cannot go on (not a product decision) — a record, not a question. + blocker: (p) => ({ text: `⛔ ${tr("Агент не может продолжить: {what}", { what: cut(s(p.what), 1000) })}${s(p.tried) ? `\n${tr("Что уже пробовал: {tried}", { tried: cut(s(p.tried), 500) })}` : ""}`, author: "agent" }), pm_comment: () => null, // handled separately: a person's message // PEP-4: the project's repo moved to another Gitea namespace. repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d32cfffe..efa518ee 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,6 +3,7 @@ export * from "./notify.ts"; export * from "./project-file.ts"; export * from "./projects.ts"; export * from "./tasks.ts"; +export * from "./questions.ts"; export * from "./sessions.ts"; export * from "./rules.ts"; export * from "./settings.ts"; diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts index df268cce..d8c6d448 100644 --- a/packages/core/src/notifications.ts +++ b/packages/core/src/notifications.ts @@ -5,6 +5,7 @@ import { eq, inArray } from "drizzle-orm"; import { getSetting, setSetting } from "./settings.ts"; import { enqueueTelegram, type OutboxRow } from "./telegram.ts"; import type { Question } from "./tasks.ts"; +import { questionType } from "./questions.ts"; import type { User } from "./users.ts"; import { enqueuePush, type PushPayload } from "./webpush.ts"; import { addMasterMessage } from "./chats.ts"; @@ -139,13 +140,14 @@ export function inQuietHours(prefs: Pick, now return from < to ? m >= from && m < to : m >= from || m < to; } -/** Which event a PM question stands for. */ -export function questionEvent(q: Pick, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent { - if (q.kind !== "attention") return q.taskId == null && q.sessionId == null ? "releases" : "questions"; - if (ctx.taskStatus === "review") return "review"; - if (ctx.sessionStatus && ["failed", "rate_limited", "stalled"].includes(ctx.sessionStatus)) return "failures"; - if (q.taskId == null && q.sessionId == null) return "releases"; - return "questions"; +/** Which event a message for the person stands for (PEP-149: by its type). */ +export function questionEvent(q: Pick & Partial>, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent { + const type = questionType(q, ctx.taskStatus); + if (type === "done") return "review"; + const projectLevel = q.taskId == null && q.sessionId == null; + if (type === "question") return projectLevel ? "releases" : "questions"; + // A message of the factory itself: about the product as a whole, or about an agent's trouble. + return projectLevel ? "releases" : "failures"; } /** Owner and members of a project (whether or not they paired Telegram). */ diff --git a/packages/core/src/questions.ts b/packages/core/src/questions.ts new file mode 100644 index 00000000..8a238191 --- /dev/null +++ b/packages/core/src/questions.ts @@ -0,0 +1,56 @@ +// PEP-149: four kinds of agent messages for the person — question, done, progress, blocker. +// The kind decides the route: only a `question` lands in «Ждут вашего ответа» and comes to +// Telegram as a question; `done` waits for «Принять»; `progress` and a non-product `blocker` +// are events of the story thread («События агентов») and never wake the person. +import { questions } from "@peppa/db"; +import { sql, type SQL } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; + +export const MESSAGE_TYPES = ["question", "done", "progress", "blocker"] as const; +export type MessageType = (typeof MESSAGE_TYPES)[number]; + +type Typed = { kind: string; msgType?: MessageType | null; options?: string[] | null; taskId?: number | null }; + +/** The type a new row gets when the caller names none: anything a person must decide is a question. */ +export function defaultMessageType(q: Pick): MessageType | null { + if (q.kind !== "attention") return "question"; + return q.options?.length ? "question" : null; +} + +/** + * The type of a message: the stored one, else derived (rows before PEP-149 and messages of the + * factory itself). null — a factory message nobody has to answer (a failure, a limit, a release). + */ +export function questionType(q: Typed, taskStatus?: string | null): MessageType | null { + if (q.msgType) return q.msgType; + const d = defaultMessageType(q); + if (d) return d; + return q.taskId != null && taskStatus === "review" ? "done" : null; +} + +/** True for what waits for a person: a question to answer or a finished story to accept. */ +export function needsPerson(q: Typed, taskStatus?: string | null): boolean { + const t = questionType(q, taskStatus); + return t === "question" || t === "done"; +} + +/** SQL twin of `questionType(q) === "question"` (counters of open questions). */ +export const IS_QUESTION: SQL = sql`(${questions.msgType} = 'question' OR (${questions.msgType} IS NULL AND (${questions.kind} != 'attention' OR json_array_length(${questions.options}) > 0)))`; + +export const ASK_MIN_OPTIONS = 2; +export const ASK_MAX_OPTIONS = 4; + +/** + * Checks the answers of an agent's question: 2–4 different options and a default among them. + * Returns the options with the default first. The text of the refusal is for the agent. + */ +export function checkChoices(options: string[] | undefined, def: string | undefined): { options: string[]; defaultOption: string } { + const opts = [...new Set((options ?? []).map((o) => o.trim()).filter(Boolean))]; + if (opts.length < ASK_MIN_OPTIONS || opts.length > ASK_MAX_OPTIONS) { + throw new PeppaError(`Not sent: a question to the owner needs ${ASK_MIN_OPTIONS}–${ASK_MAX_OPTIONS} answer options (got ${opts.length}). The owner answers with one tap — give the possible answers as \`options\` and your recommendation as \`default\`. If there is nothing to choose from, it is not a question: decide yourself, or use report_progress / report_blocker.`); + } + const d = def?.trim(); + if (!d) throw new PeppaError("Not sent: name the `default` — the option you go on with while the owner has not answered (one of `options`)."); + if (!opts.includes(d)) throw new PeppaError(`Not sent: \`default\` must be exactly one of \`options\` (${opts.map((o) => `«${o}»`).join(", ")}).`); + return { options: [d, ...opts.filter((o) => o !== d)], defaultOption: d }; +} diff --git a/packages/core/src/review-card.ts b/packages/core/src/review-card.ts index 42035ad0..94135c67 100644 --- a/packages/core/src/review-card.ts +++ b/packages/core/src/review-card.ts @@ -50,8 +50,10 @@ export async function sendReviewCard(db: Db, ref: TaskRef, text: string, session if (gate?.ok) { await clearReviewHold(db, ref.task.id); // PEP-151: «готово» for the same head commit is one message, however many times it is sent. - const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null }; - return session ? raiseSessionQuestion(db, session, "attention", text, undefined, false, state) : askPm(db, ref, { kind: "attention", text, ...state }); + // PEP-149: it is a `done` message and always carries a link to the result. + const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null, msgType: "done" as const }; + const card = /https?:\/\//.test(text) ? text : `${text}\n\n${m("Посмотреть: {url}", { url: `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/t/${ref.key}` })}`; + return session ? raiseSessionQuestion(db, session, "attention", card, undefined, false, state) : askPm(db, ref, { kind: "attention", text: card, ...state }); } const prev = await getReviewHold(db, ref.task.id); await setReviewHold(db, ref.task.id, { ...prev, text, at: Date.now() }); diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ec796bea..4ca96cca 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -5,6 +5,7 @@ import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { actorColumns } from "./actor.ts"; import type { Question, QuestionKind } from "./tasks.ts"; +import { defaultMessageType, type MessageType } from "./questions.ts"; import { userProjectIds } from "./users.ts"; import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts"; @@ -180,12 +181,12 @@ export async function raiseSessionQuestion( text: string, options?: string[], awaitingHook = false, - o: { topic?: MessageTopic; head?: string | null } = {}, + { msgType, ...o }: { topic?: MessageTopic; head?: string | null; /** PEP-149: default — by kind (core/questions.ts). */ msgType?: MessageType | null } = {}, ): Promise { const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => { const [created] = await db .insert(questions) - .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook }) + .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, msgType: msgType ?? defaultMessageType({ kind, options }) }) .returning(); return created!; }); diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index aeba839e..56d9e115 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -15,6 +15,7 @@ import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; import { taskBudgetView, type TaskBudgetView } from "./budgets.ts"; import { productNeeds, type ProductNeedView } from "./product-needs.ts"; import { raiseOnce, type MessageTopic } from "./message-state.ts"; +import { defaultMessageType, type MessageType } from "./questions.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -306,6 +307,10 @@ export interface NewQuestion { topic?: MessageTopic; /** Head commit of the result, when the caller knows it. */ head?: string | null; + /** PEP-149: what the message is for the person; default — by kind (core/questions.ts). */ + msgType?: MessageType | null; + /** PEP-149: the option the agent goes on with meanwhile (one of `options`). */ + defaultOption?: string; } /** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */ @@ -314,7 +319,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => { const [created] = await db .insert(questions) - .values({ projectId: ref.project.id, taskId: ref.task.id, ...q }) + .values({ projectId: ref.project.id, taskId: ref.task.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }) .returning(); return created!; }); @@ -324,8 +329,8 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues } /** A message for the PM about the project as a whole (releases), not about a task. */ -export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise { - const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); +export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[]; msgType?: MessageType | null }): Promise { + const [row] = await db.insert(questions).values({ projectId: project.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }).returning(); await notify(db, { type: "question", questionId: row!.id }); return row!; } @@ -378,6 +383,19 @@ export async function reportProgress(db: Db, ref: TaskRef, text: string, session return row!; } +/** + * PEP-149: the agent cannot go on and it is not a product decision — a `blocker` event in the + * story thread («События агентов»). The owner is not asked; what happens next is Peppa's job. + */ +export async function reportBlocker(db: Db, ref: TaskRef, b: { what: string; tried: string }, sessionId?: number) { + const [row] = await db + .insert(events) + .values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "blocker", payload: { what: b.what, tried: b.tried }, ...actorColumns(sessionId) }) + .returning(); + await notify(db, { type: "progress", eventId: row!.id }); + return row!; +} + function pick(o: T, keys: string[]): Record { return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]])); } diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index adf8164b..666b1fe1 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -377,6 +377,11 @@ export const questions = sqliteTable("questions", { kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(), text: text("text").notNull(), options: text("options", { mode: "json" }).$type(), + // PEP-149: what the message is for the person — decides where it shows up (core/questions.ts). + // null: a message of the factory itself (failures, limits, releases) and rows before PEP-149. + msgType: text("msg_type", { enum: ["question", "done", "progress", "blocker"] }), + // PEP-149: the option the agent goes on with while nobody answered (one of `options`). + defaultOption: text("default_option"), answer: text("answer"), // "system": closed by Peppa itself (session stopped/resumed), not by a person. answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }), diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index 5b632a87..0c8b0fe2 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -4,6 +4,9 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { askPm, + alertAdmins, + checkChoices, + reportBlocker, createTask, giteaForBot, getIncident, @@ -40,6 +43,7 @@ import { import type { Db } from "@peppa/db"; import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner"; import { z } from "zod"; +import { m } from "@peppa/shared/i18n"; import { formatIncident, formatTask } from "./format.ts"; export interface AgentServerOptions { @@ -216,24 +220,31 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer }, ); + // PEP-149: four kinds of messages to the owner — question (here), done (Peppa sends it itself + // after green checks), progress (report_progress), blocker (report_blocker). + const optionsArg = z.array(z.string()).optional().describe("2–4 possible answers, shown to the owner as buttons"); + const defaultArg = z.string().optional().describe("Your recommendation — exactly one of `options`; you go on with it while the owner has not answered"); + tool( "ask_pm", - "Ask the PM a PRODUCT question only — what users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. Put your recommended answer FIRST in options. Don't wait: keep working with your recommendation in this turn; the PM's answer arrives later as a message, and you adjust if it differs.", + "Ask the owner a PRODUCT question — the ONLY kind of message that reaches their «Ждут вашего ответа» and Telegram. What users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. REQUIRED: `options` (2–4 answers as buttons) and `default` (your recommendation, one of the options) — without them the call is refused. Don't wait: keep working with your default in this turn; the owner's answer arrives later as a message, and you adjust if it differs.", { task: taskArg, question: z.string().min(5).describe("One product question in plain words, 1–2 sentences of context, no jargon"), - options: z.array(z.string()).max(6).optional().describe("Answers shown as buttons; your recommendation first"), + options: optionsArg, + default: defaultArg, }, - async ({ task, question, options }) => { + async ({ task, question, options, default: def }) => { const ref = await resolve(task); - const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId }); - return `Question #${q.id} sent to the PM. Don't wait for the answer: continue with your recommended option now (note it in design.md); if the PM answers differently, the answer arrives as a message and you adjust.`; + const c = checkChoices(options, def); + const q = await askPm(db, ref, { kind: "question", msgType: "question", text: question, options: c.options, defaultOption: c.defaultOption, sessionId }); + return `Question #${q.id} sent to the owner. Don't wait for the answer: continue with «${c.defaultOption}» now (note it in design.md); if the owner answers differently, the answer arrives as a message and you adjust.`; }, ); tool( "report_progress", - "Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).", + "Log a short progress note on a story. It is a `progress` message: it goes to the story thread in «События агентов» and never wakes the owner (not in «Ждут вашего ответа», not in Telegram). Don't use it to ask for anything.", { task: taskArg, text: z.string().min(3) }, async ({ task, text }) => { const ref = await resolve(task); @@ -242,6 +253,31 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer }, ); + tool( + "report_blocker", + "Say that you cannot go on with the story: what stops you and what you already tried. Use it only after trying another approach or a mock. A PRODUCT blocker (only the owner can decide or give something: `product: true`) goes to the owner as a question — `options` (2–4) and `default` are required. Any other blocker (access, a broken service, CI, git, a limit) is recorded in the story thread and does NOT go to the owner: Peppa's administrators see it. After the call end your turn — Peppa wakes you when there is something to do.", + { + task: taskArg, + what: z.string().min(5).describe("What stops you, in plain words"), + tried: z.string().min(3).describe("What you already tried"), + product: z.boolean().optional().describe("true: only the owner can unblock it (a product decision, an account or a key only they have)"), + options: optionsArg, + default: defaultArg, + }, + async ({ task, what, tried, product, options, default: def }) => { + const ref = await resolve(task); + if (product) { + const c = checkChoices(options, def); + const q = await askPm(db, ref, { kind: "question", msgType: "question", text: what, options: c.options, defaultOption: c.defaultOption, sessionId }); + return `Blocker sent to the owner as question #${q.id}. End your turn — the answer arrives as a message.`; + } + const e = await reportBlocker(db, ref, { what, tried }, sessionId); + // Not the owner's business: the administrators of the factory hear about it. + await alertAdmins(db, `blocker:${e.id}`, `⛔ ${ref.key}: ${m("Агент не может продолжить: {what}", { what })}\n${m("Что уже пробовал: {tried}", { tried })}`, () => {}).catch(() => 0); + return `Blocker recorded on ${ref.key} (the owner is not asked about it). End your turn now; Peppa wakes you when there is something to do.`; + }, + ); + tool( "list_incidents", "List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.", diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 368b5e01..e606617d 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -46,6 +46,7 @@ import { setTaskAgentSettings, type AgentSettings, type AgentSettingsPatch, + needsPerson, } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, loadEnv } from "@peppa/shared"; @@ -511,11 +512,13 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ .leftJoin(tasks, eq(questions.taskId, tasks.id)) .where(and(inArray(projects.id, ids), isNull(questions.answeredAt))) .orderBy(asc(questions.id)); - if (!rows.length) return "Inbox is empty — agents need nothing from you."; - return rows + // PEP-149: only questions and stories waiting for «accept»; factory messages are not the inbox. + const waiting = rows.filter(({ q, status }) => needsPerson(q, status)); + if (!waiting.length) return "Inbox is empty — agents need nothing from you."; + return waiting .map(({ q, key, number, status }) => { const kind = q.kind === "attention" && status === "review" ? "ready for review (answer 'accept' or a comment)" : q.kind; - return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}`; + return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}${q.defaultOption ? `\n default (the agent goes on with it meanwhile): ${q.defaultOption}` : ""}`; }) .join("\n"); }); diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 422fc5f2..7e65b509 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -4,6 +4,9 @@ import { m } from "@peppa/shared/i18n"; import { askPm, + getSetting, + setSetting, + pendingReview, giteaForBot, listSessions, listTasks, @@ -41,6 +44,31 @@ async function activeSessionId(db: Db, taskId: number): Promise { return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null; } +const wokeKey = (taskId: number) => `ci.woke:${taskId}`; + +/** + * PEP-149: an agent that ended its turn waiting for the checks is woken by Peppa, not by the + * person: every check of the PR head passed and the story is still in work → one message per + * commit. Returns true when the agent was told. + */ +export async function wakeOnGreen(db: Db, ref: TaskRef, r: Pick, gitea: GiteaClient = giteaForBot()): Promise { + if (!["proposing", "in_progress"].includes(ref.task.status)) return false; + const [s] = await listSessions(db, { active: true, taskId: ref.task.id }); + if (!s || (s.status !== "idle" && s.status !== "waiting_input")) return false; + if ((await getSetting(db, wokeKey(ref.task.id))) === r.sha) return false; + if (await pendingReview(db, ref.task.id)) return false; + const { giteaOwner: o, giteaRepo: repo } = ref.project; + const n = taskPrNumber(ref.project, ref.task.prUrl) ?? r.prNumber ?? (r.branch ? (await gitea.openPullForBranch(o, repo, r.branch))?.number : null); + if (!n) return false; + const gate = await prGate({ ...ref, task: { ...ref.task, prUrl: `/${o}/${repo}/pulls/${n}` } }, gitea); + // Only the commit the PR stands on now; a branch behind the base is updated by Peppa itself. + if (!(gate.ok || gate.behind) || !gate.summary || gate.pull?.head.sha !== r.sha) return false; + await setSetting(db, wokeKey(ref.task.id), r.sha); + await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s.id, type: "checks_passed_wake", payload: { sha: r.sha, pr: n } }); + await sendToSession(db, s.id, `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}). Если работа закончена — update_task(status: review${ref.task.prUrl ? "" : ", pr_url"}); если нет — продолжай.`); + return true; +} + export interface CheckOutcome { task: string | null; /** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */ @@ -56,6 +84,7 @@ export async function recordCheck(db: Db, project: Project, r: CheckReport): Pro if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" }; if (r.state === "success") { + await wakeOnGreen(db, ref, r).catch(() => {}); const [red] = await db .select({ id: checkRuns.id }) .from(checkRuns) diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index c355aaa6..08594939 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -31,6 +31,9 @@ import { demoNote, reviewRejections, getSession, + getProject, + needsPerson, + reportProgress, logSessionEvent, peppaInputSentAt, pendingSessionQuestions, @@ -186,13 +189,13 @@ async function askQuestion(db: Db, s: SessionView, input: HookInput) { } const NUDGE = (key: string) => - `Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда стори готова — PR и update_task(status: review).`; + `Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Когда стори готова — PR и update_task(status: review). Ждёшь проверок, ревьюера или мержа — просто закончи ход: Пеппа разбудит тебя сама, PM об этом писать не нужно. Не можешь продолжать — report_blocker (что мешает, что пробовал) и закончи ход.`; /** * The agent finished a turn. Pending question → PM already has it. Task in review → * "ready for review" (accept / comment). Task still in work → ask the agent to keep going * (Claude only, via the Stop hook's block decision), at most MAX_AUTO_NUDGES in a row. - * Otherwise the PM gets "the session is waiting for you". + * Otherwise (PEP-149) the last reply becomes a `progress` record — the person is not woken. * Returns the Stop-hook output to print, if any. */ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise { @@ -209,7 +212,8 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); return null; } - if ((await pendingSessionQuestions(db, s.id)).length > 0) { + // PEP-149: only what a person must answer holds the agent; a factory message does not. + if ((await pendingSessionQuestions(db, s.id)).some((q) => needsPerson(q, s.taskStatus))) { await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } @@ -262,9 +266,11 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 }); return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") }; } - // PEP-151: the agent retells the same state in new words — one message, not one per turn. - await raiseSessionQuestion(db, s, "attention", clip(text ?? m("Агент закончил ход и ждёт вашего ответа.")), undefined, false, { topic: "turn" }); - await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); + // PEP-149: the end of a turn is progress, not a question — a record in the story thread + // («События агентов»); nobody is woken. Peppa wakes the agent when there is something to do + // (checks passed or failed, the reviewer, a rebase, a comment of the person). + if (text && task) await reportProgress(db, { project: await getProject(db, s.projectKey), task, key: s.taskKey ?? "" }, clip(text), s.id); + await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); return null; } diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 61a699a8..9236ff86 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -282,7 +282,9 @@ export async function idleStopTick(db: Db, o: { now: Date; cfg: WatchdogSettings if (o.cfg.idleStopHours <= 0) return 0; let stopped = 0; for (const s of await listSessions(db, { active: true })) { - if (s.status !== "waiting_input" || !s.taskId || !s.lastActivityAt) continue; + // PEP-149: an agent that ended its turn without a question is `idle` while its story is in work. + const turnOver = s.status === "waiting_input" || (s.status === "idle" && ["proposing", "in_progress"].includes(s.taskStatus ?? "")); + if (!turnOver || !s.taskId || !s.lastActivityAt) continue; const idleMs = o.now.getTime() - s.lastActivityAt.getTime(); if (idleMs < o.cfg.idleStopHours * 3600_000) continue; if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) continue; From 4c0a08bef27e830e7dfdd3bea796e9d085cefcfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:29:29 +0500 Subject: [PATCH 03/11] PEP-149: translations, help, agent rules, scenario tests Co-Authored-By: Claude Fable 5.2 --- apps/bot/package.json | 2 +- apps/bot/src/bot.ts | 3 +- apps/web/app/(app)/help/page.tsx | 7 + packages/core/src/help-texts.ts | 29 ++ packages/shared/src/i18n/en/bot.ts | 1 - packages/shared/src/i18n/en/help.ts | 1 + packages/shared/src/i18n/en/project.ts | 1 - packages/shared/src/i18n/en/story.ts | 5 + packages/shared/src/i18n/kk/bot.ts | 1 - packages/shared/src/i18n/kk/help.ts | 1 + packages/shared/src/i18n/kk/project.ts | 1 - packages/shared/src/i18n/kk/story.ts | 5 + packages/testkit/test/agent-messages.test.ts | 301 +++++++++++++++++++ packages/testkit/test/product-help.test.ts | 2 +- template/RULES.md | 30 +- 15 files changed, 378 insertions(+), 12 deletions(-) create mode 100644 packages/testkit/test/agent-messages.test.ts diff --git a/apps/bot/package.json b/apps/bot/package.json index 5e87285a..1313b8b1 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "type": "module", - "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, + "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" }, "bin": { "peppa-bot": "./bin/peppa-bot" }, "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 851119d2..7ea26041 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -937,7 +937,8 @@ export function createBot(o: BotOptions) { } else if (kind === "q") { const q = await getQuestion(db, id).catch(() => null); const text = q && choice ? choiceToAnswer(q, choice) : null; - toast = q && text ? await answer(q, text) : tr("Вопрос не найден"); + // PEP-149: the «continue» button of an earlier message answers nothing. + toast = q && text ? await answer(q, text) : q && choice === "cont" ? tr("Кнопка устарела — ответьте на сообщение текстом.") : tr("Вопрос не найден"); } else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) { // Decision on a new production error (PEP-58). try { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index e20b4de6..e8dc3b2b 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -102,6 +102,12 @@ async function ProductHelp() {

{t.question}

{t.product}

+
+

{t.messages.title}

+
    + {t.messages.items.map((x) =>
  • {x}
  • )} +
+

{t.problem}{" "} {tr("Ваши обращения")} @@ -149,6 +155,7 @@ export default async function Help() {

  • {rich(t("Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать."))}
  • {rich(t("Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь."))}
  • {rich(t("Изоляция и хосты — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Peppa FACTORY и чужих проектов; хуки, MCP и git идут в Peppa FACTORY через релей и только к репозиторию проекта (PR агент открывает инструментом open_pull_request). «Где запускать раннеры» — Mac Peppa FACTORY или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Peppa FACTORY на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими."))}
  • +
  • {rich(t("Сообщения агента — четырёх типов. Вопрос — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. Готово — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. Ход работы — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. Блокер — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY."))}
  • {rich(t("Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты."))}
  • diff --git a/packages/core/src/help-texts.ts b/packages/core/src/help-texts.ts index 40c18d20..1bb3da1e 100644 --- a/packages/core/src/help-texts.ts +++ b/packages/core/src/help-texts.ts @@ -18,6 +18,8 @@ export interface ProductHelpText { problem: string; /** PEP-145: where the product is. */ product: string; + /** PEP-149: the four kinds of messages an agent sends. */ + messages: { title: string; items: [string, string, string, string] }; more: string; moreLink: string; } @@ -62,6 +64,15 @@ export const PRODUCT_HELP: Record = { question: "Агент задал вопрос? Он появится на Главной и в Telegram. Ответьте кнопкой или своими словами — агент продолжит работу.", problem: "Что-то не работает в самой Peppa FACTORY? Нажмите «Сообщить о проблеме» внизу любой страницы: напишите, что случилось, и приложите скриншот. В Telegram то же самое — отправьте боту /problem. Что стало с обращением, видно в разделе «Обращения».", product: "Где посмотреть продукт? На странице проекта и на Главной есть кнопка «Открыть продукт». Ссылка появляется сама, в первый же день проекта; если её пока нет, на её месте написано, что происходит, — делать ничего не нужно.", + messages: { + title: "Какие сообщения присылает агент", + items: [ + "Вопрос — нужно ваше решение. У него всегда есть кнопки с вариантами ответа; один из них агент выберет сам, если вы не ответите.", + "Готово — задачу можно посмотреть и принять. Приходит только когда проверки прошли, вместе со ссылкой на результат.", + "Ход работы — что агент уже сделал. Это лежит в «Событиях агентов» в чате проекта; отвечать не нужно, уведомлений не будет.", + "Агент не может продолжить — если дело в вашем продукте, он задаст вопрос с вариантами. С остальным Peppa FACTORY разбирается сама.", + ], + }, more: "Хотите видеть всё, что делают агенты, и полный справочник? Включите вид «Инженер».", moreLink: "Открыть Настройки", }, @@ -101,6 +112,15 @@ export const PRODUCT_HELP: Record = { question: "Агент сұрақ қойды ма? Ол Басты бетте және Telegram-да пайда болады. Батырмамен немесе өз сөзіңізбен жауап беріңіз — агент жұмысын жалғастырады.", problem: "Peppa FACTORY-дің өзінде бірдеңе жұмыс істемей тұр ма? Кез келген беттің төменгі жағындағы «Мәселе туралы хабарлау» батырмасын басыңыз: не болғанын жазып, скриншот тіркеңіз. Telegram-да да солай — ботқа /problem жіберіңіз. Өтінішіңіздің не болғаны «Өтініштер» бөлімінде көрінеді.", product: "Өнімді қайдан көруге болады? Жоба бетінде және Басты бетте «Өнімді ашу» батырмасы бар. Сілтеме жобаның бірінші күнінде-ақ өзі пайда болады; әзірге жоқ болса, оның орнында не болып жатқаны жазылған — ештеңе істеудің қажеті жоқ.", + messages: { + title: "Агент қандай хабарламалар жібереді", + items: [ + "Сұрақ — сіздің шешіміңіз керек. Оның әрқашан жауап нұсқалары бар батырмалары болады; жауап бермесеңіз, агент біреуін өзі таңдайды.", + "Дайын — тапсырманы қарап, қабылдауға болады. Тек тексерулер өткенде, нәтижеге сілтемемен бірге келеді.", + "Жұмыс барысы — агент не істеп үлгергені. Бұл жоба чатындағы «Агенттер оқиғаларында» тұрады; жауап берудің қажеті жоқ, хабарландыру келмейді.", + "Агент жалғастыра алмайды — мәселе сіздің өніміңізде болса, ол нұсқалары бар сұрақ қояды. Қалғанын Peppa FACTORY өзі шешеді.", + ], + }, more: "Агенттердің барлық іс-әрекетін және толық анықтамалықты көргіңіз келе ме? «Инженер» көрінісін қосыңыз.", moreLink: "Баптауларды ашу", }, @@ -140,6 +160,15 @@ export const PRODUCT_HELP: Record = { question: "Did an agent ask a question? It appears on Home and in Telegram. Answer with a button or in your own words — the agent carries on.", problem: "Is something not working in Peppa FACTORY itself? Press “Report a problem” at the bottom of any page: write what happened and attach a screenshot. In Telegram it is the same — send /problem to the bot. What became of your report is shown in “Reports”.", product: "Where is the product? The project page and Home have an «Open product» button. The link appears by itself on the project's first day; if it is not there yet, the same place says what is happening — you don't need to do anything.", + messages: { + title: "What messages an agent sends", + items: [ + "Question — your decision is needed. It always has buttons with answers; the agent picks one of them itself if you don't reply.", + "Done — the task can be looked at and accepted. It comes only when the checks have passed, with a link to the result.", + "Progress — what the agent has done so far. It stays in “Agent events” in the project chat; no reply is needed and no notification comes.", + "The agent cannot go on — if it is about your product, it asks a question with options. Peppa FACTORY sorts out the rest itself.", + ], + }, more: "Want to see everything the agents do and the full reference? Turn on the “Engineer” view.", moreLink: "Open Settings", }, diff --git a/packages/shared/src/i18n/en/bot.ts b/packages/shared/src/i18n/en/bot.ts index 3e5e6b01..b630e2eb 100644 --- a/packages/shared/src/i18n/en/bot.ts +++ b/packages/shared/src/i18n/en/bot.ts @@ -94,7 +94,6 @@ export const bot: Dict = { "✅ Принять": "✅ Accept", "Есть замечания — ответь на это сообщение, агент доработает.": "Have remarks? Reply to this message and the agent will rework it.", "🔁 Перезапустить": "🔁 Restart", - "▶️ Продолжай": "▶️ Continue", "Или ответь на это сообщение — текст уйдёт в сессию.": "Or reply to this message — the text goes into the session.", "в Telegram": "in Telegram", "в вебе": "on the web", diff --git a/packages/shared/src/i18n/en/help.ts b/packages/shared/src/i18n/en/help.ts index 7a171d70..89abe659 100644 --- a/packages/shared/src/i18n/en/help.ts +++ b/packages/shared/src/i18n/en/help.ts @@ -287,4 +287,5 @@ export const help: Dict = { " — {n} вопроса ниже.": " — {n} questions below.", " — {n} вопросов ниже.": " — {n} questions below.", "Тихо… Агентам от тебя ничего не нужно, мопс спит.": "All quiet… The agents don't need anything from you, the pug is asleep.", + "Сообщения агента — четырёх типов. Вопрос — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. Готово — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. Ход работы — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. Блокер — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY.": "Agent messages come in four types. Question — your product decision is needed: always with answer buttons and a default option; only it lands in “Agent questions” on Home and comes to Telegram as a question. Done — the task can be accepted: it comes only after the checks have passed, with a link to the result. Progress — what the agent did; it stays in “Agent events” in the project chat and wakes nobody. Blocker — the agent cannot go on: if it is about the product, it asks you with answer options; everything else goes to the factory administrators. The “Continue” button is gone: Peppa FACTORY itself wakes an agent that waits for checks.", }; diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts index 496a1da5..91408982 100644 --- a/packages/shared/src/i18n/en/project.ts +++ b/packages/shared/src/i18n/en/project.ts @@ -127,7 +127,6 @@ export const project: Dict = { Разрешить: "Allow", Всегда: "Always", Запретить: "Deny", - Продолжай: "Continue", "Замечание — вернёт на доработку": "Remark — sends it back for rework", "Свой ответ": "Your answer", Ответ: "Answer", diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..0eab6477 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -416,4 +416,9 @@ export const story: Dict = { "ждёт сброса лимита": "waiting for the limit reset", закончил: "finished", "остановился с ошибкой": "stopped with an error", + "Ждут «Принять»": "Waiting for “Accept”", + "Если не ответите, агент продолжит по варианту «{option}».": "If you don't answer, the agent goes on with “{option}”.", + "Агент не может продолжить: {what}": "The agent cannot go on: {what}", + "Что уже пробовал: {tried}": "What it already tried: {tried}", + "Кнопка устарела — ответьте на сообщение текстом.": "This button no longer works — reply to the message with text.", }; diff --git a/packages/shared/src/i18n/kk/bot.ts b/packages/shared/src/i18n/kk/bot.ts index 6b8ca6b1..0bc4ff1f 100644 --- a/packages/shared/src/i18n/kk/bot.ts +++ b/packages/shared/src/i18n/kk/bot.ts @@ -93,7 +93,6 @@ export const bot: Dict = { "✅ Принять": "✅ Қабылдау", "Есть замечания — ответь на это сообщение, агент доработает.": "Ескертулер болса — осы хабарламаға жауап беріңіз, агент жетілдіреді.", "🔁 Перезапустить": "🔁 Қайта іске қосу", - "▶️ Продолжай": "▶️ Жалғастыр", "Или ответь на это сообщение — текст уйдёт в сессию.": "Немесе осы хабарламаға жауап беріңіз — мәтін сессияға кетеді.", "в Telegram": "Telegram-да", "в вебе": "вебте", diff --git a/packages/shared/src/i18n/kk/help.ts b/packages/shared/src/i18n/kk/help.ts index 8ad3592f..85c03c92 100644 --- a/packages/shared/src/i18n/kk/help.ts +++ b/packages/shared/src/i18n/kk/help.ts @@ -235,4 +235,5 @@ export const help: Dict = { " — {n} вопроса ниже.": " — төменде {n} сұрақ.", " — {n} вопросов ниже.": " — төменде {n} сұрақ.", "Тихо… Агентам от тебя ничего не нужно, мопс спит.": "Тыныш… Агенттерге сізден ештеңе керек емес, мопс ұйықтап жатыр.", + "Сообщения агента — четырёх типов. Вопрос — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. Готово — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. Ход работы — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. Блокер — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY.": "Агент хабарламалары төрт түрлі. Сұрақ — өнім туралы сіздің шешіміңіз керек: әрқашан жауап нұсқалары батырмалармен және әдепкі нұсқамен; тек осы түрі Басты беттегі «Агенттердің сұрақтары» бөліміне түседі және Telegram-ға сұрақ ретінде келеді. Дайын — тапсырманы қабылдауға болады: тек тексерулер өткеннен кейін, нәтижеге сілтемемен келеді. Жұмыс барысы — агент не істегені; жоба чатындағы «Агенттер оқиғаларында» тұрады және ешкімді мазаламайды. Кедергі — агент жалғастыра алмайды: мәселе өнімде болса, ол сізден жауап нұсқаларымен сұрайды, қалғаны фабрика әкімшілеріне кетеді. «Жалғастыр» батырмасы енді жоқ: тексерулерді күтіп тұрған агентті Peppa FACTORY өзі оятады.", }; diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts index 4b07da39..97f53c64 100644 --- a/packages/shared/src/i18n/kk/project.ts +++ b/packages/shared/src/i18n/kk/project.ts @@ -98,7 +98,6 @@ export const project: Dict = { "Разрешить": "Рұқсат беру", "Всегда": "Әрқашан", "Запретить": "Тыйым салу", - "Продолжай": "Жалғастырыңыз", "Замечание — вернёт на доработку": "Ескерту — пысықтауға қайтарады", "Свой ответ": "Өз жауабыңыз", "Ответ": "Жауап", diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..a2a6086c 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -381,4 +381,9 @@ export const story: Dict = { "ждёт сброса лимита": "лимит тасталуын күтуде", "закончил": "аяқтады", "остановился с ошибкой": "қатемен тоқтады", + "Ждут «Принять»": "«Қабылдау» күтуде", + "Если не ответите, агент продолжит по варианту «{option}».": "Жауап бермесеңіз, агент «{option}» нұсқасымен жалғастырады.", + "Агент не может продолжить: {what}": "Агент жалғастыра алмайды: {what}", + "Что уже пробовал: {tried}": "Не істеп көрді: {tried}", + "Кнопка устарела — ответьте на сообщение текстом.": "Батырма ескірді — хабарламаға мәтінмен жауап беріңіз.", }; diff --git a/packages/testkit/test/agent-messages.test.ts b/packages/testkit/test/agent-messages.test.ts new file mode 100644 index 00000000..473f241d --- /dev/null +++ b/packages/testkit/test/agent-messages.test.ts @@ -0,0 +1,301 @@ +// PEP-149, spec agent-messages: four kinds of agent messages — question, done, progress, blocker — +// and where each of them goes. mock-claude runners, mock Gitea. +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { chatMessages, events, questions } from "@peppa/db"; +import { and, eq } from "drizzle-orm"; +import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +process.env.PEPPA_WEB_URL = "http://peppa.test"; +const { createAgentServer } = await import("@peppa/mcp/agent"); +const { renderQuestion, choiceToAnswer } = await import("@peppa/bot/render"); + +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-msg-")), "gitea")); +const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; +const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" }; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +type Turns = Parameters[0]["turns"]; + +/** A story with an open PR (task/-1) in mock Gitea; checks are set by the test. */ +async function prTask(turns: Turns) { + const tp = await project({ turns }); + const proj = await core.getProject(db, tp.key); + const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS }); + writeFileSync(join(tp.dir, ".peppa/project.json"), pj); + gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); + gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; + const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" }); + const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); + const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`; + const set = (check: string, state: string) => gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${check}`, state); + const ref = () => core.resolveTask(db, tp.taskKey); + return { tp, proj, sha, prUrl, set, ref }; +} + +async function agent(projectKey: string, sessionId?: number) { + const [a, b] = InMemoryTransport.createLinkedPair(); + await createAgentServer(db, { defaultKey: projectKey, sessionId }).connect(a); + const client = new Client({ name: "mock-agent", version: "0" }); + await client.connect(b); + return async (name: string, args: Record = {}) => { + const r = await client.callTool({ name, arguments: args }); + return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError }; + }; +} + +const projectQuestions = (projectId: number) => db.select().from(questions).where(eq(questions.projectId, projectId)); +const taskEvents = (taskId: number, type: string) => db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, type))); + +describe("Конец хода — это ход работы, а не вопрос", () => { + test("Агент закончил ход, статус задачи тот же", async () => { + const tp = await project({ turns: [[{ say: "Начал." }], [{ say: "Продолжаю." }], [{ say: "Жду проверок" }]] }); + const p = await core.getProject(db, tp.key); + await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" }); + const sid = await tp.start(); + // Two nudges of the Stop hook, then the turn really ends. + await tp.waitStatus(sid, "idle"); + const task = await tp.task(); + assert.equal(task.status, "in_progress"); + + // Nothing for the person: no message at all (the bot sends to Telegram only what is in `questions`). + assert.deepEqual(await projectQuestions(p.id), [], "no question, nothing in «Ждут вашего ответа» or Telegram"); + + // «События агентов»: a record in the story thread. + const progress = await taskEvents(task.id, "progress"); + assert.equal(progress.length, 1); + assert.equal((progress[0]!.payload as { text: string }).text, "Жду проверок"); + await core.syncChats(db); + const chat = await core.ensureProjectChat(db, p.id); + const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`))); + const record = thread.find((m) => m.text.includes("Жду проверок")); + assert.ok(record, "the reply is in the story thread"); + assert.equal(record.kind, "event"); + assert.equal(record.important, false, "not in the master feed"); + assert.equal(record.questionId, null); + await runner.stopSession(db, sid); + }); + + test("У агента есть открытый вопрос", async () => { + const tp = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], default: "Синий" } }, { say: "Спросил." }]] }); + const p = await core.getProject(db, tp.key); + await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" }); + const sid = await tp.start(); + await tp.waitStatus(sid, "waiting_input"); + const qs = await projectQuestions(p.id); + assert.equal(qs.length, 1); + assert.equal(core.questionType(qs[0]!, "in_progress"), "question"); + assert.deepEqual(await taskEvents((await tp.task()).id, "progress"), [], "no progress record on top of the question"); + await runner.stopSession(db, sid); + }); +}); + +describe("Тип сообщения определяет маршрут", () => { + const base = { taskId: 1, sessionId: 1, msgType: null, options: null } as const; + + test("Вопрос попадает в «Ждут вашего ответа»", () => { + assert.equal(core.questionType({ ...base, kind: "question", options: ["Синий", "Зелёный"] }, "in_progress"), "question"); + assert.equal(core.questionType({ ...base, kind: "permission", options: ["allow", "always", "deny"] }), "question"); + assert.equal(core.questionType({ ...base, kind: "attention", options: ["🚀 Выкатить"] }), "question", "a factory message with answers to choose from"); + assert.equal(core.needsPerson({ ...base, kind: "question" }, "in_progress"), true); + assert.equal(core.questionEvent({ ...base, kind: "question" }, { taskStatus: "in_progress" }), "questions"); + }); + + test("Сообщение о сбое не попадает в «Ждут вашего ответа»", () => { + const failure = { ...base, kind: "attention" as const }; + assert.equal(core.questionType(failure, "in_progress"), null); + assert.equal(core.needsPerson(failure, "in_progress"), false); + assert.equal(core.questionEvent(failure, { taskStatus: "in_progress", sessionStatus: "failed" }), "failures"); + // «Готово» — отдельным блоком: ждёт «Принять», но это не вопрос. + assert.equal(core.questionType({ ...failure, msgType: "done" }, "review"), "done"); + assert.equal(core.questionType(failure, "review"), "done", "rows before PEP-149"); + assert.equal(core.needsPerson(failure, "review"), true); + assert.equal(core.questionEvent(failure, { taskStatus: "review" }), "review"); + }); + + test("Счётчик открытых вопросов чата считает только вопросы", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + const ref = await core.resolveTask(db, tp.taskKey); + await core.askPm(db, ref, { kind: "attention", text: "агент остановился с ошибкой" }); + await core.askPm(db, ref, { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], defaultOption: "Синий" }); + const u = await core.upsertUserFromGitea(db, { id: 9149, login: "mock-pm-149" }, { access_token: "a" }); + await core.setProjectOwner(db, p.id, u.id); + const chat = (await core.listChats(db, u)).find((c) => c.projectId === p.id)!; + assert.equal(chat.open, 1); + }); +}); + +describe("«Готово» шлёт платформа после проверок", () => { + test("Проверки ещё идут", async () => { + const t = await prTask([]); + t.set("typecheck", "success"); + t.set("test", "pending"); + await core.updateTask(db, await t.ref(), { prUrl: t.prUrl }); + const sent = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"); + assert.equal(sent, null, "held"); + assert.deepEqual(await projectQuestions(t.proj.id), [], "the owner got nothing"); + assert.ok(await core.getReviewHold(db, (await t.ref()).task.id)); + + // Red checks: still nothing. + t.set("test", "failure"); + assert.equal(await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"), null); + assert.deepEqual(await projectQuestions(t.proj.id), []); + }); + + test("Проверки прошли", async () => { + const t = await prTask([]); + t.set("typecheck", "success"); + t.set("test", "success"); + await core.updateTask(db, await t.ref(), { status: "review", prUrl: t.prUrl }); + const sent = await core.sendReviewCard(db, await t.ref(), `✅ Задача ${t.tp.taskKey} готова к ревью · Результат: ${t.prUrl}`); + assert.ok(sent); + assert.equal(sent.msgType, "done"); + assert.ok(sent.text.includes(t.prUrl), "the link to the result"); + assert.equal(core.questionType(sent, "review"), "done"); + + // A card without any link gets the link to the task page. + const bare = await core.sendReviewCard(db, await t.ref(), "✅ Готово"); + assert.match(bare!.text, new RegExp(`http://peppa\\.test/t/${t.tp.taskKey}`)); + }); +}); + +describe("Платформа будит агента, когда проверки прошли", () => { + test("Проверки прошли, агент ждал; повторный отчёт о том же коммите", async () => { + const t = await prTask([[{ say: "PR открыт." }], [{ say: "Жду." }], [{ say: "Жду проверок" }], [{ say: "Перевожу." }], [{ say: "Ок." }], [{ say: "Ок." }]]); + await core.updateTask(db, await t.ref(), { status: "in_progress" }); + t.set("typecheck", "pending"); + t.set("test", "pending"); + const sid = await t.tp.start(); + await t.tp.waitStatus(sid, "idle"); + const woke = () => t.tp.log().filter((e) => e.ev === "prompt" && String(e.prompt).includes("Проверки PR")); + + // One check of two passed: not yet. + t.set("typecheck", "success"); + await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "typecheck", state: "success" }); + assert.equal(woke().length, 0); + + t.set("test", "success"); + await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "test", state: "success" }); + await waitFor("the agent is told the checks passed", async () => woke().length || undefined); + assert.match(String(woke()[0]!.prompt), /прошли/); + assert.deepEqual(await projectQuestions(t.proj.id), [], "the person is not involved"); + + await t.tp.waitStatus(sid, "idle"); + assert.equal(await runner.wakeOnGreen(db, await t.ref(), { sha: t.sha, branch: `task/${t.tp.taskKey}` }), false, "once per commit"); + assert.equal(woke().length, 1); + await runner.stopSession(db, sid); + }); +}); + +describe("Вопрос агента — с вариантами и вариантом по умолчанию", () => { + test("Вопрос с вариантами принят", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + const call = await agent(tp.key); + const r = await call("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", options: ["Нет", "Да"], default: "Да" }); + assert.equal(r.isError, false, r.text); + const [q] = await projectQuestions(p.id); + assert.equal(q!.msgType, "question"); + assert.equal(q!.defaultOption, "Да"); + assert.deepEqual(q!.options, ["Да", "Нет"], "the default goes first"); + }); + + for (const [name, args, why] of [ + ["без вариантов", {}, /2–4 answer options/], + ["один вариант", { options: ["Да"], default: "Да" }, /2–4 answer options/], + ["пять вариантов", { options: ["1", "2", "3", "4", "5"], default: "1" }, /2–4 answer options/], + ["без варианта по умолчанию", { options: ["Да", "Нет"] }, /`default`/], + ["вариант по умолчанию не из списка", { options: ["Да", "Нет"], default: "Может быть" }, /one of `options`/], + ] as const) { + test(`Вопрос без вариантов отклонён: ${name}`, async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + const r = await (await agent(tp.key))("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", ...args }); + assert.equal(r.isError, true); + assert.match(r.text, why); + assert.deepEqual(await projectQuestions(p.id), [], "no question"); + }); + } +}); + +describe("Блокер идёт по своему маршруту", () => { + test("Непродуктовый блокер", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + const r = await (await agent(tp.key))("report_blocker", { task: tp.taskKey, what: "нет доступа к серверу сборки", tried: "повторил три раза" }); + assert.equal(r.isError, false, r.text); + assert.deepEqual(await projectQuestions(p.id), [], "the owner is not asked"); + const task = await tp.task(); + assert.equal((await taskEvents(task.id, "blocker")).length, 1); + await core.syncChats(db); + const chat = await core.ensureProjectChat(db, p.id); + const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`))); + const record = thread.find((m) => m.text.includes("нет доступа к серверу сборки")); + assert.ok(record); + assert.equal(record.important, false); + assert.match(record.text, /повторил три раза/); + }); + + test("Продуктовый блокер без вариантов; с вариантами — вопрос", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + const call = await agent(tp.key); + const refused = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true }); + assert.equal(refused.isError, true); + assert.match(refused.text, /2–4 answer options/); + assert.deepEqual(await projectQuestions(p.id), []); + + const ok = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true, options: ["Оставить демо", "Дам аккаунт"], default: "Оставить демо" }); + assert.equal(ok.isError, false, ok.text); + const [q] = await projectQuestions(p.id); + assert.equal(core.questionType(q!), "question"); + assert.equal(q!.defaultOption, "Оставить демо"); + }); +}); + +describe("Нет кнопки «Продолжай»", () => { + const q = (over: Record) => ({ id: 7, projectId: 1, taskId: 1, sessionId: null, kind: "attention", text: "агент остановился с ошибкой", options: null, msgType: null, defaultOption: null, answer: null, answeredVia: null, telegramMessageId: null, awaitingHook: false, reminders: 0, createdAt: new Date(), answeredAt: null, ...over }) as never; + const ctx = { taskKey: "PEP-1", taskTitle: "t", taskStatus: "in_progress", session: null, webUrl: "http://peppa.test" }; + + test("Сообщение фабрики в Telegram", () => { + const r = renderQuestion(q({}), ctx); + assert.deepEqual(r.buttons, [], "no buttons at all"); + assert.doesNotMatch(r.text, /Продолжай/); + }); + + test("Вопрос — кнопки вариантов и вариант по умолчанию", () => { + const r = renderQuestion(q({ kind: "question", text: "Какой цвет?", options: ["Синий", "Зелёный"], msgType: "question", defaultOption: "Синий" }), ctx); + assert.deepEqual(r.buttons.flat().map((b) => b.text), ["Синий", "Зелёный"]); + assert.match(r.text, /продолжит по варианту «Синий»/); + assert.match(r.text, /своим текстом/); + }); + + test("Старая кнопка «Продолжай»", () => { + assert.equal(choiceToAnswer(q({}), "cont"), null, "nothing goes to the agent"); + }); + + test("В вебе и боте кнопки нет", () => { + const root = join(import.meta.dirname, "../../.."); + for (const f of ["apps/web/components/cards.tsx", "apps/bot/src/render.ts"]) { + assert.doesNotMatch(readFileSync(join(root, f), "utf8").replace(/\/\/.*|\{\/\*.*?\*\/\}/g, ""), /Продолжай|"cont"/, f); + } + }); +}); diff --git a/packages/testkit/test/product-help.test.ts b/packages/testkit/test/product-help.test.ts index d5f121c4..b113bd50 100644 --- a/packages/testkit/test/product-help.test.ts +++ b/packages/testkit/test/product-help.test.ts @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs"; import { describe, test } from "node:test"; import { HELP_LANGS, PRODUCT_HELP, type ProductHelpText } from "@peppa/core"; -const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])]; +const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.messages.title, ...t.messages.items, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])]; /** «Нельзя» column of docs/glossary.md. */ function forbidden(): string[] { diff --git a/template/RULES.md b/template/RULES.md index 3736d5a1..e7468854 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -56,7 +56,8 @@ git, тесты, раннеры — решаешь ты сам и пишешь, выполнения и коммить маленькими шагами: `PEP-42: <что сделано>`. - `peppa.report_progress` на каждые 2–3 пункта или раз в ~30 минут. - Не заканчивай ход посреди работы: если остановишься без вопроса PM, Пеппа попросит - продолжить, а на третий раз позовёт PM. + продолжить; на третий раз твоя реплика уйдёт в ход работы, а PM никто не позовёт + (см. «Сообщения PM: четыре типа»). - Тесты и линтеры проекта должны проходить до PR. ### Завершение @@ -226,13 +227,32 @@ git, тесты, раннеры — решаешь ты сам и пишешь, платёжный сервис подключить), доступ, который есть только у PM (аккаунт, ключ сервиса). - Нельзя: всё техническое — стек, библиотеки, архитектура, данные, CI и проверки, git, раннеры, разрешения, «как лучше сделать». Это решаешь ты. -- `peppa.ask_pm`: один вопрос, 1–2 предложения контекста, твой рекомендуемый вариант — - первым в `options`. **Не жди ответа и не заканчивай ход**: продолжай по своему - варианту и запиши его в `design.md`. Ответ придёт позже сообщением — если он другой, - переделаешь. +- `peppa.ask_pm`: один вопрос, 1–2 предложения контекста, **обязательно** `options` + (2–4 варианта ответа — PM отвечает одной кнопкой) и `default` (твой рекомендуемый + вариант, один из `options`); без них вызов отклоняется. **Не жди ответа и не заканчивай + ход**: продолжай по `default` и запиши его в `design.md`. Ответ придёт позже + сообщением — если он другой, переделаешь. - Нужен ключ или аккаунт, которого нет, — делай на моке (раздел ниже) и объяви его через `peppa.declare_needs`: владелец получит список «что дать и куда вставить». +## Сообщения PM: четыре типа + +Всё, что ты сообщаешь PM, — одного из четырёх типов. От типа зависит, увидит ли он это. + +| Тип | Что это | Как отправить | Куда попадает | +|---|---|---|---| +| **question** | нужно решение PM о продукте | `ask_pm` с `options` (2–4) и `default` | «Ждут вашего ответа», Telegram — единственный тип, который будит PM | +| **done** | стори готова, можно принять | сам не шлёшь: `update_task(status: review)`, сообщение отправит Пеппа после зелёных проверок, со ссылкой на результат | «Ждут „Принять“», Telegram | +| **progress** | ход работы | `report_progress`; последняя реплика твоего хода тоже становится progress | «События агентов» (тред стори); PM не будит | +| **blocker** | не можешь продолжать | `report_blocker` (что мешает, что уже пробовал) | продуктовый (`product: true` + `options` и `default`) — PM как question; остальное — в тред стори и администраторам Пеппы, не PM | + +- Последняя реплика хода — не способ что-то спросить: PM её не получит. Нужен ответ — `ask_pm`. +- Ждёшь проверок, ревьюера или мержа — просто закончи ход. Пеппа разбудит тебя сама: красные + проверки придут с логом, зелёные — сообщением «проверки прошли», замечания — текстом. + Писать PM «жду проверок» не нужно и некуда. +- Кнопки «Продолжай» у PM нет: никто не подтолкнёт тебя вручную. Не можешь двигаться — + сначала смени подход или сделай мок, потом `report_blocker`. + ## Если MCP `peppa` недоступен Работай напрямую через OpenSpec CLI (`openspec list`, `openspec show `, From ceef0d7e2f9a001b96417b222e9edec81d98c80d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:30:40 +0500 Subject: [PATCH 04/11] PEP-149: story page shows only questions; AGENTS.md Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 1 + apps/web/app/(app)/t/[key]/page.tsx | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 577e31f0..3f1dcd15 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,6 +43,7 @@ - **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики» - **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок) - **Слова по режиму (PEP-123)**: `@peppa/shared/wording` — `wording(mode)`: `task(форма)` / `Task` / `tasks(n)` («задача» в «Продакте», «стори» в «Инженере»), `runner(форма)` («агент» / «раннер»), формы `nom|gen|dat|acc|ins|pre|pl|genPl|datPl|accPl|insPl|prePl`. Веб: серверный компонент — `const w = await words()` (`lib/auth.ts`), клиентский — `useWords()` (`components/Words.tsx`, `WordsProvider` в раскладке). Что читает только инженер (репозиторий, раннеры, модель, секреты, бюджет, ревьюер в «Настройках проекта», команда терминала, адрес кода, подробная автономность) — под `w.engineer`. Тексты без читателя (события чатов `EVENT_TEXT`, вопросы и сообщения PM из runner, Telegram, push, подписи из core) — всегда словами «Продакта»: «задача», «агент», «Peppa FACTORY», «вы», «Результат:» вместо «PR:». Промпты агентам, MCP и CLI — прежние слова. Страница задачи, полоса лимитов и «Помощь» — PEP-120/121/122. Тест `wording.test.ts` +- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0019; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts` - **Комментарий уточняет постановку (PEP-115)**: `pm_comment` к стори в бэклоге без живого агента → `storyRefineTick` в тике вачдога (`runner/story-refine.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`/`_MODEL`), промпт `refinePrompt` (core/story-refine.ts: контекст `intakeContext`, текущая постановка, обсуждение, новые комментарии), ответ — JSON аналитика (`parseAnalystNote`) → описание через `intakeDescription` («Исходный запрос» сохраняется, `originalRequest`) + заметка аналитика `intake_note` в «Обсуждении» стори. Курсор `refine.task:`, комментарии старше `PEPPA_STORY_REFINE_MAX_AGE_MIN` (60) не трогаются, сбой — одна заметка без повторов, стори взяли в работу до ответа — описание не меняется, роли PEP-84 не закончили — ждёт; `PEPPA_STORY_REFINE=off`. `refinePending` — «Аналитик уточняет постановку…» и исключение из `readyBacklog`. Подпись поля — `apps/web/lib/comment-hint.ts`. Мок — роль `refine` в `mock-intake` (`slowMs`); тест `story-refine.test.ts` - **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок) - **Страница задачи в режиме «Продакт» (PEP-120)**: `t/[key]/page.tsx` при `uiMode()` = product рисует `components/StoryProduct.tsx` — карточку из `storyProductView` (core/story-product.ts, чистая функция; все тексты — `STORY_PRODUCT_TEXT`; `plainStep` не показывает пункт tasks.md с путями, файлами и идентификаторами): что сейчас, «Шаг N из M», «Посмотреть» (`reviewPreview().previewUrl`), что нужно от вас, что дальше, открытые вопросы (`QuestionCard plain`: команда разрешения — под «Подробнее»), «Принять» (`acceptStoryAction`) и «Поправить» (`fixStoryAction` → `fixStory` в runner/flow.ts: только из ревью, комментарий + закрыть «готово к ревью» + `moveTask in_progress` + замечание агенту). Прежнее содержимое страницы и блоки правой панели — под ссылкой «Подробнее» (`?more=1`, также `?tab=`/`?edit=`; закрыто — терминал не монтируется), без правой панели и значка статуса. «Инженер» — без изменений. Тест `story-product.test.ts` diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index b75d6fce..53320906 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -42,6 +42,7 @@ import { taskCiSummary, type GateResult, productUrls, + questionType, } from "@peppa/core"; import { checkRuns } from "@peppa/db"; import { desc, eq } from "drizzle-orm"; @@ -236,7 +237,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom ); // What a product manager reads first: open questions (the «готово к ревью» message is the card's own buttons). - const productQuestions = questions.filter((q) => !q.answeredAt && !(q.kind === "attention" && task.status === "review")).reverse(); + // PEP-149: only messages of type `question`; failures and other factory messages stay under «Подробнее». + const productQuestions = questions.filter((q) => !q.answeredAt && questionType(q, task.status) === "question").reverse(); const productView = storyProductView({ status: task.status, archived: !!task.archivedAt, From 11d6bbafdf0fa6bdada54e4e5a141ef5141b3d90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:30:48 +0500 Subject: [PATCH 05/11] PEP-149: project memory Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.peppa/memory.md b/.peppa/memory.md index aedf6b99..cd62bdfa 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -44,3 +44,4 @@ - Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй или `glossary-ignore`; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ). - Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`. Состояние — settings `question.state:`, `chat.repeat:`. В тесте нужен второй вопрос — меняй статус, коммит в check_runs или текст. - Продукт по ссылке (PEP-145): ссылка и её статус — только через `projectProduct` (`fix`/`broken`/`preparing`) и `productUrls`/`productLookLine`; системную стори заводит `productLinkTick` (в тестах выключен в helpers.ts, свой тест делает `delete process.env.PEPPA_PRODUCT_LINK`); «Показывать всем» — `getPublishMode`/`autoPublish` (вернул true — вопрос с кнопкой не слать). Менял `template/` — после мержа `scripts/push-template.sh`. +- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`. Конец хода агента вопроса не создаёт: в тестах жди статус сессии `idle`, а не `waitQuestion(sid, "attention")`. From 0a5eff6485c0aa1a01fbb30f3a52b60cfcd95014 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:33:55 +0500 Subject: [PATCH 06/11] =?UTF-8?q?PEP-149:=20old=20tests=20follow=20the=20n?= =?UTF-8?q?ew=20contract=20(no=20=C2=ABagent=20ended=20its=20turn=C2=BB=20?= =?UTF-8?q?message,=20ask=5Fpm=20with=20options)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../pep-149-agent-message-kinds/tasks.md | 24 +++++++++---------- packages/testkit/test/autonomy.test.ts | 14 +++++------ packages/testkit/test/bot.test.ts | 18 ++++++++------ packages/testkit/test/budgets.test.ts | 2 +- packages/testkit/test/cjm.test.ts | 8 ++++--- packages/testkit/test/limits.test.ts | 4 ++-- packages/testkit/test/oauth.test.ts | 2 +- packages/testkit/test/usage.test.ts | 2 +- 8 files changed, 40 insertions(+), 34 deletions(-) diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/pep-149-agent-message-kinds/tasks.md index e470d634..83ed215d 100644 --- a/openspec/changes/pep-149-agent-message-kinds/tasks.md +++ b/openspec/changes/pep-149-agent-message-kinds/tasks.md @@ -1,22 +1,22 @@ # Tasks: PEP-149 ## 1. Ядро -- [ ] 1.1 Миграция: `questions.msg_type`, `questions.default_option` -- [ ] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion` -- [ ] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна -- [ ] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`) +- [x] 1.1 Миграция: `questions.msg_type`, `questions.default_option` +- [x] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion` +- [x] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна +- [x] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`) ## 2. Агент -- [ ] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle` -- [ ] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит) -- [ ] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress` +- [x] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle` +- [x] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит) +- [x] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress` ## 3. Веб и бот -- [ ] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике) -- [ ] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP -- [ ] 3.3 Переводы en/kk +- [x] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике) +- [x] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP +- [x] 3.3 Переводы en/kk ## 4. Правила, помощь, проверки -- [ ] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа -- [ ] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов +- [x] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа +- [x] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов - [ ] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта diff --git a/packages/testkit/test/autonomy.test.ts b/packages/testkit/test/autonomy.test.ts index 83015627..06330323 100644 --- a/packages/testkit/test/autonomy.test.ts +++ b/packages/testkit/test/autonomy.test.ts @@ -42,17 +42,17 @@ describe("autonomous cycle", () => { assert.equal((await core.getQuestion(db, review.id)).answer, "✅ Принято"); }); - test("after two nudges in a row the PM is called; a human answer resets the counter", async () => { + test("after two nudges in a row the turn ends as progress — the PM is not called (PEP-149); a human message resets the counter", async () => { const p = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "in_progress" } }, { say: "шаг 1" }], [{ say: "шаг 2" }], [{ say: "застрял на шаге 3" }], [{ say: "понял" }]], }); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); - assert.match(q.text, /застрял на шаге 3/); + await p.waitStatus(sid, "idle"); assert.equal(await nudges(sid), runner.MAX_AUTO_NUDGES); - await runner.answerAndDeliver(db, q.id, "делай вариант Б", "telegram"); - assert.equal((await p.session(sid)).autoNudges, 0); - await p.waitLog("answer delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б")); + assert.deepEqual(await p.pending(sid), [], "nobody is asked"); + await runner.sendToSession(db, sid, "делай вариант Б"); + await p.waitLog("message delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б")); + await waitFor("the counter is reset", async () => (await p.session(sid)).autoNudges === 0); await runner.stopSession(db, sid); }); @@ -71,7 +71,7 @@ describe("autonomous cycle", () => { describe("task board", () => { test("moving a card to In progress starts an agent; back to Backlog stops it", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?" } }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?", options: ["Да", "Нет"], default: "Да" } }]] }); let ref = await core.resolveTask(db, p.taskKey); assert.equal(runner.columnOf(ref.task.status), "backlog"); const { started } = await runner.moveTask(db, ref, "in_progress"); diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts index 9d63e985..a9f1e97d 100644 --- a/packages/testkit/test/bot.test.ts +++ b/packages/testkit/test/bot.test.ts @@ -79,7 +79,7 @@ describe("pairing", () => { describe("answering from Telegram", () => { test("question with options: button press reaches the agent, message is closed", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду." }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду." }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -138,7 +138,9 @@ describe("answering from Telegram", () => { test("free-text reply to a 'session is waiting' alert is typed into the session", async () => { const p = await project({ turns: [[{ say: "Сделал черновик. Что дальше?" }], [{ say: "Понял." }]] }); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); + // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert. + const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Сделал черновик. Что дальше?"); const m = await messageFor(q.id); assert.match(m.text, /Что дальше/); tg.userSends(PM, "добавь тесты\nи README", m.message_id); @@ -154,7 +156,7 @@ describe("several users", () => { await waitFor("bob paired", async () => (await core.getUser(db, bobUser.id))?.telegramChatId === BOB.chatId); // PM's project: Bob has no access. - const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"] } }], [{ say: "Ок." }]] }); + const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await mine.start(); const q = await mine.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -198,7 +200,7 @@ describe("review", () => { describe("staleness and reliability", () => { test("answered in the terminal: Telegram message is closed and old buttons do nothing", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -213,7 +215,9 @@ describe("staleness and reliability", () => { test("an update re-delivered after a restart is not replayed", async () => { const p = await project({ turns: [[{ say: "Жду указаний." }], [{ say: "Ок." }], [{ say: "лишний ход" }]] }); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); + // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert. + const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Жду указаний."); const m = await messageFor(q.id); const updateId = tg.userSends(PM, "сделай раз", m.message_id); await p.waitLog("delivered once", isPrompt("сделай раз")); @@ -227,7 +231,7 @@ describe("staleness and reliability", () => { test("outbox retries after 429 (retry_after) and 5xx", async () => { tg.failNext("sendMessage", 429, 1); tg.failNext("sendMessage", 500); - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?" } }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); @@ -259,7 +263,7 @@ describe("staleness and reliability", () => { }); test("tmux killed while waiting: answer is saved, PM told the session is down", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?" } }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?", options: ["Да", "Нет"], default: "Да" } }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); diff --git a/packages/testkit/test/budgets.test.ts b/packages/testkit/test/budgets.test.ts index f77c4a59..3ca60c6c 100644 --- a/packages/testkit/test/budgets.test.ts +++ b/packages/testkit/test/budgets.test.ts @@ -21,7 +21,7 @@ const budgetQuestion = (taskId: number) => async function spentRunner() { const p = await project({ turns: [[{ usage: { input: 1000, output: 500 } }, { say: "Сделал часть." }]] }); const sid = await p.start(); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); await waitFor("usage recorded", async () => core.usageTotals((await core.getSession(db, sid)).usage).total === 1500); return { p, sid, task: await p.task() }; } diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts index 47ba8e10..d996e9ab 100644 --- a/packages/testkit/test/cjm.test.ts +++ b/packages/testkit/test/cjm.test.ts @@ -76,7 +76,7 @@ describe("Claude: task lifecycle", () => { describe("Claude: questions to the PM", () => { test("ask_pm question answered from Telegram is typed into the session", async () => { const p = await project({ - turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]], + turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]], }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); @@ -90,7 +90,9 @@ describe("Claude: questions to the PM", () => { test("multi-line answer arrives as one prompt (bracketed paste)", async () => { const p = await project({ turns: [[{ say: "Что дальше?" }], [{ say: "Понял." }]] }); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); + // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert. + const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Что дальше?"); await runner.answerAndDeliver(db, q.id, "строка один\nстрока два", PM); const e = await p.waitLog("pasted prompt", isPrompt("строка один")); assert.equal(e.prompt, "строка один\nстрока два"); @@ -127,7 +129,7 @@ describe("Claude: questions to the PM", () => { }); test("typing in the terminal answers whatever the session was waiting for", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?" } }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); await runner.sendToSession(db, sid, "назови peppa-api"); diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts index 1d4e23e6..11ebd45c 100644 --- a/packages/testkit/test/limits.test.ts +++ b/packages/testkit/test/limits.test.ts @@ -90,9 +90,9 @@ describe("Защита от зацикливания", () => { test("Предел достигнут", async () => { const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] }); const sid = await p.start(); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); await core.updateSession(db, sid, { limitResumes: runner.MAX_LIMIT_RESUMES_PER_DAY, limitResumesDay: new Date().toLocaleDateString("sv-SE") }); - await runner.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "дальше", "web"); + await runner.sendToSession(db, sid, "дальше"); await p.waitStatus(sid, "rate_limited"); const s = await sess(sid); assert.equal(s.resumeAt, null, "no more auto-resumes today"); diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 70f94d04..61e178a8 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -94,7 +94,7 @@ async function mcpAs(user: typeof owner) { describe("PM tools over MCP", () => { test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => { - const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] }); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] }); const proj = await core.getProject(db, p.key); await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); diff --git a/packages/testkit/test/usage.test.ts b/packages/testkit/test/usage.test.ts index 2c9a4ffe..8bade025 100644 --- a/packages/testkit/test/usage.test.ts +++ b/packages/testkit/test/usage.test.ts @@ -56,7 +56,7 @@ describe("Расход сессии из statusLine и transcript", () => { const p = await project({ turns: [[{ usage: { input: 1200, output: 300, costUsd: 0.42, context: { used: 50000, size: 200000 }, fiveHour: 42, sevenDay: 18 } }, { say: "Готово." }]] }); const sid = await p.start(); await p.waitLog("statusline", (e) => e.ev === "statusline"); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); const s = await core.getSession(db, sid); const t = core.usageTotals(s.usage); assert.equal(t.total, 1500); From 5f738942e0c5cad7230bb894b392dc16626a760e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:48:31 +0500 Subject: [PATCH 07/11] PEP-149: remaining old tests follow the new end-of-turn behaviour Co-Authored-By: Claude Fable 5.2 --- .../changes/pep-149-agent-message-kinds/tasks.md | 2 +- packages/testkit/test/cjm.test.ts | 16 ++++++++-------- packages/testkit/test/claude-live.test.ts | 10 ++++++---- packages/testkit/test/rotation.test.ts | 4 ++-- packages/testkit/test/sandbox-hosts.test.ts | 6 +++--- 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/pep-149-agent-message-kinds/tasks.md index 83ed215d..621df364 100644 --- a/openspec/changes/pep-149-agent-message-kinds/tasks.md +++ b/openspec/changes/pep-149-agent-message-kinds/tasks.md @@ -19,4 +19,4 @@ ## 4. Правила, помощь, проверки - [x] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа - [x] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов -- [ ] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта +- [x] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts index d996e9ab..0baf4e8f 100644 --- a/packages/testkit/test/cjm.test.ts +++ b/packages/testkit/test/cjm.test.ts @@ -244,7 +244,7 @@ describe("Claude: failures and recovery", () => { test("tmux session killed from outside → failed, PM alerted", async () => { const p = await project({ turns: [[{ say: "Работаю." }]] }); const sid = await p.start(); - await p.waitStatus(sid, "waiting_input"); + await p.waitStatus(sid, "idle"); execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]); await tick(); assert.equal((await p.session(sid)).status, "failed"); @@ -258,7 +258,7 @@ describe("Claude: failures and recovery", () => { const cleared = await p.waitLog("cleared", (e) => e.ev === "clear"); await waitFor("new conversation id stored", async () => (await p.session(sid)).conversationId === cleared.newConversationId); assert.notEqual(before, cleared.newConversationId); - await p.waitStatus(sid, "waiting_input"); + await p.waitStatus(sid, "idle"); await runner.stopSession(db, sid); }); @@ -282,14 +282,14 @@ describe("Codex", () => { const mcpCall = await p.waitLog("codex reaches peppa MCP", (e) => e.ev === "mcp" && e.tool === "get_task"); assert.equal(mcpCall.isError, false); - const alert = await p.waitQuestion(sid, "attention"); - assert.match(alert.text, /какой фреймворк/); + // PEP-149: the end of a turn is a progress record, not a question to the PM. + await p.waitStatus(sid, "idle"); + assert.deepEqual(await p.pending(sid), []); const s = await p.session(sid); assert.equal(s.provider, "codex"); - assert.equal(s.status, "waiting_input"); assert.equal(s.conversationId, start.conversationId); - await runner.answerAndDeliver(db, alert.id, "Fastify", PM); + await runner.sendToSession(db, sid, "Fastify"); await p.waitLog("answer typed in", isPrompt("Fastify")); await runner.stopSession(db, sid); }); @@ -309,9 +309,9 @@ describe("Codex", () => { test("crash → resume uses `codex resume `", async () => { const p = await project({ turns: [[{ say: "Первый ход." }], [{ crash: 2 }]], resumeTurns: [[{ say: "Вернулся." }]] }); const sid = await p.start({ provider: "codex" }); - const alert = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); const thread = (await p.session(sid)).conversationId; - await runner.answerAndDeliver(db, alert.id, "продолжай", PM); + await runner.sendToSession(db, sid, "продолжай"); await p.waitLog("crashed", (e) => e.ev === "exit"); await waitFor("failed", async () => { await tick(); diff --git a/packages/testkit/test/claude-live.test.ts b/packages/testkit/test/claude-live.test.ts index 3cfce8a1..96d26177 100644 --- a/packages/testkit/test/claude-live.test.ts +++ b/packages/testkit/test/claude-live.test.ts @@ -9,7 +9,7 @@ import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, describe, test } from "node:test"; import { events } from "@peppa/db"; -import { asc, eq } from "drizzle-orm"; +import { and, asc, eq } from "drizzle-orm"; import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; after(teardown); @@ -177,7 +177,7 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", () await runner.stopSession(db, sid); }); - test("Stop: стори в работе → decision block; после двух — PM", async () => { + test("Stop: стори в работе → decision block; после двух — ход работы, PM не зовём", async () => { const p = await project({ turns: [[{ sleep: 60_000 }]] }); const sid = await p.start(); // The prompt hook resets auto_nudges; let it finish before the Stop hooks are counted. @@ -190,8 +190,10 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", () assert.match(first.reason, new RegExp(p.taskKey)); assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block"); assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null); - const q = await p.waitQuestion(sid, "attention"); - assert.equal(q.text, fixture("stop-after-block").last_assistant_message); + // PEP-149: the last reply becomes a progress record — the PM is not asked. + assert.deepEqual(await p.pending(sid), []); + const [progress] = await db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, "progress"))); + assert.equal((progress!.payload as { text: string }).text, fixture("stop-after-block").last_assistant_message); await runner.stopSession(db, sid); }); }); diff --git a/packages/testkit/test/rotation.test.ts b/packages/testkit/test/rotation.test.ts index 020a0e4a..dd9bf13b 100644 --- a/packages/testkit/test/rotation.test.ts +++ b/packages/testkit/test/rotation.test.ts @@ -166,9 +166,9 @@ describe("Предохранители", () => { const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 3600, credential: "caplimA" } }]] }); await poolFor(p.key, [a.id, b.id]); const sid = await p.start(); - const q = await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); for (let i = 0; i < runner.maxRotationsPerHour(); i++) await core.logSessionEvent(db, await sess(sid), runner.SWITCH_EVENT, { reason: "limit" }); - await runner.answerAndDeliver(db, q.id, "дальше", "web"); + await runner.sendToSession(db, sid, "дальше"); await p.waitStatus(sid, "rate_limited"); assert.equal((await sess(sid)).rotateReason, null); assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/); diff --git a/packages/testkit/test/sandbox-hosts.test.ts b/packages/testkit/test/sandbox-hosts.test.ts index 89c307af..97e55944 100644 --- a/packages/testkit/test/sandbox-hosts.test.ts +++ b/packages/testkit/test/sandbox-hosts.test.ts @@ -142,7 +142,7 @@ describe("PEP-17: агент в контейнере", () => { const p = await project({ turns: [[{ say: "ok" }]] }); const before = runs().length; const sid = await p.start(); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); const s = await core.getSession(db, sid); assert.equal(s.container, null); assert.equal(s.host, null); @@ -193,7 +193,7 @@ describe("PEP-17: агент в контейнере", () => { await new Promise((r) => setTimeout(r, 1200)); // longer than one relay wait await runner.answerAndDeliver(db, q.id, "allow", "web"); await p.waitLog("permission allowed by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "allow"); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); // Stop hook through the relay with the transcript: tokens counted as for a local agent. assert.equal(core.usageTotals((await core.getSession(db, sid)).usage).total, 1500); assert.ok((await evs(sid, "turn_end")).length >= 1); @@ -300,7 +300,7 @@ describe("PEP-40: хосты раннеров", () => { const log = join(remoteWs, ".peppa", "mock-log.jsonl"); await waitFor("mcp from the host", async () => existsSync(log) && readFileSync(log, "utf8").includes('"tool":"report_progress","args":{"task":"')); assert.match(readFileSync(log, "utf8"), /"tool":"report_progress".*"isError":false/); - await p.waitQuestion(sid, "attention"); + await p.waitStatus(sid, "idle"); // PEP-9 over SSH: the frame comes from the host's pane. const frame = await new Promise((resolve, reject) => { From 1353b358b837f9358e3c73360f5a849c89c366f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:48:34 +0500 Subject: [PATCH 08/11] PEP-149: archive the change Co-Authored-By: Claude Fable 5.2 --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/agent-messages/spec.md | 0 .../tasks.md | 0 openspec/specs/agent-messages/spec.md | 104 ++++++++++++++++++ 6 files changed, 104 insertions(+) rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/.openspec.yaml (100%) rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/design.md (100%) rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/proposal.md (100%) rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/specs/agent-messages/spec.md (100%) rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/tasks.md (100%) create mode 100644 openspec/specs/agent-messages/spec.md diff --git a/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/.openspec.yaml similarity index 100% rename from openspec/changes/pep-149-agent-message-kinds/.openspec.yaml rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/.openspec.yaml diff --git a/openspec/changes/pep-149-agent-message-kinds/design.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/design.md similarity index 100% rename from openspec/changes/pep-149-agent-message-kinds/design.md rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/design.md diff --git a/openspec/changes/pep-149-agent-message-kinds/proposal.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/proposal.md similarity index 100% rename from openspec/changes/pep-149-agent-message-kinds/proposal.md rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/proposal.md diff --git a/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/specs/agent-messages/spec.md similarity index 100% rename from openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/specs/agent-messages/spec.md diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/tasks.md similarity index 100% rename from openspec/changes/pep-149-agent-message-kinds/tasks.md rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/tasks.md diff --git a/openspec/specs/agent-messages/spec.md b/openspec/specs/agent-messages/spec.md new file mode 100644 index 00000000..f6555fe7 --- /dev/null +++ b/openspec/specs/agent-messages/spec.md @@ -0,0 +1,104 @@ +# agent-messages Specification + +## Purpose +Сообщения агента пользователю делятся на четыре типа — вопрос, готово, ход работы, блокер; от типа зависит, увидит ли его пользователь в «Ждут вашего ответа», в Telegram или только в «Событиях агентов». + +## Requirements + +### Requirement: Тип сообщения определяет маршрут +Система SHALL присваивать каждому новому сообщению агента пользователю один из типов `question`, `done`, `progress`, `blocker`. В «Ждут вашего ответа» SHALL попадать только `question`; счётчик «ждут вас», напоминания и push SHALL учитывать только `question` и `done`. + +#### Scenario: Вопрос попадает в «Ждут вашего ответа» +- **GIVEN** задача PEP-1 в работе +- **WHEN** агент задаёт вопрос «Какой цвет кнопки?» с вариантами «Синий» и «Зелёный», по умолчанию «Синий» +- **THEN** на Главной в «Ждут вашего ответа» есть этот вопрос с кнопками «Синий» и «Зелёный» и полем «Свой ответ» +- **AND** счётчик «ждут вас» равен 1 + +#### Scenario: Сообщение о сбое не попадает в «Ждут вашего ответа» +- **GIVEN** открытое сообщение фабрики без вариантов ответа «агент остановился с ошибкой» +- **WHEN** пользователь открывает Главную +- **THEN** в «Ждут вашего ответа» этого сообщения нет +- **AND** счётчик «ждут вас» равен 0 + +### Requirement: Конец хода — это ход работы, а не вопрос +Когда агент закончил ход, а статус задачи не изменился и подталкивания исчерпаны, система SHALL записать последнюю реплику агента как `progress` в «События агентов» и SHALL NOT создавать вопрос, отправлять Telegram или push. + +#### Scenario: Агент закончил ход, статус задачи тот же +- **GIVEN** задача PEP-1 в работе, агент уже дважды получил подталкивание +- **WHEN** агент заканчивает ход с текстом «Жду проверок» +- **THEN** в «Ждут вашего ответа» и в Telegram владельца ничего нового нет +- **AND** в «Событиях агентов» проекта, в треде PEP-1, есть запись «Жду проверок» + +#### Scenario: У агента есть открытый вопрос +- **GIVEN** агент задал вопрос с вариантами и не получил ответа +- **WHEN** агент заканчивает ход +- **THEN** новая запись хода работы не создаётся, вопрос остаётся в «Ждут вашего ответа» + +### Requirement: Платформа будит агента, когда проверки прошли +Когда все проверки последнего коммита задачи в работе прошли, а ход агента окончен, система SHALL один раз на коммит сообщить агенту, что задачу можно переводить в ревью. + +#### Scenario: Проверки прошли, агент ждал +- **GIVEN** задача PEP-1 в работе, агент закончил ход, проверки коммита `abc1234` ещё шли +- **WHEN** последняя проверка коммита `abc1234` проходит +- **THEN** агент получает сообщение «проверки прошли» + +#### Scenario: Повторный отчёт о том же коммите +- **GIVEN** агент уже получил сообщение о коммите `abc1234` +- **WHEN** приходит ещё один успешный отчёт по коммиту `abc1234` +- **THEN** второго сообщения агент не получает + +### Requirement: «Готово» шлёт платформа после проверок +Сообщение типа `done` SHALL отправляться только платформой, только когда проверки последнего коммита прошли и нет конфликта, и SHALL содержать ссылку на результат. + +#### Scenario: Проверки прошли +- **GIVEN** задача PEP-1 в ревью, проверки зелёные, результат `https://git.example/pulls/7` +- **WHEN** агент заканчивает ход +- **THEN** владелец получает сообщение «готова к ревью» типа `done` со ссылкой `https://git.example/pulls/7` и кнопкой «Принять» + +#### Scenario: Проверки ещё идут +- **GIVEN** задача PEP-1 в ревью, одна проверка не завершена +- **WHEN** агент заканчивает ход +- **THEN** владелец ничего не получает, пока проверки не пройдут + +### Requirement: Вопрос агента — с вариантами и вариантом по умолчанию +Инструмент `ask_pm` SHALL принимать вопрос только с 2–4 вариантами ответа и вариантом по умолчанию из их числа; иначе SHALL отклонять вызов с объяснением. + +#### Scenario: Вопрос с вариантами принят +- **WHEN** агент вызывает `ask_pm` с вариантами «Да», «Нет» и вариантом по умолчанию «Да» +- **THEN** вопрос отправлен, вариант «Да» показан первым и отмечен как выбранный по умолчанию + +#### Scenario Outline: Вопрос без вариантов отклонён +- **WHEN** агент вызывает `ask_pm` с вариантами <варианты> и вариантом по умолчанию <по умолчанию> +- **THEN** вызов отклонён с объяснением «<причина>», вопрос не создан + +| варианты | по умолчанию | причина | +|---|---|---| +| нет | нет | нужны 2–4 варианта | +| «Да» | «Да» | нужны 2–4 варианта | +| «Да», «Нет» | нет | нужен вариант по умолчанию | +| «Да», «Нет» | «Может быть» | вариант по умолчанию — один из вариантов | + +### Requirement: Блокер идёт по своему маршруту +Инструмент `report_blocker` SHALL принимать, что мешает и что агент уже пробовал. Продуктовый блокер SHALL идти пользователю как `question` с вариантами; непродуктовый SHALL записываться в «События агентов» и SHALL NOT отправляться владельцу проекта. + +#### Scenario: Непродуктовый блокер +- **WHEN** агент сообщает блокер «нет доступа к серверу сборки», пробовал «повторил три раза» +- **THEN** в треде задачи в «Событиях агентов» есть запись о блокере +- **AND** владелец не получает ни вопроса, ни сообщения в Telegram + +#### Scenario: Продуктовый блокер без вариантов +- **WHEN** агент сообщает продуктовый блокер без вариантов ответа +- **THEN** вызов отклонён с объяснением, что нужны варианты и вариант по умолчанию + +### Requirement: Нет кнопки «Продолжай» +Веб и Telegram-бот SHALL NOT показывать кнопку «Продолжай» ни у какого сообщения; у `question` SHALL быть кнопки вариантов и возможность своего ответа. + +#### Scenario: Сообщение фабрики в Telegram +- **GIVEN** открытое сообщение фабрики без вариантов ответа +- **WHEN** бот отправляет его в Telegram +- **THEN** у сообщения нет кнопки «Продолжай» + +#### Scenario: Старая кнопка «Продолжай» +- **GIVEN** старое сообщение в Telegram с кнопкой «Продолжай» +- **WHEN** пользователь нажимает её +- **THEN** агенту ничего не отправляется From 2dd13261bc413c9f5666ae10ef8468a92c6364d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 12:08:52 +0500 Subject: [PATCH 09/11] PEP-149: migration regenerated on top of main (0020) Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 2 +- packages/db/migrations/0020_fuzzy_plazm.sql | 2 + .../db/migrations/meta/0020_snapshot.json | 4372 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + 4 files changed, 4382 insertions(+), 1 deletion(-) create mode 100644 packages/db/migrations/0020_fuzzy_plazm.sql create mode 100644 packages/db/migrations/meta/0020_snapshot.json diff --git a/AGENTS.md b/AGENTS.md index 3f1dcd15..906a0217 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,7 +43,7 @@ - **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики» - **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок) - **Слова по режиму (PEP-123)**: `@peppa/shared/wording` — `wording(mode)`: `task(форма)` / `Task` / `tasks(n)` («задача» в «Продакте», «стори» в «Инженере»), `runner(форма)` («агент» / «раннер»), формы `nom|gen|dat|acc|ins|pre|pl|genPl|datPl|accPl|insPl|prePl`. Веб: серверный компонент — `const w = await words()` (`lib/auth.ts`), клиентский — `useWords()` (`components/Words.tsx`, `WordsProvider` в раскладке). Что читает только инженер (репозиторий, раннеры, модель, секреты, бюджет, ревьюер в «Настройках проекта», команда терминала, адрес кода, подробная автономность) — под `w.engineer`. Тексты без читателя (события чатов `EVENT_TEXT`, вопросы и сообщения PM из runner, Telegram, push, подписи из core) — всегда словами «Продакта»: «задача», «агент», «Peppa FACTORY», «вы», «Результат:» вместо «PR:». Промпты агентам, MCP и CLI — прежние слова. Страница задачи, полоса лимитов и «Помощь» — PEP-120/121/122. Тест `wording.test.ts` -- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0019; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts` +- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0020; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts` - **Комментарий уточняет постановку (PEP-115)**: `pm_comment` к стори в бэклоге без живого агента → `storyRefineTick` в тике вачдога (`runner/story-refine.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`/`_MODEL`), промпт `refinePrompt` (core/story-refine.ts: контекст `intakeContext`, текущая постановка, обсуждение, новые комментарии), ответ — JSON аналитика (`parseAnalystNote`) → описание через `intakeDescription` («Исходный запрос» сохраняется, `originalRequest`) + заметка аналитика `intake_note` в «Обсуждении» стори. Курсор `refine.task:`, комментарии старше `PEPPA_STORY_REFINE_MAX_AGE_MIN` (60) не трогаются, сбой — одна заметка без повторов, стори взяли в работу до ответа — описание не меняется, роли PEP-84 не закончили — ждёт; `PEPPA_STORY_REFINE=off`. `refinePending` — «Аналитик уточняет постановку…» и исключение из `readyBacklog`. Подпись поля — `apps/web/lib/comment-hint.ts`. Мок — роль `refine` в `mock-intake` (`slowMs`); тест `story-refine.test.ts` - **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок) - **Страница задачи в режиме «Продакт» (PEP-120)**: `t/[key]/page.tsx` при `uiMode()` = product рисует `components/StoryProduct.tsx` — карточку из `storyProductView` (core/story-product.ts, чистая функция; все тексты — `STORY_PRODUCT_TEXT`; `plainStep` не показывает пункт tasks.md с путями, файлами и идентификаторами): что сейчас, «Шаг N из M», «Посмотреть» (`reviewPreview().previewUrl`), что нужно от вас, что дальше, открытые вопросы (`QuestionCard plain`: команда разрешения — под «Подробнее»), «Принять» (`acceptStoryAction`) и «Поправить» (`fixStoryAction` → `fixStory` в runner/flow.ts: только из ревью, комментарий + закрыть «готово к ревью» + `moveTask in_progress` + замечание агенту). Прежнее содержимое страницы и блоки правой панели — под ссылкой «Подробнее» (`?more=1`, также `?tab=`/`?edit=`; закрыто — терминал не монтируется), без правой панели и значка статуса. «Инженер» — без изменений. Тест `story-product.test.ts` diff --git a/packages/db/migrations/0020_fuzzy_plazm.sql b/packages/db/migrations/0020_fuzzy_plazm.sql new file mode 100644 index 00000000..ab537714 --- /dev/null +++ b/packages/db/migrations/0020_fuzzy_plazm.sql @@ -0,0 +1,2 @@ +ALTER TABLE `questions` ADD `msg_type` text;--> statement-breakpoint +ALTER TABLE `questions` ADD `default_option` text; \ No newline at end of file diff --git a/packages/db/migrations/meta/0020_snapshot.json b/packages/db/migrations/meta/0020_snapshot.json new file mode 100644 index 00000000..75262e8e --- /dev/null +++ b/packages/db/migrations/meta/0020_snapshot.json @@ -0,0 +1,4372 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "53ced319-040c-444d-8e11-97e95c7b2821", + "prevId": "61f327b6-cb6a-4359-9b4b-23df03040aa9", + "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": {} + }, + "feedback": { + "name": "feedback", + "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 + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'received'" + }, + "analysis": { + "name": "analysis", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_error": { + "name": "analysis_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_started_at": { + "name": "analysis_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "option_index": { + "name": "option_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reject_reason": { + "name": "reject_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_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": { + "feedback_user": { + "name": "feedback_user", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + }, + "feedback_status": { + "name": "feedback_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "feedback_user_id_users_id_fk": { + "name": "feedback_user_id_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "feedback_task_id_tasks_id_fk": { + "name": "feedback_task_id_tasks_id_fk", + "tableFrom": "feedback", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "feedback_decided_by_users_id_fk": { + "name": "feedback_decided_by_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "decided_by" + ], + "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 + }, + "msg_type": { + "name": "msg_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_option": { + "name": "default_option", + "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 2081d2ec..ca475679 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -141,6 +141,13 @@ "when": 1794806148240, "tag": "0019_stormy_vin_gonzales", "breakpoints": true + }, + { + "idx": 20, + "version": "6", + "when": 1794812739508, + "tag": "0020_fuzzy_plazm", + "breakpoints": true } ] } \ No newline at end of file From 165b4865470f9ba06e83ecf7e8ae6503f0dbdb59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 12:35:47 +0500 Subject: [PATCH 10/11] =?UTF-8?q?PEP-149:=20rebased=20on=20PEP-151=20?= =?UTF-8?q?=E2=80=94=20the=20refreshed=20Telegram=20message=20has=20no=20?= =?UTF-8?q?=C2=ABcontinue=C2=BB=20button?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- packages/testkit/test/no-repeats.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/testkit/test/no-repeats.test.ts b/packages/testkit/test/no-repeats.test.ts index f5cec6e5..d5e4e014 100644 --- a/packages/testkit/test/no-repeats.test.ts +++ b/packages/testkit/test/no-repeats.test.ts @@ -96,10 +96,10 @@ describe("Одно состояние — одно сообщение", () => { assert.equal(inThread.length, 1); assert.equal(inThread[0]!.repeats, 8); assert.ok(inThread[0]!.updatedAt); - // Telegram: still one message, with the last text and the «Продолжай» button back. + // Telegram: still one message, with the last text; PEP-149: no «Продолжай» button any more. const msg = await waitFor("the Telegram message refreshed", async () => { const [m] = tgAbout(t.project.key); - return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null; + return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && !m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null; }); assert.equal(tgAbout(t.project.key).length, 1); assert.ok(msg.edits >= 1); From 4dec8247a268ac83fee7e6d86d8e85160857c422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 12:47:00 +0500 Subject: [PATCH 11/11] =?UTF-8?q?PEP-149:=20=C2=ABproduct=20released=C2=BB?= =?UTF-8?q?=20and=20=C2=ABbacklog=20is=20empty=C2=BB=20notices=20ask=20not?= =?UTF-8?q?hing=20=E2=80=94=20no=20answer=20form;=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/web/components/cards.tsx | 6 ++++-- packages/testkit/test/agent-messages.test.ts | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 47eb7afe..148c1594 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -1,7 +1,7 @@ // Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; -import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; +import { questionState, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { db } from "@/lib/db"; import { SubscriptionName } from "@/components/SubscriptionName"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; @@ -37,6 +37,7 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal const t = await getT(); const review = q.kind === "attention" && taskStatus === "review"; const answered = !!q.answeredAt; + const notice = questionType(q, taskStatus) === null && q.taskId == null && q.sessionId == null; // PEP-149: a factory message with answers to choose from is a question for the person. const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind]; const Icon = review ? CircleCheck : k.icon; @@ -71,12 +72,13 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal

    {t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

    )} + {/* PEP-149: a notice about the product as a whole (released, backlog is empty) asks nothing — no answer form. */} {answered ? (

    {q.answeredVia === "system" ? : } {q.answeredVia === "system" ? t.text(q.answer) : t("Ответ ({via}): {answer}", { via: q.answeredVia, answer: q.answer })}

    - ) : ( + ) : notice ? null : (
    diff --git a/packages/testkit/test/agent-messages.test.ts b/packages/testkit/test/agent-messages.test.ts index 473f241d..48b51672 100644 --- a/packages/testkit/test/agent-messages.test.ts +++ b/packages/testkit/test/agent-messages.test.ts @@ -130,6 +130,21 @@ describe("Тип сообщения определяет маршрут", () => assert.equal(core.questionEvent(failure, { taskStatus: "review" }), "review"); }); + test("Сообщения «продукт обновлён» и «бэклог пуст» — не вопросы", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + for (const text of ["🚀 Shop: ваш продукт обновлён и открыт для всех", "📭 Shop: все задачи сделаны, бэклог пуст — агентам нечего делать."]) { + const q = await core.askPmProject(db, p, { kind: "attention", text }); + assert.equal(q.msgType, null); + assert.equal(core.needsPerson(q), false, "not in «Ждут вашего ответа», not counted, no push"); + // Telegram: a plain notice — no buttons to press. + assert.deepEqual(renderQuestion(q, { taskKey: null, taskTitle: null, session: null, webUrl: "http://peppa.test" }).buttons, []); + } + // The offer to release has an answer to choose: it is a question. + const offer = await core.askPmProject(db, p, { kind: "question", text: "Показать всем?", options: ["🚀 Показать всем"] }); + assert.equal(core.needsPerson(offer), true); + }); + test("Счётчик открытых вопросов чата считает только вопросы", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key);