diff --git a/AGENTS.md b/AGENTS.md
index 5fb61cbf..36872b68 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,7 +7,7 @@
## Структура
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (PEP-32): шапка (статус, эпик, прогресс tasks.md, «Изменить» — название/описание/эпик, агент и живая сессия с терминалом и лентой шагов) и вкладки `?tab=` Proposal · Design (свой безопасный рендер `components/Markdown.tsx`) · Specs (дельта-спеки change) · Tasks · Comments (вопросы + комментарии PM: событие `pm_comment`, агент видит в `get_task`, флажок «Отправить агенту сейчас») · Tests · Merge request («Принять и смержить» = `acceptStory` в runner/flow.ts) · Activity (с авторами: `payload.login` / сессия / система); change читает `core/openspec.ts` (`readChange`, `parseTasks`, `taskProgress`, и архивный); новый проект. **Живые страницы (PEP-37)**: `LiveRefresh` (вместо `AutoRefresh`, он остался только у подписок) слушает SSE `GET /api/live?scope=home|runners|project:|task:|steps:` и делает `router.refresh()` (ждёт, пока пользователь печатает), индикатор связи, откат на опрос 5 с; хаб `runner/live.ts` (`globalThis`) будят `notify()` (подписчик `web`, сокет `$PEPPA_HOME/web.events.sock`) и `PRAGMA data_version` + `total_changes()` раз в секунду, отпечаток области — один SQL без `last_activity_at`/шагов; заголовки `no-cache, no-transform`, `X-Accel-Buffering: no`, пинг 15 с **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
-- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
+- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта. **Стори из сообщения (PEP-45)**: любой другой текст привязанного пользователя — черновик (`apps/bot/src/drafts.ts`, `settings` `bot.draft:`, сутки): префикс `KEY:`/`в KEY:` (только свои проекты) или кнопки проекта → кнопки эпика/«Создать» → `createTask` → «▶️ Взять в работу» (`moveTask`); кнопки `d::p|g|x`, `t::start|keep`. Голос: `getFile` → `transcribe.ts` — OpenAI-совместимый `POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions` (`PEPPA_TRANSCRIBE_KEY`, `_MODEL`=whisper-1, `_LANG`=ru); без env — просит текстом. Моки: `mock-transcribe`, голос и `/file/` в `mock-telegram`
- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36)
- `packages/shared` — env, ключи задач (`PEP-42`)
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM); живые обновления — `notify()` будит подписчика (бота) через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот вдобавок раз в секунду смотрит `PRAGMA data_version`; ежедневная копия базы (`backupDb`, `VACUUM INTO`, `~/.peppa/backups`, 7 штук) из вачдога; всё ходит через неё
@@ -36,6 +36,8 @@
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]`
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)
- Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью)
+ - **Gitea → Пеппа (PEP-46)**: вебхук подписан на `GITEA_HOOK_EVENTS` (+ issues, issue_comment, pull_request_comment, pull_request_review; обновить у существующих — `peppa ci connect `); `handleGiteaEvent` (runner/gitea-events.ts) определяет событие по форме payload (Gitea 1.22 зовёт и ревью, и комментарий `pull_request_comment`). Issue от владельца/участника (логин Gitea, `users.gitea_id > 0`) → стори в бэклоге (`tasks.gitea_issue`, идемпотентно) + комментарий-ссылка от peppa-bot; чужие игнор; `moveTask(done)` закрывает issue; разовый импорт `peppa project import-issues ` (без проверки автора). Комментарий/ревью «нужны изменения» в PR стори → агенту (живой раннер или новый, из «Ревью» — в работу); одобрения и `GITEA_BOT_LOGIN` (peppa-bot) — игнор. PR смержен руками → стори done, «готово к ревью» закрыт (`acceptTask` терпит гонку с вебхуком)
+ - **Превью на ревью (PEP-44)**: `reviewPreview` (core/preview.ts) — здоровый превью-стенд PR стори из `releases`, дифф `/files`, итог проверок, скриншоты, issue; в «готово к ревью» (Stop-хук, ревьюер), карточке (`components/ReviewPreview.tsx`) и `get_task`. Скриншоты снимает `peppa-deploy.sh preview` (headless Chromium в контейнере `PEPPA_SCREENSHOT_IMAGE`, сеть Traefik, base64 через stdout; страницы `deploy.screenshots`, по умолчанию `["/"]`) → `X-Peppa-Event: screenshots` → `recordScreenshots` (`$PEPPA_HOME/screenshots//`, ≤6×3 МБ, PNG) → `releases.screenshots`; веб `/api/releases//shots/` (владелец/участник)
- Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены»)
- **Агент-ревьюер (PEP-26)**: настройка проекта `review_settings` (вкл/выкл, по умолчанию выкл; `max_iterations` = 2; `rules` PM) — веб «⋯ Настройки проекта → Ревьюер». Агент зовёт MCP `update_task(status: review)`, гейт PEP-57 пройден → `requestReview` (runner/reviewer.ts): ставит `code_reviews` (queued, головной SHA PR) и сразу запускает в процессе MCP, агенту — «закончи ход» (стори остаётся `in_progress`; Stop-хук не подгоняет, пока `pendingReview`). Ревью: дифф `GiteaClient.pullDiff` → `$PEPPA_REVIEW_BIN -p --output-format json --model ${PEPPA_REVIEW_MODEL:-sonnet}` (общий запуск `runner/claude-print.ts`, токен пула проекта, как триаж). `changes` → замечания агенту (`sendToSession` или новый раннер), `ok`/ошибка → стори в `review` и «готово к ревью» с резюме (если ход агента ещё идёт — его шлёт Stop-хук с той же заметкой `reviewNote`). Тот же одобренный SHA не ревьюится повторно; после `max_iterations` возвратов — к PM с последними замечаниями. Зависшие/непринятые — `reviewTick` в вачдоге (раз в минуту). Карточка и `get_task` — последнее ревью. PM, двигающий карточку сам, ревьюера не зовёт. Мок `mock-reviewer` (`MOCK_REVIEW_SCENARIO`)
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index e4c85b05..8181a1eb 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -34,16 +34,26 @@ import {
questionByTelegramMessage,
setOffset,
setSetting,
+ createTask,
+ getGoal,
+ listGoals,
+ listUserProjects,
+ type Project,
type OutboxRow,
type Question,
type SessionView,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
-import { acceptTask, answerAndDeliver, decideIncident, resumeSession, stopSession } from "@peppa/runner";
-import { eq } from "drizzle-orm";
+import { acceptTask, answerAndDeliver, decideIncident, moveTask, resumeSession, stopSession } from "@peppa/runner";
+import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
-import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
+import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
+import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
+import { transcribe, transcribeConfig, TranscribeError } from "./transcribe.ts";
+
+/** Longest voice note the bot transcribes (seconds). */
+const VOICE_MAX_SEC = 5 * 60;
export interface BotOptions {
db: Db;
@@ -65,6 +75,7 @@ const HELP = `Я бот Пеппы. Присылаю вопросы от аге
• Кнопки под сообщением — быстрый ответ.
• Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию.
+• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
• /status — активные сессии и открытые вопросы.
• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
@@ -231,6 +242,133 @@ export function createBot(o: BotOptions) {
return lines.join("\n");
}
+ // ── stories from messages (PEP-45) ─────────────────────────────────────────────
+ const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }];
+ const rows = (buttons: InlineButton[], per = 2) => buttons.reduce((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
+ const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`;
+
+ /** Send (or, for a button press, edit in place) a bot message with buttons. */
+ async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) {
+ const params = { chat_id: chatId, text, parse_mode: "HTML", reply_markup: { inline_keyboard: buttons }, link_preview_options: { is_disabled: true } };
+ if (editId) await api.call("editMessageText", { ...params, message_id: editId }).catch((e) => log(`edit: ${(e as Error).message}`));
+ else await api.call("sendMessage", params).catch((e) => log(`send: ${(e as Error).message}`));
+ }
+
+ async function askProject(d: Draft, projects: Project[], editId?: number) {
+ // Most recently active first (the latest story touched), then newest projects.
+ const touched = new Map();
+ for (const r of await db.select({ projectId: tasks.projectId, at: sql`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0);
+ projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id);
+ const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` }));
+ const more = projects.length > 12 ? "\nНет нужного — напиши заново с ключом: «KEY: …»." : "";
+ await show(d.chatId, `📝 Новая стори ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId);
+ }
+
+ async function askEpic(d: Draft, project: Project, editId?: number) {
+ const epics = (await listGoals(db, project.id)).slice(0, 10);
+ const buttons = epics.length
+ ? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }]
+ : [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }];
+ await show(d.chatId, `📝 Новая стори в ${esc(project.key)} : ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId);
+ }
+
+ /** A plain message (or a transcribed voice note) → a draft and the next question. */
+ async function startStory(user: User, chatId: number, text: string, voice: boolean) {
+ const projects = await listUserProjects(db, user.id);
+ if (!projects.length) return reply(chatId, `У тебя пока нет проектов — создай первый: ${esc(o.webUrl)}/projects/new`);
+ const parsed = parseStoryText(text, projects);
+ if (!parsed.body) return reply(chatId, "Пустая стори — напиши, что сделать.");
+ const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null);
+ const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice });
+ if (project) await askEpic(d, project);
+ else await askProject(d, projects);
+ }
+
+ async function onVoice(user: User, m: TgMessage) {
+ const f = m.voice ?? m.audio!;
+ const cfg = transcribeConfig();
+ if (!cfg) return reply(m.chat.id, "Голосовые пока не настроены — напиши задачу текстом.", m.message_id);
+ if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) — запиши короче или напиши текстом.`, m.message_id);
+ let text: string;
+ try {
+ const file = await api.getFile(f.file_id);
+ if (!file.file_path) throw new TranscribeError("Telegram не отдал файл");
+ const audio = await api.downloadFile(file.file_path);
+ text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg");
+ } catch (e) {
+ log(`voice: ${(e as Error).message}`);
+ return reply(m.chat.id, `Не получилось расшифровать голосовое (${esc((e as Error).message)}). Напиши текстом.`, m.message_id);
+ }
+ if (!text) return reply(m.chat.id, "Не разобрал ни слова — попробуй ещё раз или напиши текстом.", m.message_id);
+ await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id);
+ await startStory(user, m.chat.id, text, true);
+ }
+
+ /** Buttons of a draft (`d::p:` / `d::g:` / `d::x`) and of a new story (`t::start|keep`). */
+ async function onStoryButton(user: User, c: TgCallbackQuery, parts: string[]): Promise {
+ const msgId = c.message?.message_id;
+ const chatId = c.message!.chat.id;
+ if (parts[0] === "t") {
+ const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1])));
+ if (!t || !(await canAccess(user, t.projectId))) return "Стори не найдена";
+ const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
+ const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
+ const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
+ if (parts[2] === "keep") {
+ await show(chatId, `${head}\nВ бэклоге.`, [], msgId);
+ return "Оставил в бэклоге";
+ }
+ if (parts[2] !== "start") return "Неизвестная кнопка";
+ if (t.status !== "backlog") {
+ await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId);
+ return `${ref.key} уже ${t.status}`;
+ }
+ try {
+ await moveTask(db, ref, "in_progress");
+ } catch (e) {
+ return (e as Error).message;
+ }
+ await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId);
+ return `${ref.key}: агент взялся ▶️`;
+ }
+ const d = await loadDraft(db, Number(parts[1]), user.id);
+ if (!d) {
+ await show(chatId, "Черновик не найден или устарел — напиши заново.", [], msgId);
+ return "Черновик устарел";
+ }
+ if (parts[2] === "x") {
+ await dropDraft(db, d.id);
+ await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId);
+ return "Отменено";
+ }
+ if (parts[2] === "p") {
+ const projectId = Number(parts[3]);
+ const project = await projectForUser(db, user.id, projectId).catch(() => null);
+ if (!project) return "Проект не найден";
+ await updateDraft(db, { ...d, projectId });
+ await askEpic(d, project, msgId);
+ return project.key;
+ }
+ if (parts[2] === "g" && d.projectId) {
+ const project = await projectForUser(db, user.id, d.projectId).catch(() => null);
+ if (!project) return "Проект не найден";
+ const goalId = Number(parts[3]) || undefined;
+ if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден";
+ const { title, rest } = splitStory(d.text);
+ const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`;
+ const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
+ await dropDraft(db, d.id);
+ await show(
+ chatId,
+ `📥 Создал ${esc(ref.key)} : ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`,
+ [[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]],
+ msgId,
+ );
+ return `Создал ${ref.key}`;
+ }
+ return "Неизвестная кнопка";
+ }
+
async function onMessage(m: TgMessage): Promise<"done" | "ignored"> {
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
@@ -264,7 +402,16 @@ export function createBot(o: BotOptions) {
await reply(m.chat.id, esc(await answer(q, text)), m.message_id);
return "done";
}
- await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. /status — что сейчас происходит.");
+ if (m.voice || m.audio) {
+ await onVoice(user, m);
+ return "done";
+ }
+ if (!text || text.startsWith("/")) {
+ await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею.");
+ return "done";
+ }
+ // PEP-45: any other text is a new story (created only after a button press).
+ await startStory(user, m.chat.id, text, false);
return "done";
}
@@ -274,7 +421,13 @@ export function createBot(o: BotOptions) {
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
return "ignored";
}
- const [kind, idStr, choice] = (c.data ?? "").split(":");
+ const parts = (c.data ?? "").split(":");
+ if (parts[0] === "d" || parts[0] === "t") {
+ const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка"));
+ await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
+ return "done";
+ }
+ const [kind, idStr, choice] = parts;
const id = Number(idStr);
let toast = "Неизвестная кнопка";
const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
diff --git a/apps/bot/src/drafts.ts b/apps/bot/src/drafts.ts
new file mode 100644
index 00000000..99ea1b66
--- /dev/null
+++ b/apps/bot/src/drafts.ts
@@ -0,0 +1,74 @@
+// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so
+// a stray message never creates a story by itself. Drafts live in `settings` for a day.
+import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core";
+import type { Db } from "@peppa/db";
+
+export const DRAFT_TTL_MS = 24 * 3600_000;
+export const TITLE_MAX = 120;
+
+export interface Draft {
+ id: number;
+ userId: number;
+ chatId: number;
+ text: string;
+ projectId: number | null;
+ voice: boolean;
+ createdAt: number;
+}
+
+const key = (id: number) => `bot.draft:${id}`;
+
+export async function saveDraft(db: Db, d: Omit): Promise {
+ const id = ((await getSetting(db, "bot.draft.seq")) ?? 0) + 1;
+ await setSetting(db, "bot.draft.seq", id);
+ const draft: Draft = { ...d, id, createdAt: Date.now() };
+ await setSetting(db, key(id), draft);
+ return draft;
+}
+
+/** The user's own, not expired draft. */
+export async function loadDraft(db: Db, id: number, userId: number): Promise {
+ const d = await getSetting(db, key(id));
+ if (!d || d.userId !== userId) return null;
+ if (Date.now() - d.createdAt > DRAFT_TTL_MS) {
+ await deleteSetting(db, key(id));
+ return null;
+ }
+ return d;
+}
+
+export async function updateDraft(db: Db, d: Draft): Promise {
+ await setSetting(db, key(d.id), d);
+}
+
+export async function dropDraft(db: Db, id: number): Promise {
+ await deleteSetting(db, key(id));
+}
+
+/**
+ * "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…".
+ * The key counts only if it is one of the user's projects; otherwise the whole text is the story.
+ */
+export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
+ const t = text.trim();
+ const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
+ const withSep = /^(?:(?:в|во|для|in|to)\s+)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
+ if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() };
+ const spoken = /^(?:в|во|для|in|to)\s+([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
+ if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() };
+ return { project: null, body: t };
+}
+
+/** Title (first line, at most TITLE_MAX chars, cut at a word) and the rest as description. */
+export function splitStory(body: string): { title: string; rest: string } {
+ const [first = "", ...lines] = body.trim().split("\n");
+ let title = first.trim();
+ let rest = lines.join("\n").trim();
+ if (title.length > TITLE_MAX) {
+ const cut = title.lastIndexOf(" ", TITLE_MAX - 1);
+ const at = cut > TITLE_MAX / 2 ? cut : TITLE_MAX - 1;
+ rest = `${title}${rest ? `\n\n${rest}` : ""}`;
+ title = `${title.slice(0, at).trim()}…`;
+ }
+ return { title, rest };
+}
diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts
index fad604cc..b8039146 100644
--- a/apps/bot/src/telegram.ts
+++ b/apps/bot/src/telegram.ts
@@ -12,6 +12,15 @@ export interface TgMessage {
from?: TgUser;
text?: string;
reply_to_message?: TgMessage;
+ /** PEP-45: voice notes and audio files become stories after transcription. */
+ voice?: TgFileRef;
+ audio?: TgFileRef;
+}
+export interface TgFileRef {
+ file_id: string;
+ duration?: number;
+ mime_type?: string;
+ file_size?: number;
}
export interface TgCallbackQuery {
id: string;
@@ -96,6 +105,17 @@ export class TelegramApi {
return this.call("answerCallbackQuery", { callback_query_id: id, text });
}
+ getFile(fileId: string) {
+ return this.call<{ file_id: string; file_path?: string; file_size?: number }>("getFile", { file_id: fileId });
+ }
+
+ /** Bytes of a file from getFile (Bot API: GET /file/bot/, up to 20 MB). */
+ async downloadFile(filePath: string): Promise {
+ const res = await fetch(`${this.baseUrl}/file/bot${this.token}/${filePath}`, { signal: AbortSignal.timeout(60_000) });
+ if (!res.ok) throw new TelegramError("downloadFile", res.status, res.statusText);
+ return Buffer.from(await res.arrayBuffer());
+ }
+
sendMessage(chatId: number, text: string, extra: Record = {}) {
return this.call("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
}
diff --git a/apps/bot/src/transcribe.ts b/apps/bot/src/transcribe.ts
new file mode 100644
index 00000000..11bfe038
--- /dev/null
+++ b/apps/bot/src/transcribe.ts
@@ -0,0 +1,52 @@
+// Speech to text for voice notes (PEP-45): any OpenAI-compatible audio API —
+// POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions (multipart: file, model, language,
+// response_format=json) with "Authorization: Bearer $PEPPA_TRANSCRIBE_KEY" → {"text": "…"}.
+// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1,
+// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use
+// mock-transcribe (packages/testkit).
+
+export interface TranscribeConfig {
+ url: string;
+ key: string | null;
+ model: string;
+ language: string | null;
+}
+
+/** From env; null when voice is not set up (the bot asks for text then). */
+export function transcribeConfig(env: NodeJS.ProcessEnv = process.env): TranscribeConfig | null {
+ const url = env.PEPPA_TRANSCRIBE_URL?.trim();
+ if (!url) return null;
+ return {
+ url: url.replace(/\/$/, ""),
+ key: env.PEPPA_TRANSCRIBE_KEY?.trim() || null,
+ model: env.PEPPA_TRANSCRIBE_MODEL?.trim() || "whisper-1",
+ language: env.PEPPA_TRANSCRIBE_LANG === "" ? null : (env.PEPPA_TRANSCRIBE_LANG?.trim() || "ru"),
+ };
+}
+
+export class TranscribeError extends Error {}
+
+export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename = "voice.ogg", mime = "audio/ogg"): Promise {
+ const form = new FormData();
+ form.set("file", new Blob([new Uint8Array(audio)], { type: mime }), filename);
+ form.set("model", cfg.model);
+ form.set("response_format", "json");
+ if (cfg.language) form.set("language", cfg.language);
+ let res: Response;
+ try {
+ res = await fetch(`${cfg.url}/audio/transcriptions`, {
+ method: "POST",
+ headers: cfg.key ? { Authorization: `Bearer ${cfg.key}` } : {},
+ body: form,
+ signal: AbortSignal.timeout(120_000),
+ });
+ } catch (e) {
+ throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`);
+ }
+ const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string };
+ if (!res.ok) {
+ const msg = typeof body.error === "string" ? body.error : body.error?.message;
+ throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`);
+ }
+ return (body.text ?? "").trim();
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index ac9331ae..b671b5ce 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -137,6 +137,17 @@ export default async function Help() {
deploy ). После каждого деплоя — проверка /healthz до 2 минут; не
прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
+
+ Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на
+ дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из deploy.screenshots {" "}
+ (по умолчанию главная, [] — выключить) — они в карточке стори.
+
+
+ Gitea знает о Пеппе: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится
+ ссылка; стори готова — issue закроется), старые открытые issues переносит{" "}
+ peppa project import-issues KEY . Комментарий или ревью «нужны изменения» в PR стори
+ уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово».
+
Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок{" "}
main приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с
@@ -152,6 +163,10 @@ export default async function Help() {
проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что
сейчас происходит, /digest — сводка за сутки.
+
+ Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и
+ эпик кнопками, создаст стори и предложит «Взять в работу». Голосовые работают, если на сервере настроена расшифровка.
+
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index f9413c46..f65c6347 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -17,6 +17,7 @@ import {
PROVIDER_NAMES,
readChange,
reviewLabel,
+ reviewPreview,
sessionSteps,
storyComments,
taskCiSummary,
@@ -31,6 +32,7 @@ import { LiveRefresh } from "@/components/LiveRefresh";
import { Button } from "@/components/ui/button";
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
+import { ReviewPreview } from "@/components/ReviewPreview";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { taskActivity, taskForUser } from "@/lib/queries";
@@ -64,6 +66,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const tab: StoryTab = STORY_TABS.find((t) => t.id === sp.tab)?.id ?? (change ? "proposal" : "comments");
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
const back = tabHref(tab);
+ const preview = await reviewPreview(db, ref);
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
const superadmin = await isSuperadmin(db, user);
const pool = await projectPool(db, project.id);
@@ -86,6 +89,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const aside = (
+
{CI_ICON[ci.state as keyof typeof CI_ICON]}
diff --git a/apps/web/app/api/releases/[id]/shots/[n]/route.ts b/apps/web/app/api/releases/[id]/shots/[n]/route.ts
new file mode 100644
index 00000000..c507ccdc
--- /dev/null
+++ b/apps/web/app/api/releases/[id]/shots/[n]/route.ts
@@ -0,0 +1,18 @@
+// Screenshots of a preview stand (PEP-44), taken by the project's CI step: only the
+// project's owner and members see them.
+import { projectForUser } from "@peppa/core";
+import { releaseScreenshot } from "@peppa/runner";
+import { currentUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(_req: Request, { params }: { params: Promise<{ id: string; n: string }> }) {
+ const user = await currentUser();
+ if (!user) return new Response("Нужен вход", { status: 401 });
+ const { id, n } = await params;
+ const shot = await releaseScreenshot(db, Number(id), Number(n));
+ const allowed = shot && (await projectForUser(db, user.id, shot.projectId).then(() => true, () => false));
+ if (!shot || !allowed) return new Response("Не найдено", { status: 404 });
+ return new Response(new Uint8Array(shot.png), { headers: { "Content-Type": "image/png", "Cache-Control": "private, max-age=3600" } });
+}
diff --git a/apps/web/components/ReviewPreview.tsx b/apps/web/components/ReviewPreview.tsx
new file mode 100644
index 00000000..87e0a513
--- /dev/null
+++ b/apps/web/components/ReviewPreview.tsx
@@ -0,0 +1,46 @@
+// PEP-44/46: what the PM needs to review a story — the preview stand of its PR, the diff,
+// the screenshots taken by CI, and the Gitea issue it came from.
+import { Eye, FileDiff, CircleDot } from "lucide-react";
+import type { ReviewPreview as Preview } from "@peppa/core";
+import { PanelSection } from "@/components/ActivityAside";
+
+export function ReviewPreview({ preview }: { preview: Preview }) {
+ if (!preview.previewUrl && !preview.diffUrl && !preview.issueUrl) return null;
+ return (
+
+
+ {preview.releaseId != null && preview.screenshots.length > 0 && (
+
+ )}
+
+ );
+}
diff --git a/openspec/changes/archive/2026-11-14-pep-44-review-preview/proposal.md b/openspec/changes/archive/2026-11-14-pep-44-review-preview/proposal.md
new file mode 100644
index 00000000..ccfe7fb8
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-44-review-preview/proposal.md
@@ -0,0 +1,28 @@
+# PEP-44: Превью результата на ревью — ссылка на стенд и скриншоты
+
+## Зачем
+PM принимает стори вслепую по тексту агента. CD (PEP-57) уже поднимает стенд PR
+`-pr.telecom.quest` и пишет его в `releases`, но ни сообщение «готово к ревью»,
+ни карточка стори об этом не говорят.
+
+## Что меняется
+- **Сводка ревью** (`reviewPreview` в core): последний здоровый превью-стенд PR стори
+ («👀 Посмотреть»), дифф (`/files`), итог проверок (`taskCiSummary`), скриншоты.
+ Добавляется в «готово к ревью» (Stop-хук и агент-ревьюер), в карточку стори и в
+ MCP `get_task`.
+- **Скриншоты в CI-шаге, не на хосте.** `peppa-deploy.sh preview` после здорового стенда
+ снимает страницы `deploy.screenshots` (по умолчанию `["/"]`) headless Chromium в
+ контейнере (`PEPPA_SCREENSHOT_IMAGE`, по умолчанию `zenika/alpine-chrome`) в сети
+ Traefik — PNG через stdout (base64), без томов, т.к. job сам в контейнере. Отчёт
+ `X-Peppa-Event: screenshots` (подпись как у deploy). Сбой скриншотов деплой не валит.
+- **Пеппа хранит** PNG в `$PEPPA_HOME/screenshots//` (≤ 6 штук, ≤ 3 МБ,
+ проверка сигнатуры PNG), список — в `releases.screenshots`. Веб отдаёт их по
+ `/api/releases//shots/` только владельцу и участникам проекта.
+- Превью поднялся после «готово к ревью» — ссылка есть в карточке (сообщение не редактируется).
+
+## Влияние
+- БД: `releases.screenshots` (миграция). core: `reviewPreview`; runner: `recordScreenshots`,
+ хук, ревьюер; веб: маршрут скриншотов и блок в карточке; шаблон: `peppa-deploy.sh`.
+- testkit: `mock-docker run` отдаёт PNG; `deploy.test.ts`.
+- Реальная интеграция: `scripts/push-template.sh` и обновить `.gitea/peppa-deploy.sh` в
+ репо проектов; первый прогон скачает образ Chromium на docker хоста.
diff --git a/openspec/changes/archive/2026-11-14-pep-44-review-preview/specs/delivery-pipeline/spec.md b/openspec/changes/archive/2026-11-14-pep-44-review-preview/specs/delivery-pipeline/spec.md
new file mode 100644
index 00000000..42b1cd45
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-44-review-preview/specs/delivery-pipeline/spec.md
@@ -0,0 +1,18 @@
+## ADDED Requirements
+
+### Requirement: Превью на ревью
+Сообщение «готово к ревью» и карточка стори SHALL показывать ссылку на здоровый превью-стенд PR стори, ссылку на дифф и итог проверок; карточка SHALL показывать скриншоты стенда, снятые CI-шагом деплоя превью.
+
+#### Scenario: Стенд поднят
+- **GIVEN** стори PAY-7 с PR #3 и здоровым превью `pay-pr3.telecom.quest`
+- **WHEN** PAY-7 уходит в «Ревью»
+- **THEN** «готово к ревью» содержит «Посмотреть: https://pay-pr3.telecom.quest», ссылку на дифф и итог проверок
+
+#### Scenario: Скриншоты
+- **GIVEN** проект с `deploy.screenshots: ["/"]`
+- **WHEN** превью PR #3 поднялось здоровым
+- **THEN** CI-шаг присылает скриншот, он виден в карточке стори PAY-7
+
+#### Scenario: Скриншоты не сняты
+- **WHEN** снять скриншот не удалось
+- **THEN** превью всё равно здоровое, карточка показывает ссылку без скриншотов
diff --git a/openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md b/openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md
new file mode 100644
index 00000000..1da4d21b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md
@@ -0,0 +1,8 @@
+# Tasks: PEP-44
+
+- [x] 1.1 Схема `releases.screenshots` + миграция; core `reviewPreview`
+- [x] 1.2 runner `recordScreenshots` + событие `screenshots` в хуке; сводка в Stop-хуке и ревьюере
+- [x] 1.3 Шаблон `peppa-deploy.sh`: скриншоты превью в контейнере, отчёт
+- [x] 1.4 Веб: маршрут скриншотов, блок «Превью» в карточке; MCP `get_task`
+- [x] 1.5 testkit: `mock-docker run`, `deploy.test.ts`
+- [x] 1.6 AGENTS.md, «Помощь», `openspec validate`
diff --git a/openspec/changes/archive/2026-11-14-pep-45-bot-story/proposal.md b/openspec/changes/archive/2026-11-14-pep-45-bot-story/proposal.md
new file mode 100644
index 00000000..f299b7d1
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-45-bot-story/proposal.md
@@ -0,0 +1,29 @@
+# PEP-45: Создать стори сообщением боту — текст или голос
+
+## Зачем
+Стори заводятся только в вебе или через MCP. PM в дороге хочет написать или наговорить
+боту «в PAY: добавить экспорт в CSV» и сразу отдать агенту.
+
+## Что меняется
+- **Текст.** Обычное сообщение привязанного пользователя (не команда и не реплай на вопрос)
+ — черновик стори. Префикс `KEY:` / `в KEY:` выбирает проект (только из доступных
+ пользователю). Иначе: один проект — он, несколько — кнопки проектов.
+- **Эпик.** Есть открытые эпики — кнопки эпиков и «Без эпика»; нет — «✅ Создать» /
+ «Отмена». Шаг с кнопками — подтверждение: случайное сообщение не создаёт стори само.
+- **Создание.** Первая строка — название (≤ 120 символов), остальное и пометка «из Telegram
+ (логин)» — описание. Ответ: «Создал PAY-12» с кнопками «▶️ Взять в работу» (`moveTask` →
+ агент) и «Оставить в бэклоге».
+- **Голос.** Голосовое/аудио → файл из Bot API (`getFile`) → расшифровка по
+ OpenAI-совместимому API `POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions` (multipart:
+ `file`, `model` = `$PEPPA_TRANSCRIBE_MODEL` (whisper-1), `language` =
+ `$PEPPA_TRANSCRIBE_LANG` (ru); `Authorization: Bearer $PEPPA_TRANSCRIBE_KEY`; ответ
+ `{text}`) → бот показывает расшифровку и дальше как текст. Не настроено — бот просит
+ написать текстом. Подходит OpenAI, Groq, локальный faster-whisper/speaches.
+- Черновики — в `settings` (`bot.draft:`, сутки), без новых таблиц.
+
+## Влияние
+- apps/bot: `drafts.ts`, `transcribe.ts`, `telegram.ts` (`getFile`, скачивание файла).
+- testkit: `mock-telegram` (голосовые, `getFile`, `/file/…`), `mock-transcribe`
+ (контракт OpenAI audio API), тесты в `bot.test.ts`.
+- На моке: расшифровка. Для настоящей — ключ OpenAI-совместимого сервиса в `.env`
+ (`PEPPA_TRANSCRIBE_URL`, `PEPPA_TRANSCRIBE_KEY`) и перезапуск бота.
diff --git a/openspec/changes/archive/2026-11-14-pep-45-bot-story/specs/telegram-notifications/spec.md b/openspec/changes/archive/2026-11-14-pep-45-bot-story/specs/telegram-notifications/spec.md
new file mode 100644
index 00000000..44253b8e
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-45-bot-story/specs/telegram-notifications/spec.md
@@ -0,0 +1,28 @@
+## ADDED Requirements
+
+### Requirement: Стори из сообщения боту
+Привязанный пользователь SHALL создавать стори сообщением боту — текстом или голосом. Бот SHALL уточнять проект (если не указан и проектов несколько) и эпик кнопками, создавать стори только после нажатия кнопки и предлагать сразу взять её в работу. Проект SHALL выбираться только из доступных пользователю.
+
+#### Scenario: Текст с проектом
+- **GIVEN** PM с привязанным Telegram и проектом «PAY» без эпиков
+- **WHEN** PM пишет боту «в PAY: добавить экспорт в CSV» и нажимает «Создать»
+- **THEN** в бэклоге PAY появляется стори «добавить экспорт в CSV»
+- **AND** бот предлагает «Взять в работу»
+
+#### Scenario: Выбор проекта и эпика
+- **GIVEN** у PM два проекта, в «PAY» есть эпик «Отчёты»
+- **WHEN** PM пишет боту «экспорт в CSV», выбирает «PAY», затем «Отчёты»
+- **THEN** стори создана в PAY с эпиком «Отчёты»
+
+#### Scenario: Взять в работу
+- **WHEN** PM нажимает «Взять в работу» под созданной стори
+- **THEN** стори «В работе», агент запущен
+
+#### Scenario: Голосовое
+- **GIVEN** расшифровка голоса настроена
+- **WHEN** PM присылает голосовое «в PAY добавить экспорт»
+- **THEN** бот показывает расшифровку и предлагает создать стори в PAY
+
+#### Scenario: Чужой проект
+- **WHEN** пользователь пишет «в SEC: …», а к проекту SEC у него нет доступа
+- **THEN** проект SEC не предлагается и стори в нём не создаётся
diff --git a/openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md b/openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md
new file mode 100644
index 00000000..c32f67cf
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md
@@ -0,0 +1,6 @@
+# Tasks: PEP-45
+
+- [x] 1.1 Бот: черновик из текста (разбор `KEY:`), кнопки проекта/эпика, создание, «Взять в работу»
+- [x] 1.2 Голос: `getFile` + скачивание, `transcribe.ts` (OpenAI-совместимый API, env)
+- [x] 1.3 testkit: голос и файлы в `mock-telegram`, `mock-transcribe`, тесты в `bot.test.ts`
+- [x] 1.4 AGENTS.md, «Помощь», HELP бота, `openspec validate`
diff --git a/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/design.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/design.md
new file mode 100644
index 00000000..04118a5f
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/design.md
@@ -0,0 +1,20 @@
+# Design: PEP-46
+
+## Определение события
+`/api/hooks/gitea` передаёт `X-Gitea-Event`. Обработчик смотрит на payload, а не на имя:
+- `comment` + `issue` → комментарий (`issue.pull_request` или `is_pull` → комментарий в PR);
+- `review` + `pull_request` → ревью (`review.type` содержит `approved` → игнор);
+- `pull_request` + `action` → событие PR (`closed` + `merged` → мерж);
+- `issue` без `comment` → событие issue (`opened`/`reopened` → импорт).
+
+## Доступ
+Отправитель (`sender.login`) сопоставляется с пользователем Пеппы по логину Gitea
+(`users.gitea_id > 0`), затем `projectForUser`. Локальные пользователи (PEP-68) логина
+Gitea не имеют. peppa-bot (`GITEA_BOT_LOGIN`, по умолчанию `peppa-bot`) — всегда игнор,
+чтобы собственные комментарии Пеппы не возвращались агенту петлёй.
+
+## Мерж руками и гонка с «Принять»
+`acceptTask` мержит PR сам, и вебхук `closed/merged` может прийти раньше, чем
+`acceptTask` закроет вопрос. Обработчик закрывает только стори не в `done`, ответ на
+вопрос «готово к ревью» — `answerQuestion(...).catch()`; в `acceptTask` закрытие вопроса
+после мержа тоже терпит «уже отвечено».
diff --git a/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/proposal.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/proposal.md
new file mode 100644
index 00000000..67610026
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/proposal.md
@@ -0,0 +1,35 @@
+# PEP-46: Интеграция с Gitea — вебхуки, issues и комментарии в PR
+
+## Зачем
+Пеппа не знает, что происходит в Gitea, кроме проверок CI (PEP-57): комментарий человека
+в PR агент не видит, мерж руками не закрывает стори, issues живут отдельно от бэклога.
+
+## Что меняется
+- **Вебхук проекта** подписан ещё на `issues`, `issue_comment`, `pull_request_comment`,
+ `pull_request_review` (`setupCi` обновляет существующий хук). Обработчики — через
+ `onGiteaEvent` (runner/gitea-events.ts); тип события определяется по форме payload
+ (Gitea 1.22 шлёт одно и то же имя `pull_request_comment` и для комментария, и для ревью).
+- **Issue → стори.** Открытый issue от пользователя с доступом к проекту (владелец или
+ участник, логин Gitea) становится стори в бэклоге (`tasks.gitea_issue`, идемпотентно);
+ peppa-bot пишет в issue комментарий со ссылкой на стори. Чужие issues (публичный репо)
+ игнорируются — иначе любой аккаунт Gitea заводил бы стори, а авто-режим брал бы их в работу.
+ Разовый импорт уже открытых issues — `peppa project import-issues ` (решение PM =
+ доверие, без проверки автора).
+- **Стори готова → issue закрыт** с комментарием (PR стори), best effort.
+- **Комментарий/ревью «нужны изменения» в PR стори** от человека с доступом уходит агенту
+ стори: в живой раннер или новым раннером (как красный CI), стори из «Ревью» возвращается
+ «В работу». Одобрение и комментарии peppa-bot игнорируются. Комментарий в issue стори —
+ только в живой раннер.
+- **PR стори смержен руками в Gitea** → стори «Готово», раннер остановлен, «готово к
+ ревью» закрыт, рабочая копия синхронизирована. `acceptTask` терпит, что вебхук закрыл
+ вопрос раньше.
+- **Красный CI → агенту** — уже есть (PEP-57).
+- Карточка стори и MCP `get_task` показывают ссылку на issue.
+
+## Влияние
+- БД: `tasks.gitea_issue` (миграция). Gitea-клиент: issues (список, комментарий, закрытие).
+- runner: `gitea-events.ts`, `flow.ts` (done → закрыть issue; acceptTask), `ci.ts` (события хука).
+- CLI `peppa project import-issues`. testkit: issues и комментарии в `mock-gitea`,
+ `gitea-events.test.ts`.
+- Реальная интеграция: после выкатки — `peppa ci connect ` (или пересоздание проекта),
+ чтобы обновить подписку вебхука на новые события.
diff --git a/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/specs/gitea-integration/spec.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/specs/gitea-integration/spec.md
new file mode 100644
index 00000000..e0333aa1
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/specs/gitea-integration/spec.md
@@ -0,0 +1,41 @@
+## ADDED Requirements
+
+### Requirement: Issues становятся стори
+Открытый в репозитории проекта issue от пользователя с доступом к проекту SHALL становиться стори в бэклоге со ссылкой на issue, а issue SHALL получать комментарий со ссылкой на стори. Issue от пользователя без доступа SHALL игнорироваться. Когда стори готова, связанный issue SHALL закрываться.
+
+#### Scenario: Участник открыл issue
+- **GIVEN** проект «PAY», владелец которого вошёл через Gitea как «pm»
+- **WHEN** «pm» открывает issue «Экспорт в CSV» в репозитории PAY
+- **THEN** в бэклоге PAY появляется стори «Экспорт в CSV» со ссылкой на issue
+- **AND** в issue появляется комментарий со ссылкой на стори
+
+#### Scenario: Чужой issue
+- **GIVEN** публичный репозиторий проекта «PAY»
+- **WHEN** issue открывает пользователь Gitea без доступа к PAY
+- **THEN** стори не создаётся
+
+#### Scenario: Стори готова
+- **GIVEN** стори PAY-7, созданная из issue #3
+- **WHEN** PAY-7 переходит в «Готово»
+- **THEN** issue #3 закрыт с комментарием
+
+### Requirement: Комментарии в PR уходят агенту
+Комментарий или ревью «нужны изменения» в PR стори от пользователя с доступом SHALL доставляться агенту стори; стори из «Ревью» SHALL возвращаться «В работу». Одобрения и комментарии самой Пеппы SHALL игнорироваться.
+
+#### Scenario: Комментарий в PR
+- **GIVEN** стори PAY-7 в «Ревью» с открытым PR
+- **WHEN** «pm» пишет в PR комментарий «Переименуй кнопку»
+- **THEN** агент PAY-7 получает текст комментария
+- **AND** PAY-7 снова «В работе»
+
+#### Scenario: Комментарий бота
+- **WHEN** комментарий в PR оставляет peppa-bot
+- **THEN** агенту ничего не уходит
+
+### Requirement: Мерж руками закрывает стори
+Мерж PR стори в Gitea вручную SHALL переводить стори в «Готово» и останавливать её раннер.
+
+#### Scenario: PM смержил PR в Gitea
+- **GIVEN** стори PAY-7 в «Ревью» с открытым PR
+- **WHEN** PR смержен в интерфейсе Gitea
+- **THEN** PAY-7 в «Готово», сообщение «готово к ревью» закрыто
diff --git a/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/tasks.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/tasks.md
new file mode 100644
index 00000000..3fbd9771
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/tasks.md
@@ -0,0 +1,8 @@
+# Tasks: PEP-46
+
+- [x] 1.1 Схема `tasks.gitea_issue` + миграция; Gitea-клиент: issues, комментарий, закрытие; `GITEA_BOT_LOGIN`
+- [x] 1.2 runner `gitea-events.ts`: issue → стори, комментарий/ревью → агенту, мерж руками → done; регистрация через `onGiteaEvent`
+- [x] 1.3 `moveTask(done)` закрывает issue; `acceptTask` терпит закрытый вебхуком вопрос; события вебхука в `setupCi`
+- [x] 1.4 `importIssues` + CLI `peppa project import-issues`; issue в карточке и `get_task`
+- [x] 1.5 testkit: issues/комментарии в `mock-gitea`, `gitea-events.test.ts` по сценариям
+- [x] 1.6 AGENTS.md, «Помощь», `openspec validate`
diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md
index 9216d26f..a8478a75 100644
--- a/openspec/specs/delivery-pipeline/spec.md
+++ b/openspec/specs/delivery-pipeline/spec.md
@@ -111,3 +111,20 @@
- **GIVEN** проект, где PM не включал ревьюер
- **WHEN** агент переводит стори с зелёными проверками в «Ревью»
- **THEN** стори сразу в «Ревью», ревьюер не вызывается
+
+### Requirement: Превью на ревью
+Сообщение «готово к ревью» и карточка стори SHALL показывать ссылку на здоровый превью-стенд PR стори, ссылку на дифф и итог проверок; карточка SHALL показывать скриншоты стенда, снятые CI-шагом деплоя превью.
+
+#### Scenario: Стенд поднят
+- **GIVEN** стори PAY-7 с PR #3 и здоровым превью `pay-pr3.telecom.quest`
+- **WHEN** PAY-7 уходит в «Ревью»
+- **THEN** «готово к ревью» содержит «Посмотреть: https://pay-pr3.telecom.quest», ссылку на дифф и итог проверок
+
+#### Scenario: Скриншоты
+- **GIVEN** проект с `deploy.screenshots: ["/"]`
+- **WHEN** превью PR #3 поднялось здоровым
+- **THEN** CI-шаг присылает скриншот, он виден в карточке стори PAY-7
+
+#### Scenario: Скриншоты не сняты
+- **WHEN** снять скриншот не удалось
+- **THEN** превью всё равно здоровое, карточка показывает ссылку без скриншотов
diff --git a/openspec/specs/gitea-integration/spec.md b/openspec/specs/gitea-integration/spec.md
new file mode 100644
index 00000000..c7931608
--- /dev/null
+++ b/openspec/specs/gitea-integration/spec.md
@@ -0,0 +1,46 @@
+# gitea-integration Specification
+
+## Purpose
+Как Пеппа узнаёт о событиях в Gitea: issues становятся стори, комментарии и ревью в PR уходят агенту, мерж PR руками закрывает стори.
+
+## Requirements
+
+### Requirement: Issues становятся стори
+Открытый в репозитории проекта issue от пользователя с доступом к проекту SHALL становиться стори в бэклоге со ссылкой на issue, а issue SHALL получать комментарий со ссылкой на стори. Issue от пользователя без доступа SHALL игнорироваться. Когда стори готова, связанный issue SHALL закрываться.
+
+#### Scenario: Участник открыл issue
+- **GIVEN** проект «PAY», владелец которого вошёл через Gitea как «pm»
+- **WHEN** «pm» открывает issue «Экспорт в CSV» в репозитории PAY
+- **THEN** в бэклоге PAY появляется стори «Экспорт в CSV» со ссылкой на issue
+- **AND** в issue появляется комментарий со ссылкой на стори
+
+#### Scenario: Чужой issue
+- **GIVEN** публичный репозиторий проекта «PAY»
+- **WHEN** issue открывает пользователь Gitea без доступа к PAY
+- **THEN** стори не создаётся
+
+#### Scenario: Стори готова
+- **GIVEN** стори PAY-7, созданная из issue #3
+- **WHEN** PAY-7 переходит в «Готово»
+- **THEN** issue #3 закрыт с комментарием
+
+### Requirement: Комментарии в PR уходят агенту
+Комментарий или ревью «нужны изменения» в PR стори от пользователя с доступом SHALL доставляться агенту стори; стори из «Ревью» SHALL возвращаться «В работу». Одобрения и комментарии самой Пеппы SHALL игнорироваться.
+
+#### Scenario: Комментарий в PR
+- **GIVEN** стори PAY-7 в «Ревью» с открытым PR
+- **WHEN** «pm» пишет в PR комментарий «Переименуй кнопку»
+- **THEN** агент PAY-7 получает текст комментария
+- **AND** PAY-7 снова «В работе»
+
+#### Scenario: Комментарий бота
+- **WHEN** комментарий в PR оставляет peppa-bot
+- **THEN** агенту ничего не уходит
+
+### Requirement: Мерж руками закрывает стори
+Мерж PR стори в Gitea вручную SHALL переводить стори в «Готово» и останавливать её раннер.
+
+#### Scenario: PM смержил PR в Gitea
+- **GIVEN** стори PAY-7 в «Ревью» с открытым PR
+- **WHEN** PR смержен в интерфейсе Gitea
+- **THEN** PAY-7 в «Готово», сообщение «готово к ревью» закрыто
diff --git a/openspec/specs/telegram-notifications/spec.md b/openspec/specs/telegram-notifications/spec.md
index 0d25f8fe..51fe5e13 100644
--- a/openspec/specs/telegram-notifications/spec.md
+++ b/openspec/specs/telegram-notifications/spec.md
@@ -37,3 +37,30 @@ Telegram, и никому больше.
#### Scenario: Нет доступа
- **WHEN** пользователь без доступа к проекту присылает нажатие кнопки чужого вопроса
- **THEN** вопрос остаётся без ответа
+
+### Requirement: Стори из сообщения боту
+Привязанный пользователь SHALL создавать стори сообщением боту — текстом или голосом. Бот SHALL уточнять проект (если не указан и проектов несколько) и эпик кнопками, создавать стори только после нажатия кнопки и предлагать сразу взять её в работу. Проект SHALL выбираться только из доступных пользователю.
+
+#### Scenario: Текст с проектом
+- **GIVEN** PM с привязанным Telegram и проектом «PAY» без эпиков
+- **WHEN** PM пишет боту «в PAY: добавить экспорт в CSV» и нажимает «Создать»
+- **THEN** в бэклоге PAY появляется стори «добавить экспорт в CSV»
+- **AND** бот предлагает «Взять в работу»
+
+#### Scenario: Выбор проекта и эпика
+- **GIVEN** у PM два проекта, в «PAY» есть эпик «Отчёты»
+- **WHEN** PM пишет боту «экспорт в CSV», выбирает «PAY», затем «Отчёты»
+- **THEN** стори создана в PAY с эпиком «Отчёты»
+
+#### Scenario: Взять в работу
+- **WHEN** PM нажимает «Взять в работу» под созданной стори
+- **THEN** стори «В работе», агент запущен
+
+#### Scenario: Голосовое
+- **GIVEN** расшифровка голоса настроена
+- **WHEN** PM присылает голосовое «в PAY добавить экспорт»
+- **THEN** бот показывает расшифровку и предлагает создать стори в PAY
+
+#### Scenario: Чужой проект
+- **WHEN** пользователь пишет «в SEC: …», а к проекту SEC у него нет доступа
+- **THEN** проект SEC не предлагается и стори в нём не создаётся
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 4d4663df..6c5a20fb 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -52,7 +52,7 @@ import {
type TaskStatus,
} from "@peppa/core";
import { createDb, migrateDb } from "@peppa/db";
-import { answerAndDeliver, connectCi, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
+import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { loadEnv } from "@peppa/shared";
@@ -64,6 +64,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa project owner
peppa project autonomy [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes)
peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot)
+ peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
peppa project list
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
peppa release list [KEY]
@@ -232,6 +233,14 @@ async function main(): Promise {
console.log(`${p.key} owner → ${u?.login ?? "none"}`);
break;
}
+ case "project import-issues": {
+ if (!args[0]) throw new PeppaError("usage: peppa project import-issues ");
+ const p = await getProject(db, args[0]);
+ const out = await importIssues(db, p);
+ for (const r of out) console.log(`${r.key}${r.created ? " (new)" : ""}`);
+ console.log(`${out.filter((r) => r.created).length} imported, ${out.filter((r) => !r.created).length} already linked`);
+ break;
+ }
case "project visibility": {
const [first, second] = args;
const keys = opts.all ? (await listProjects(db)).map((p) => p.key) : first ? [first] : [];
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index 7d192808..b6ad2e06 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -58,6 +58,15 @@ export interface GiteaCombinedStatus {
sha: string;
statuses: GiteaCommitStatus[] | null;
}
+export interface GiteaIssue {
+ number: number;
+ title: string;
+ body?: string;
+ state: "open" | "closed";
+ html_url: string;
+ user?: { login: string };
+ pull_request?: unknown;
+}
export interface GiteaHook {
id: number;
type: string;
@@ -271,6 +280,25 @@ export class GiteaClient {
return this.request("POST", `${this.repoPath(owner, repo)}/hooks`, body);
}
+ /** Open issues (not pull requests), oldest first. */
+ async listOpenIssues(owner: string, repo: string): Promise {
+ const out: GiteaIssue[] = [];
+ for (let page = 1; page <= 10; page++) {
+ const batch = await this.request("GET", `${this.repoPath(owner, repo)}/issues?state=open&type=issues&limit=50&page=${page}`);
+ out.push(...batch.filter((i) => !i.pull_request));
+ if (batch.length < 50) break;
+ }
+ return out.sort((a, b) => a.number - b.number);
+ }
+
+ commentIssue(owner: string, repo: string, n: number, body: string) {
+ return this.request<{ id: number }>("POST", `${this.repoPath(owner, repo)}/issues/${n}/comments`, { body });
+ }
+
+ closeIssue(owner: string, repo: string, n: number) {
+ return this.request("PATCH", `${this.repoPath(owner, repo)}/issues/${n}`, { state: "closed" });
+ }
+
createTag(owner: string, repo: string, tag: string, target: string, message?: string) {
return this.request<{ name: string }>("POST", `${this.repoPath(owner, repo)}/tags`, { tag_name: tag, target, message });
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c67f3061..4f411fd0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -28,3 +28,4 @@ export * from "./digest.ts";
export * from "./autonomy.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
+export * from "./preview.ts";
diff --git a/packages/core/src/preview.ts b/packages/core/src/preview.ts
new file mode 100644
index 00000000..50481552
--- /dev/null
+++ b/packages/core/src/preview.ts
@@ -0,0 +1,55 @@
+// What the PM needs to review a story without a terminal (PEP-44): the preview stand of its
+// PR (deployed by the project's CD, PEP-57), the diff, the checks and the screenshots the CI
+// step took of the stand. Also the Gitea issue the story came from (PEP-46).
+import { releases, type Db } from "@peppa/db";
+import { loadEnv } from "@peppa/shared";
+import { and, desc, eq } from "drizzle-orm";
+import { taskCiSummary, taskPrNumber } from "./ci.ts";
+import type { TaskRef } from "./tasks.ts";
+
+export interface ReviewPreview {
+ /** https URL of the healthy preview stand of the story's PR. */
+ previewUrl: string | null;
+ /** The release behind it (screenshots are served by its id). */
+ releaseId: number | null;
+ /** Commit deployed to the stand. */
+ sha: string | null;
+ diffUrl: string | null;
+ /** "Проверки: 4 из 4 пройдены". */
+ checks: string;
+ screenshots: Array<{ n: number; path: string }>;
+ issueUrl: string | null;
+}
+
+export async function reviewPreview(db: Db, ref: TaskRef): Promise {
+ const pr = taskPrNumber(ref.project, ref.task.prUrl);
+ const [rel] = pr
+ ? await db
+ .select()
+ .from(releases)
+ .where(and(eq(releases.projectId, ref.project.id), eq(releases.env, "preview"), eq(releases.prNumber, pr), eq(releases.status, "healthy")))
+ .orderBy(desc(releases.id))
+ .limit(1)
+ : [];
+ const issueUrl = ref.task.giteaIssue
+ ? `${loadEnv().GITEA_URL.replace(/\/$/, "")}/${ref.project.giteaOwner}/${ref.project.giteaRepo}/issues/${ref.task.giteaIssue}`
+ : null;
+ return {
+ previewUrl: rel?.host ? `https://${rel.host}` : null,
+ releaseId: rel?.id ?? null,
+ sha: rel?.sha ?? null,
+ diffUrl: ref.task.prUrl ? `${ref.task.prUrl.replace(/\/$/, "")}/files` : null,
+ checks: (await taskCiSummary(db, ref)).label,
+ screenshots: (rel?.screenshots ?? []).map((s, n) => ({ n, path: s.path })),
+ issueUrl,
+ };
+}
+
+/** Lines for the "ready for review" message: look, diff, checks (empty parts left out). */
+export function reviewPreviewNote(p: ReviewPreview): string {
+ const lines: string[] = [];
+ if (p.previewUrl) lines.push(`👀 Посмотреть: ${p.previewUrl}${p.screenshots.length ? ` (скриншотов: ${p.screenshots.length} — в карточке)` : ""}`);
+ if (p.diffUrl) lines.push(`📄 Дифф: ${p.diffUrl}`);
+ if (p.checks) lines.push(`🧪 ${p.checks.charAt(0).toUpperCase()}${p.checks.slice(1)}`);
+ return lines.join("\n");
+}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 12b6cfdb..745d158b 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -8,6 +8,7 @@ import { incidentForTask, type Incident } from "./incidents.ts";
import { taskCiSummary, type CiSummary } from "./ci.ts";
import { latestReview, type CodeReview } from "./reviews.ts";
import { getAutonomy, type AutonomySettings } from "./autonomy.ts";
+import { reviewPreview, type ReviewPreview } from "./preview.ts";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@@ -137,6 +138,8 @@ export interface TaskDetails {
autonomy: AutonomySettings;
/** PM comments on the story (PEP-32), oldest first: the agent reads them in get_task. */
comments: StoryComment[];
+ /** Preview stand, diff, checks, screenshots, Gitea issue (PEP-44/46). */
+ preview: ReviewPreview;
}
export const COMMENT_EVENT = "pm_comment";
@@ -178,7 +181,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise
.orderBy(desc(events.id))
.limit(20);
const incident = await incidentForTask(db, ref.task.id);
- return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id) };
+ return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref) };
}
export interface NewQuestion {
diff --git a/packages/db/migrations/0007_calm_anthem.sql b/packages/db/migrations/0007_calm_anthem.sql
new file mode 100644
index 00000000..31aca708
--- /dev/null
+++ b/packages/db/migrations/0007_calm_anthem.sql
@@ -0,0 +1,3 @@
+ALTER TABLE `releases` ADD `screenshots` text DEFAULT '[]' NOT NULL;--> statement-breakpoint
+ALTER TABLE `tasks` ADD `gitea_issue` integer;--> statement-breakpoint
+CREATE UNIQUE INDEX `tasks_project_issue` ON `tasks` (`project_id`,`gitea_issue`);
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0007_snapshot.json b/packages/db/migrations/meta/0007_snapshot.json
new file mode 100644
index 00000000..e739eee2
--- /dev/null
+++ b/packages/db/migrations/meta/0007_snapshot.json
@@ -0,0 +1,2997 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "d8e80765-8ce2-47d6-b112-53bf26c85f84",
+ "prevId": "b6495e1a-6087-42fb-a94f-3e6942582651",
+ "tables": {
+ "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
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "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"
+ }
+ },
+ "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": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "subscription_pool_id": {
+ "name": "subscription_pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "projects_subscription_pool_id_subscription_pools_id_fk": {
+ "name": "projects_subscription_pool_id_subscription_pools_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "subscription_pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_outbox": {
+ "name": "push_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "urgency": {
+ "name": "urgency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_outbox_dedupe_key_unique": {
+ "name": "push_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_outbox_subscription_id_push_subscriptions_id_fk": {
+ "name": "push_outbox_subscription_id_push_subscriptions_id_fk",
+ "tableFrom": "push_outbox",
+ "tableTo": "push_subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_subscriptions": {
+ "name": "push_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "p256dh": {
+ "name": "p256dh",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_ok_at": {
+ "name": "last_ok_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_subscriptions_endpoint_unique": {
+ "name": "push_subscriptions_endpoint_unique",
+ "columns": [
+ "endpoint"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_subscriptions_user_id_users_id_fk": {
+ "name": "push_subscriptions_user_id_users_id_fk",
+ "tableFrom": "push_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "questions": {
+ "name": "questions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "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": {}
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "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": {}
+ },
+ "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
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_updates": {
+ "name": "telegram_updates",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "egov_iin": {
+ "name": "egov_iin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "egov_linked_at": {
+ "name": "egov_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_set_at": {
+ "name": "password_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "columns": [
+ "gitea_id"
+ ],
+ "isUnique": true
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "columns": [
+ "login"
+ ],
+ "isUnique": true
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "columns": [
+ "telegram_chat_id"
+ ],
+ "isUnique": true
+ },
+ "users_egov_iin_unique": {
+ "name": "users_egov_iin_unique",
+ "columns": [
+ "egov_iin"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json
index d8790d22..900dcfed 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -50,6 +50,13 @@
"when": 1794615712278,
"tag": "0006_rotation",
"breakpoints": true
+ },
+ {
+ "idx": 7,
+ "version": "6",
+ "when": 1794617253656,
+ "tag": "0007_calm_anthem",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index 85de53c7..84b5c49c 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -127,10 +127,12 @@ export const tasks = sqliteTable(
// PEP-57: red CI runs in a row (distinct head SHAs) since the last green one.
ciAttempts: integer("ci_attempts").notNull().default(0),
ciFailedSha: text("ci_failed_sha"),
+ // PEP-46: the Gitea issue of the project's repo this story came from (or is linked to).
+ giteaIssue: integer("gitea_issue"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
- (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)],
+ (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue)],
);
/** PEP-57: one deployment of a project to an environment (and its outcome). */
@@ -151,6 +153,8 @@ export const releases = sqliteTable("releases", {
reason: text("reason"),
runUrl: text("run_url"),
logTail: text("log_tail"),
+ // PEP-44: screenshots of a preview taken by the CI step (files under $PEPPA_HOME/screenshots).
+ screenshots: text("screenshots", { mode: "json" }).$type>().notNull().default([]),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts
index 6c489bc0..93244ddd 100644
--- a/packages/mcp/src/format.ts
+++ b/packages/mcp/src/format.ts
@@ -21,6 +21,8 @@ export function formatTask(d: TaskDetails): string {
`- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`,
];
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
+ if (d.preview?.issueUrl) lines.push(`- Issue Gitea: ${d.preview.issueUrl}`);
+ if (d.preview?.previewUrl) lines.push(`- Превью: ${d.preview.previewUrl}${d.preview.screenshots.length ? ` (скриншотов: ${d.preview.screenshots.length})` : ""}`);
lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`);
for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`);
if (d.review) {
diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts
index 8bf13aff..0c61d5fb 100644
--- a/packages/runner/src/ci-feedback.ts
+++ b/packages/runner/src/ci-feedback.ts
@@ -23,8 +23,9 @@ import { checkRuns, projects, tasks, type Db } from "@peppa/db";
import { and, eq, sql } from "drizzle-orm";
import { sendToSession } from "./sessions.ts";
import { moveTask } from "./flow.ts";
-import { recordRelease } from "./deploy.ts";
+import { recordRelease, recordScreenshots } from "./deploy.ts";
import { offerPlatformRelease } from "./platform-release.ts";
+import { handleGiteaEvent } from "./gitea-events.ts";
/** Red runs in a row after which the PM is asked instead of the agent. */
export const MAX_CI_ATTEMPTS = 3;
@@ -174,8 +175,19 @@ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ statu
});
return { status: 200, body: { ok: true, release: rel.id, status: rel.status } };
}
+ if (req.event === "screenshots") {
+ if (typeof payload.sha !== "string" || !Array.isArray(payload.shots)) return { status: 400, body: { error: "bad screenshots report" } };
+ const out = await recordScreenshots(db, project, {
+ sha: payload.sha,
+ prNumber: typeof payload.pr === "number" ? payload.pr : null,
+ shots: (payload.shots as Array<{ path?: unknown; png?: unknown }>).map((s) => ({ path: String(s.path ?? "/"), png: String(s.png ?? "") })),
+ });
+ return { status: 200, body: { ok: true, ...out } };
+ }
+ // PEP-46: issues, comments and reviews in PRs, PRs merged by hand.
+ const out = await handleGiteaEvent(db, project, payload);
for (const h of eventHandlers) await h(db, project, req.event, payload);
- return { status: 200, body: { ok: true } };
+ return { status: 200, body: { ok: true, ...out } };
}
/**
diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts
index 805d1854..acf82742 100644
--- a/packages/runner/src/ci.ts
+++ b/packages/runner/src/ci.ts
@@ -18,6 +18,9 @@ export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "dep
export const CI_BRANCH = "peppa/ci";
export const CI_SECRET_NAME = "PEPPA_CI_SECRET";
+/** Events the project webhook gets: PRs and pushes (PEP-57), issues, comments, reviews (PEP-46). */
+export const GITEA_HOOK_EVENTS = ["pull_request", "push", "issues", "issue_comment", "pull_request_comment", "pull_request_review"];
+
/** Where Gitea webhooks and CI reports reach Peppa. */
export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`;
@@ -66,7 +69,7 @@ export async function setupCi(db: Db, project: Project): Promise {
const secret = projectHookSecret(project.id);
await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret));
// PR and push events (preview stands, merges) — signed with the same secret.
- await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, ["pull_request", "push"]));
+ await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, GITEA_HOOK_EVENTS));
return { runner };
}
diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts
index b516cf09..6771c999 100644
--- a/packages/runner/src/deploy.ts
+++ b/packages/runner/src/deploy.ts
@@ -6,6 +6,9 @@ import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type Gi
import { projects, questions, releases, type Db } from "@peppa/db";
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { deployPlatform, isPlatform } from "./platform-release.ts";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { peppaHome } from "@peppa/shared";
export type Release = typeof releases.$inferSelect;
export type ReleaseEnv = Release["env"];
@@ -169,3 +172,55 @@ export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: s
}
return true;
}
+
+/** PEP-44: limits for screenshots sent by the CI step. */
+export const MAX_SCREENSHOTS = 6;
+export const MAX_SCREENSHOT_BYTES = 3 * 1024 * 1024;
+const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+export interface ScreenshotReport {
+ sha: string;
+ prNumber: number | null;
+ shots: Array<{ path: string; png: string }>;
+}
+
+const screenshotDir = (projectId: number) => join(peppaHome(), "screenshots", String(projectId));
+
+/**
+ * Screenshots of a preview stand (CI step after a healthy preview): PNG files under
+ * $PEPPA_HOME/screenshots//, listed on the preview release of that PR and commit.
+ * Not PNG, too big or too many → skipped. Returns how many were kept.
+ */
+export async function recordScreenshots(db: Db, project: Project, r: ScreenshotReport): Promise<{ release: number | null; saved: number }> {
+ const [rel] = await db
+ .select()
+ .from(releases)
+ .where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.sha, r.sha), r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined))
+ .orderBy(desc(releases.id))
+ .limit(1);
+ if (!rel) return { release: null, saved: 0 };
+ const dir = screenshotDir(project.id);
+ mkdirSync(dir, { recursive: true });
+ const kept: Array<{ path: string; file: string }> = [];
+ for (const [i, s] of r.shots.slice(0, MAX_SCREENSHOTS).entries()) {
+ const buf = Buffer.from(s.png ?? "", "base64");
+ if (buf.length < PNG_MAGIC.length || buf.length > MAX_SCREENSHOT_BYTES || !buf.subarray(0, 8).equals(PNG_MAGIC)) continue;
+ const file = `r${rel.id}-${i}.png`;
+ writeFileSync(join(dir, file), buf);
+ kept.push({ path: String(s.path ?? "/").slice(0, 200), file });
+ }
+ await db.update(releases).set({ screenshots: kept }).where(eq(releases.id, rel.id));
+ return { release: rel.id, saved: kept.length };
+}
+
+/** PNG bytes of screenshot `n` of a release (null when absent). Access is checked by the caller. */
+export async function releaseScreenshot(db: Db, releaseId: number, n: number): Promise<{ projectId: number; png: Buffer } | null> {
+ const [rel] = await db.select().from(releases).where(eq(releases.id, releaseId));
+ const s = rel?.screenshots[n];
+ if (!rel || !s || !/^r\d+-\d+\.png$/.test(s.file)) return null;
+ try {
+ return { projectId: rel.projectId, png: readFileSync(join(screenshotDir(rel.projectId), s.file)) };
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts
index abc9cf9e..932910ad 100644
--- a/packages/runner/src/flow.ts
+++ b/packages/runner/src/flow.ts
@@ -6,6 +6,8 @@ import { eq } from "drizzle-orm";
import { startSession, stopSession, type StartOptions } from "./sessions.ts";
import { mergeTaskPr } from "./ci-feedback.ts";
import { syncWorkspace } from "./workspace-sync.ts";
+import { closeLinkedIssue } from "./gitea-events.ts";
+import type { GiteaClient } from "@peppa/core";
export type BoardColumn = "backlog" | "in_progress" | "review" | "done";
@@ -35,7 +37,7 @@ export async function reviewGate(ref: TaskRef): Promise {
* started unless one is running. Into "review": only past the CI gate. Into
* "backlog"/"done": active sessions are stopped.
*/
-export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}): Promise<{ started?: number; stopped: number }> {
+export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}, gitea?: GiteaClient): Promise<{ started?: number; stopped: number }> {
const from = columnOf(ref.task.status);
let stopped = 0;
if (to === "in_progress") {
@@ -56,7 +58,11 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
stopped++;
}
}
+ // Fresh status: a webhook (PEP-46) may have finished the story since `ref` was read.
+ const [now] = to === "done" ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, ref.task.id)) : [];
if (from !== to || ref.task.status !== to) await updateTask(db, ref, { status: to });
+ // PEP-46: a finished story closes the Gitea issue it came from.
+ if (to === "done" && now && now.status !== "done") await closeLinkedIssue(ref, gitea);
return { stopped };
}
@@ -77,7 +83,8 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable {});
await moveTask(db, ref, "done");
// PEP-25: the merged main lands in the working copy (best effort, never fails the accept).
await syncWorkspace(db, ref).catch(() => {});
diff --git a/packages/runner/src/gitea-events.ts b/packages/runner/src/gitea-events.ts
new file mode 100644
index 00000000..f1030338
--- /dev/null
+++ b/packages/runner/src/gitea-events.ts
@@ -0,0 +1,203 @@
+// Gitea → Peppa (PEP-46): issues become stories, comments and "changes requested" reviews in
+// a story's PR go to its agent, a PR merged by hand in Gitea closes the story; a finished
+// story closes its issue. CI results are handled in ci-feedback.ts (PEP-57).
+//
+// Gitea 1.22 names review events and PR comments alike (`pull_request_comment`), so the kind
+// of event is taken from the payload shape, not from the header.
+import { answerQuestion, createTask, giteaForBot, listSessions, taskForCheck, type GiteaClient, type Project, type TaskRef } from "@peppa/core";
+import { events, projectMembers, questions, tasks, users, type Db } from "@peppa/db";
+import { formatTaskKey, loadEnv } from "@peppa/shared";
+import { and, eq, gt, isNull, sql } from "drizzle-orm";
+import { sendToSession } from "./sessions.ts";
+import { moveTask } from "./flow.ts";
+import { syncWorkspace } from "./workspace-sync.ts";
+
+type Payload = Record;
+interface GUser {
+ login?: string;
+ username?: string;
+}
+interface GIssue {
+ number: number;
+ title?: string;
+ body?: string;
+ html_url?: string;
+ user?: GUser;
+ pull_request?: unknown;
+}
+interface GPull {
+ number: number;
+ merged?: boolean;
+ html_url?: string;
+ head?: { ref?: string };
+}
+
+export type GiteaEventKind = "issue" | "issue_comment" | "pr_comment" | "review" | "pull_request" | "other";
+
+/** What a webhook is about, from the payload shape (Gitea 1.22 reuses event names). */
+export function giteaEventKind(p: Payload): GiteaEventKind {
+ if (p.comment && p.issue) return (p.issue as GIssue).pull_request || p.is_pull ? "pr_comment" : "issue_comment";
+ if (p.review && p.pull_request) return "review";
+ if (p.pull_request && p.action) return "pull_request";
+ if (p.issue && p.action) return "issue";
+ return "other";
+}
+
+const loginOf = (u: GUser | undefined) => (u?.login ?? u?.username ?? "").trim();
+const isBot = (login: string) => login.toLowerCase() === loadEnv().GITEA_BOT_LOGIN.toLowerCase();
+const webUrl = () => loadEnv().PEPPA_WEB_URL.replace(/\/$/, "");
+
+/** True when the Gitea login is a Peppa user (Gitea account) who owns or shares the project. */
+export async function giteaLoginHasAccess(db: Db, project: Project, login: string): Promise {
+ if (!login) return false;
+ const [u] = await db
+ .select({ id: users.id, disabledAt: users.disabledAt })
+ .from(users)
+ .where(and(sql`lower(${users.login}) = ${login.toLowerCase()}`, gt(users.giteaId, 0)));
+ if (!u || u.disabledAt) return false;
+ if (project.ownerId === u.id) return true;
+ const [m] = await db
+ .select({ id: projectMembers.userId })
+ .from(projectMembers)
+ .where(and(eq(projectMembers.projectId, project.id), eq(projectMembers.userId, u.id)));
+ return !!m;
+}
+
+async function logProjectEvent(db: Db, project: Project, type: string, payload: Record, taskId?: number) {
+ await db.insert(events).values({ projectId: project.id, taskId, type, payload });
+}
+
+export interface IssueImport {
+ key: string;
+ created: boolean;
+}
+
+/** Story for an issue (idempotent by issue number); peppa-bot links back from the issue. */
+export async function importIssue(db: Db, project: Project, issue: GIssue, gitea?: GiteaClient): Promise {
+ const [have] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.giteaIssue, issue.number)));
+ if (have) return { key: formatTaskKey(project.key, have.number), created: false };
+ const title = (issue.title ?? "").trim().slice(0, 200) || `Issue #${issue.number}`;
+ const body = (issue.body ?? "").trim();
+ const link = issue.html_url ?? `${loadEnv().GITEA_URL.replace(/\/$/, "")}/${project.giteaOwner}/${project.giteaRepo}/issues/${issue.number}`;
+ const ref = await createTask(db, { projectId: project.id, title, description: `${body ? `${body}\n\n` : ""}Issue Gitea: ${link}` });
+ await db.update(tasks).set({ giteaIssue: issue.number }).where(eq(tasks.id, ref.task.id));
+ await logProjectEvent(db, project, "issue_imported", { issue: issue.number, author: loginOf(issue.user) }, ref.task.id);
+ try {
+ await (gitea ?? giteaForBot()).commentIssue(project.giteaOwner, project.giteaRepo, issue.number, `Стори ${ref.key} в Пеппе: ${webUrl()}/t/${ref.key}`);
+ } catch {}
+ return { key: ref.key, created: true };
+}
+
+/** One-time import of the repo's open issues (the PM asked: no author check). */
+export async function importIssues(db: Db, project: Project, gitea: GiteaClient = giteaForBot()): Promise {
+ const out: IssueImport[] = [];
+ for (const i of await gitea.listOpenIssues(project.giteaOwner, project.giteaRepo)) out.push(await importIssue(db, project, i, gitea));
+ return out;
+}
+
+/** A finished story closes its issue with a comment (best effort). */
+export async function closeLinkedIssue(ref: TaskRef, gitea?: GiteaClient): Promise {
+ if (!ref.task.giteaIssue) return false;
+ try {
+ const c = gitea ?? giteaForBot();
+ await c.commentIssue(ref.project.giteaOwner, ref.project.giteaRepo, ref.task.giteaIssue, `✅ Стори ${ref.key} готова${ref.task.prUrl ? `: ${ref.task.prUrl}` : ""}.`);
+ await c.closeIssue(ref.project.giteaOwner, ref.project.giteaRepo, ref.task.giteaIssue);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const ACTIVE = ["proposing", "in_progress", "review", "blocked"];
+
+/** Text from a human in Gitea → the story's agent: live runner, else a new one (story back in work). */
+async function toAgent(db: Db, ref: TaskRef, text: string, restart: boolean): Promise<"agent" | "restarted" | "none"> {
+ const [s] = await listSessions(db, { active: true, taskId: ref.task.id });
+ if (s) {
+ try {
+ await sendToSession(db, s.id, text);
+ if (ref.task.status === "review") await moveTask(db, ref, "in_progress");
+ return "agent";
+ } catch {}
+ }
+ if (!restart) return "none";
+ await moveTask(db, ref, "in_progress", { prompt: text });
+ return "restarted";
+}
+
+async function taskByIssue(db: Db, project: Project, n: number): Promise {
+ const [t] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.giteaIssue, n)));
+ return t ? { project, task: t, key: formatTaskKey(project.key, t.number) } : null;
+}
+
+export interface GiteaEventOutcome {
+ kind: GiteaEventKind;
+ task?: string | null;
+ action: string;
+}
+
+/** Dispatches a Gitea webhook (other than CI reports) for a project. */
+export async function handleGiteaEvent(db: Db, project: Project, payload: Payload, gitea?: GiteaClient): Promise {
+ const kind = giteaEventKind(payload);
+ const sender = loginOf(payload.sender as GUser);
+ const action = String(payload.action ?? "");
+
+ if (kind === "issue") {
+ const issue = payload.issue as GIssue;
+ if (action !== "opened" && action !== "reopened") return { kind, action: "none" };
+ const author = loginOf(issue.user) || sender;
+ if (isBot(author)) return { kind, action: "none" };
+ if (!(await giteaLoginHasAccess(db, project, author))) return { kind, action: "no_access" };
+ const r = await importIssue(db, project, issue, gitea);
+ return { kind, task: r.key, action: r.created ? "imported" : "exists" };
+ }
+
+ if (kind === "pull_request") {
+ const pull = payload.pull_request as GPull;
+ if (action !== "closed" || !pull.merged) return { kind, action: "none" };
+ const ref = await taskForCheck(db, project, pull.head?.ref, pull.number ?? (payload.number as number));
+ if (!ref || ref.task.status === "done") return { kind, task: ref?.key ?? null, action: "none" };
+ // Merged by hand in Gitea (Peppa's own merges move the story to done right after).
+ for (const q of await db.select().from(questions).where(and(eq(questions.taskId, ref.task.id), isNull(questions.answeredAt), eq(questions.kind, "attention")))) {
+ await answerQuestion(db, q.id, `✅ PR смержен в Gitea${sender ? ` (${sender})` : ""}`, "system").catch(() => {});
+ }
+ await moveTask(db, ref, "done", {}, gitea); // also closes the story's issue
+ await syncWorkspace(db, ref).catch(() => {});
+ await logProjectEvent(db, project, "pr_merged_in_gitea", { pr: pull.number, by: sender }, ref.task.id);
+ return { kind, task: ref.key, action: "done" };
+ }
+
+ if (kind === "pr_comment" || kind === "review" || kind === "issue_comment") {
+ if (!sender || isBot(sender)) return { kind, action: "none" };
+ let ref: TaskRef | null;
+ let text: string;
+ if (kind === "review") {
+ const pull = payload.pull_request as GPull;
+ const review = payload.review as { type?: string; content?: string };
+ const type = `${review.type ?? ""} ${action}`.toLowerCase();
+ if (type.includes("approved")) return { kind, action: "none" };
+ const content = (review.content ?? "").trim();
+ if (!content) return { kind, action: "none" };
+ ref = await taskForCheck(db, project, pull.head?.ref, pull.number);
+ const verdict = type.includes("rejected") ? "просит изменений" : "оставил ревью";
+ text = `💬 ${sender} ${verdict} в PR #${pull.number}${pull.html_url ? ` (${pull.html_url}/files)` : ""}:\n\n${content}\n\nРазбери замечания (комментарии к строкам — в PR), исправь и запушь в ту же ветку.`;
+ } else {
+ if (action && action !== "created") return { kind, action: "none" };
+ const issue = payload.issue as GIssue;
+ const comment = payload.comment as { body?: string; html_url?: string };
+ const body = (comment.body ?? "").trim();
+ if (!body) return { kind, action: "none" };
+ ref = kind === "pr_comment" ? await taskForCheck(db, project, null, issue.number) : await taskByIssue(db, project, issue.number);
+ text =
+ kind === "pr_comment"
+ ? `💬 ${sender} в PR #${issue.number}${comment.html_url ? ` (${comment.html_url})` : ""}:\n\n${body}\n\nЭто замечание к стори: исправь и запушь в ту же ветку (или ответь, почему не нужно).`
+ : `💬 ${sender} в issue #${issue.number}:\n\n${body}`;
+ }
+ if (!ref || !ACTIVE.includes(ref.task.status)) return { kind, task: ref?.key ?? null, action: "none" };
+ if (!(await giteaLoginHasAccess(db, project, sender))) return { kind, task: ref.key, action: "no_access" };
+ const out = await toAgent(db, ref, text, kind !== "issue_comment");
+ await logProjectEvent(db, project, "gitea_comment", { from: sender, kind, delivered: out }, ref.task.id);
+ return { kind, task: ref.key, action: out };
+ }
+ return { kind, action: "none" };
+}
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index aeaf5104..7e3388ce 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -15,6 +15,8 @@ import {
latestReview,
pendingReview,
reviewNote,
+ reviewPreview,
+ reviewPreviewNote,
reviewRejections,
getSession,
logSessionEvent,
@@ -26,7 +28,7 @@ import {
type Question,
type SessionView,
} from "@peppa/core";
-import { createDb, tasks, type Db } from "@peppa/db";
+import { createDb, projects, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { peppaHome } from "@peppa/shared";
import { HOOK_WAIT_SEC, MAX_AUTO_NUDGES } from "./run-settings.ts";
@@ -204,7 +206,10 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
// PEP-26: what the reviewer agent said (approved, findings left after the limit, failed).
const settings = await getReviewSettings(db, task.projectId);
const note = settings.enabled ? reviewNote(await latestReview(db, task.id), (await reviewRejections(db, task.id)) >= settings.maxIterations) : "";
- await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${note ? `${note}\n\n` : ""}${text ?? ""}`.trim()));
+ // PEP-44: the preview stand, the diff and the checks — the PM reviews without a terminal.
+ const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId));
+ const look = project ? reviewPreviewNote(await reviewPreview(db, { project, task, key: s.taskKey ?? "" }).catch(() => ({ previewUrl: null, releaseId: null, sha: null, diffUrl: null, checks: "", screenshots: [], issueUrl: null }))) : "";
+ await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${note ? `${note}\n\n` : ""}${text ?? ""}`.trim()));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index 361dd829..3d6ab1fd 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -25,3 +25,4 @@ export * from "./autonomy.ts";
export * from "./workspace-sync.ts";
export * from "./rotation.ts";
export * from "./live.ts";
+export * from "./gitea-events.ts";
diff --git a/packages/runner/src/reviewer.ts b/packages/runner/src/reviewer.ts
index 4ef8f12e..c12cc2f4 100644
--- a/packages/runner/src/reviewer.ts
+++ b/packages/runner/src/reviewer.ts
@@ -16,6 +16,8 @@ import {
raiseSessionQuestion,
resolveTask,
reviewNote,
+ reviewPreview,
+ reviewPreviewNote,
reviewRejections,
reviewsToRun,
taskPrNumber,
@@ -208,7 +210,8 @@ export async function processReview(db: Db, id: number, gitea: GiteaClient = git
}
await updateTask(db, fresh, { status: "review" });
- const msg = `✅ Стори ${fresh.key} готова к ревью${fresh.task.prUrl ? ` · PR: ${fresh.task.prUrl}` : ""}\n\n${reviewNote(review)}`.slice(0, 3500);
+ const look = reviewPreviewNote(await reviewPreview(db, fresh));
+ const msg = `✅ Стори ${fresh.key} готова к ревью${fresh.task.prUrl ? ` · PR: ${fresh.task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${reviewNote(review)}`.slice(0, 3500);
const [s] = sessionId ? await listSessions(db, { active: true, taskId: fresh.task.id }) : [];
// Still in the turn that asked for review: its Stop hook sends "ready for review" with this
// note (OpenCode has no turn hooks — it gets the message now).
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index c89a733b..0a5c8877 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -9,6 +9,8 @@ const schema = z.object({
GITEA_URL: z.string().url().default("https://git.telecom.quest"),
GITEA_TOKEN: z.string().optional(),
GITEA_TEMPLATE_REPO: z.string().default("peppa-bot/template"),
+ // PEP-46: Peppa's own Gitea account — its comments in PRs/issues never go back to agents.
+ GITEA_BOT_LOGIN: z.string().default("peppa-bot"),
PEPPA_WORKSPACES: z.string().default("~/peppa/workspaces"),
TELEGRAM_BOT_TOKEN: z.string().optional(),
TELEGRAM_PM_CHAT_ID: z.string().optional(),
diff --git a/packages/testkit/bin/mock-docker b/packages/testkit/bin/mock-docker
index 0a37532d..eef55e1b 100755
--- a/packages/testkit/bin/mock-docker
+++ b/packages/testkit/bin/mock-docker
@@ -2,7 +2,7 @@
# mock-docker — stands in for the docker CLI in .gitea/peppa-deploy.sh tests (first on PATH).
# Same calls and exit codes as the script uses from real docker; state lives in
# $MOCK_DOCKER_STATE: images (one tag per line), containers/ (its image), calls.log.
-# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail.
+# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail; MOCK_DOCKER_SCREENSHOT_FAIL=1 — `docker run` (screenshot).
set -uo pipefail
st="${MOCK_DOCKER_STATE:?MOCK_DOCKER_STATE is required}"
mkdir -p "$st/containers"
@@ -31,5 +31,11 @@ case "$1" in
down) rm -f "$st/containers/$project-"*; echo "Removed $project" ;;
run) echo "ran in $IMAGE: ${*: -1}" ;;
esac ;;
+ run) # PEP-44: docker run … -c '' _ → base64 PNG on stdout
+ url="${@: -1}"
+ echo "$url" >> "$st/screenshots.log"
+ [[ -n "${MOCK_DOCKER_SCREENSHOT_FAIL:-}" ]] && { echo "mock screenshot failed" >&2; exit 1; }
+ # 1x1 transparent PNG
+ printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=' ;;
*) echo "mock-docker: unsupported: $*" >&2; exit 1 ;;
esac
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index 112c52b6..acdc608c 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -22,6 +22,17 @@ interface MockRepo {
secrets: Record;
hooks: Array<{ id: number; url: string; secret: string; events: string[] }>;
tags: Array<{ name: string; target: string }>;
+ issues: MockIssue[];
+}
+
+/** PEP-46: an issue with its comments (by login). */
+export interface MockIssue {
+ number: number;
+ title: string;
+ body: string;
+ state: "open" | "closed";
+ author: string;
+ comments: Array<{ body: string; author: string }>;
}
export interface MockPull {
@@ -116,6 +127,7 @@ export class MockGitea {
secrets: {},
hooks: [],
tags: [],
+ issues: [],
private: opts.private ?? true,
};
this.repos.set(`${owner}/${name}`, repo);
@@ -173,6 +185,18 @@ export class MockGitea {
return pr;
}
+ /** An issue opened by `author` (numbers start at 100: apart from PR numbers). */
+ addIssue(owner: string, name: string, title: string, author: string, body = ""): MockIssue {
+ const r = this.repo(owner, name);
+ const i: MockIssue = { number: 100 + r.issues.length, title, body, state: "open", author, comments: [] };
+ r.issues.push(i);
+ return i;
+ }
+
+ issueJson(r: MockRepo, i: MockIssue) {
+ return { number: i.number, title: i.title, body: i.body, state: i.state, html_url: `${this.url}/${r.owner}/${r.name}/issues/${i.number}`, user: { login: i.author } };
+ }
+
/** Records a commit status, like a CI job does. */
setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string } = {}) {
const r = this.repo(owner, name);
@@ -433,6 +457,29 @@ export class MockGitea {
return { status: 404, body: { message: "not found" } };
}
}
+ if (method === "GET" && sub === "issues") {
+ const page = Number(q.get("page") ?? 1);
+ const limit = Number(q.get("limit") ?? 30);
+ const list = r.issues.filter((i) => (q.get("state") ?? "open") === "all" || i.state === (q.get("state") ?? "open"));
+ return { status: 200, body: list.slice((page - 1) * limit, page * limit).map((i) => this.issueJson(r, i)) };
+ }
+ if ((m = sub.match(/^issues\/(\d+)(\/comments)?$/))) {
+ const n = Number(m[1]);
+ const i = r.issues.find((x) => x.number === n);
+ const isPull = r.pulls.some((p) => p.number === n);
+ if (!i && !isPull) return { status: 404, body: { message: "issue not found" } };
+ if (method === "POST" && m[2]) {
+ const c = { body: String(body.body), author: me.login };
+ if (i) i.comments.push(c);
+ return { status: 201, body: { id: this.seq++, body: c.body, user: { login: me.login } } };
+ }
+ if (method === "PATCH" && !m[2] && i) {
+ if (!canWrite) return { status: 403, body: { message: "forbidden" } };
+ if (body.state === "closed" || body.state === "open") i.state = body.state;
+ return { status: 201, body: this.issueJson(r, i) };
+ }
+ if (method === "GET" && !m[2] && i) return { status: 200, body: this.issueJson(r, i) };
+ }
if (method === "POST" && sub === "tags") {
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
const target = this.sha(r.owner, r.name, String(body.target));
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index aad39524..9b177f04 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -30,6 +30,8 @@ export class MockTelegram {
private waiters: Array<() => void> = [];
private failures: Array<{ method: string; code: number; retryAfter?: number }> = [];
private server: Server | null = null;
+ /** PEP-45: uploaded voice files by file_id (served at /file/bot/). */
+ private files = new Map();
url = "";
async start(port = 0): Promise {
@@ -37,6 +39,12 @@ export class MockTelegram {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", async () => {
+ if (req.method === "GET" && req.url!.startsWith(`/file/bot${this.token}/`)) {
+ const path = decodeURIComponent(req.url!.slice(`/file/bot${this.token}/`.length));
+ const f = [...this.files.values()].find((x) => x.path === path);
+ res.writeHead(f ? 200 : 404, { "Content-Type": "application/octet-stream" });
+ return res.end(f?.data ?? "");
+ }
if (req.url!.startsWith("/_mock/")) {
const r = this.inspect(req.method!, req.url!, body ? JSON.parse(body) : {});
res.writeHead(r.status, { "Content-Type": "application/json" });
@@ -107,6 +115,11 @@ export class MockTelegram {
m.edits++;
return { ok: true, result: { message_id: m.message_id } };
}
+ case "getFile": {
+ const f = this.files.get(String(p.file_id));
+ if (!f) return { ok: false, error_code: 400, description: "Bad Request: invalid file_id" };
+ return { ok: true, result: { file_id: p.file_id, file_unique_id: `u-${p.file_id}`, file_size: f.data.length, file_path: f.path } };
+ }
case "answerCallbackQuery":
this.callbackAnswers.push({ id: String(p.callback_query_id), text: p.text as string | undefined });
return { ok: true, result: true };
@@ -135,6 +148,20 @@ export class MockTelegram {
});
}
+ /** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */
+ userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) {
+ const fileId = `mock-voice-${this.nextMessageId}`;
+ this.files.set(fileId, { path: `voice/file_${this.nextMessageId}.oga`, data: audio });
+ return this.push({
+ message: {
+ message_id: this.nextMessageId++,
+ chat: { id: user.chatId, type: "private" },
+ from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
+ voice: { file_id: fileId, file_unique_id: `u-${fileId}`, duration, mime_type: "audio/ogg", file_size: audio.length },
+ },
+ });
+ }
+
/** User presses an inline button on a bot message. */
userClicks(user: MockTgUser, messageId: number, data: string) {
const id = `cb-${this.nextUpdateId}`;
diff --git a/packages/testkit/src/mock-transcribe.ts b/packages/testkit/src/mock-transcribe.ts
new file mode 100644
index 00000000..73af06d4
--- /dev/null
+++ b/packages/testkit/src/mock-transcribe.ts
@@ -0,0 +1,51 @@
+// Mock OpenAI-compatible speech-to-text (PEP-45): POST /v1/audio/transcriptions, multipart
+// `file` + `model` (+ `language`, `response_format`), Bearer key → {"text": "…"}, errors as
+// {"error": {"message"}} with 400/401 like OpenAI. "Speech" is the audio bytes as UTF-8
+// prefixed "MOCK-SPEECH:"; anything else transcribes to "" (silence).
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+
+export class MockTranscribe {
+ readonly key = "mock-transcribe-key";
+ readonly requests: Array<{ model: string; language: string | null; filename: string; bytes: number }> = [];
+ private server: Server | null = null;
+ url = "";
+
+ /** Audio that the mock "hears" as `text`. */
+ static speech(text: string): Buffer {
+ return Buffer.from(`MOCK-SPEECH:${text}`, "utf8");
+ }
+
+ async start(port = 0): Promise {
+ this.server = createServer(async (req, res) => {
+ const send = (status: number, body: unknown) => {
+ res.writeHead(status, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(body));
+ };
+ if (req.method !== "POST" || req.url !== "/v1/audio/transcriptions") return send(404, { error: { message: "not found" } });
+ if (req.headers.authorization !== `Bearer ${this.key}`) return send(401, { error: { message: "Incorrect API key provided" } });
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ let form: FormData;
+ try {
+ form = await new Request("http://x", { method: "POST", headers: { "content-type": String(req.headers["content-type"]) }, body: Buffer.concat(chunks) }).formData();
+ } catch {
+ return send(400, { error: { message: "Could not parse multipart form" } });
+ }
+ const file = form.get("file");
+ const model = form.get("model");
+ if (!(file instanceof Blob) || typeof model !== "string" || !model) return send(400, { error: { message: "file and model are required" } });
+ const bytes = Buffer.from(await file.arrayBuffer());
+ this.requests.push({ model, language: (form.get("language") as string | null) ?? null, filename: (file as File).name ?? "", bytes: bytes.length });
+ const s = bytes.toString("utf8");
+ send(200, { text: s.startsWith("MOCK-SPEECH:") ? s.slice("MOCK-SPEECH:".length) : "" });
+ });
+ await new Promise((r) => this.server!.listen(port, "127.0.0.1", r));
+ this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`;
+ return this;
+ }
+
+ async stop() {
+ await new Promise((r) => this.server?.close(() => r()) ?? r());
+ }
+}
diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts
index 41081929..8c736c12 100644
--- a/packages/testkit/test/bot.test.ts
+++ b/packages/testkit/test/bot.test.ts
@@ -5,6 +5,7 @@ import { after, before, describe, test } from "node:test";
// helpers must load first: it sets the isolated test env that runner modules read on load.
import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts";
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
+import { MockTranscribe } from "../src/mock-transcribe.ts";
import type { Bot } from "@peppa/bot";
const { createBot } = await import("@peppa/bot");
@@ -264,3 +265,116 @@ describe("staleness and reliability", () => {
assert.equal((await core.getQuestion(db, q.id)).answer, "используй v2");
});
});
+
+// PEP-45, spec telegram-notifications: «Стори из сообщения боту».
+describe("Стори из сообщения боту", () => {
+ const botMsg = (re: RegExp) => waitFor(`bot message ${re}`, async () => tg.botMessages(PM.chatId).filter((m) => re.test(m.text)).at(-1));
+ const button = (m: MockTgMessage, re: RegExp) => {
+ const b = m.reply_markup?.inline_keyboard.flat().find((x) => re.test(x.text));
+ assert.ok(b, `button ${re} in ${JSON.stringify(m.reply_markup)}`);
+ return b.callback_data!;
+ };
+ const storyByTitle = async (projectKey: string, title: string) => {
+ const proj = await core.getProject(db, projectKey);
+ return (await core.listTasks(db, { projectId: proj.id })).find((t) => t.title === title);
+ };
+
+ test("Scenario: Текст с проектом — «Создать», стори в бэклоге, предложение взять в работу", async () => {
+ const p = await project({ turns: [] });
+ tg.userSends(PM, `в ${p.key}: добавить экспорт в CSV`);
+ const ask = await botMsg(new RegExp(`Новая стори в ${p.key} : «добавить экспорт в CSV»`));
+ assert.equal(await storyByTitle(p.key, "добавить экспорт в CSV"), undefined, "nothing is created before the button");
+ tg.userClicks(PM, ask.message_id, button(ask, new RegExp(`Создать в ${p.key}`)));
+ await waitFor("created", async () => /Создал /.test(ask.text));
+ const t = await storyByTitle(p.key, "добавить экспорт в CSV");
+ assert.ok(t);
+ assert.equal(t.status, "backlog");
+ assert.match(t.description!, /Создано из Telegram \(mock-pm\)/);
+ assert.match(ask.text, new RegExp(`${t.key}`));
+ button(ask, /Взять в работу/);
+ tg.userClicks(PM, ask.message_id, button(ask, /Оставить в бэклоге/));
+ await waitFor("kept", async () => /В бэклоге/.test(ask.text) && ask.reply_markup?.inline_keyboard.length === 0);
+ assert.equal((await core.resolveTask(db, t.key)).task.status, "backlog");
+ });
+
+ test("Scenario: Выбор проекта и эпика", async () => {
+ await project({ turns: [] });
+ const p = await project({ turns: [] });
+ const proj = await core.getProject(db, p.key);
+ const epic = await core.createGoal(db, proj.id, "Отчёты");
+ tg.userSends(PM, "экспорт отчётов в xlsx");
+ const ask = await botMsg(/Новая стори «экспорт отчётов в xlsx»\nВ какой проект\?/);
+ tg.userClicks(PM, ask.message_id, button(ask, new RegExp(`^${p.key}$`)));
+ await waitFor("epic asked", async () => /Эпик\?/.test(ask.text));
+ button(ask, /Без эпика/);
+ tg.userClicks(PM, ask.message_id, button(ask, /^Отчёты$/));
+ await waitFor("created", async () => /Создал/.test(ask.text));
+ const t = await storyByTitle(p.key, "экспорт отчётов в xlsx");
+ assert.equal(t?.goalId, epic.id);
+ });
+
+ test("Scenario: Взять в работу — стори в работе, агент запущен", async () => {
+ const p = await project({ turns: [[{ say: "Беру стори." }]] });
+ tg.userSends(PM, `${p.key}: поправить опечатку`);
+ const ask = await botMsg(new RegExp(`Новая стори в ${p.key} : «поправить опечатку»`));
+ tg.userClicks(PM, ask.message_id, button(ask, /Создать/));
+ await waitFor("created", async () => /Создал/.test(ask.text));
+ const cb = tg.userClicks(PM, ask.message_id, button(ask, /Взять в работу/));
+ await waitFor("taken", async () => tg.callbackAnswers.find((a) => a.id === cb && /агент взялся/.test(a.text ?? "")));
+ const t = (await storyByTitle(p.key, "поправить опечатку"))!;
+ assert.equal(t.status, "in_progress");
+ const sessions = await core.listSessions(db, { active: true, taskId: t.id });
+ assert.equal(sessions.length, 1);
+ for (const s of sessions) await runner.stopSession(db, s.id);
+ });
+
+ test("Scenario: Голосовое — расшифровка и предложение создать стори; без настройки — просьба написать текстом", async () => {
+ const p = await project({ turns: [] });
+ tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`));
+ await botMsg(/Голосовые пока не настроены/);
+
+ const stt = await new MockTranscribe().start();
+ Object.assign(process.env, { PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key });
+ try {
+ tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`));
+ await botMsg(new RegExp(`Расслышал: «в ${p.key} добавить экспорт»`));
+ const ask = await botMsg(new RegExp(`Новая стори в ${p.key} : «добавить экспорт»`));
+ assert.deepEqual(stt.requests.at(-1), { model: "whisper-1", language: "ru", filename: stt.requests.at(-1)!.filename, bytes: MockTranscribe.speech(`в ${p.key} добавить экспорт`).length });
+ tg.userClicks(PM, ask.message_id, button(ask, /Создать/));
+ await waitFor("created", async () => /Создал/.test(ask.text));
+ assert.match((await storyByTitle(p.key, "добавить экспорт"))!.description!, /расшифровка голосового/);
+ // Silence → nothing to create.
+ tg.userSendsVoice(PM, Buffer.from("ogg-opus-noise"));
+ await botMsg(/Не разобрал ни слова/);
+ // Wrong key → the service error is shown, no draft.
+ process.env.PEPPA_TRANSCRIBE_KEY = "wrong";
+ tg.userSendsVoice(PM, MockTranscribe.speech("что-то"));
+ await botMsg(/Не получилось расшифровать голосовое \(расшифровка не удалась: 401/);
+ } finally {
+ delete process.env.PEPPA_TRANSCRIBE_URL;
+ delete process.env.PEPPA_TRANSCRIBE_KEY;
+ await stt.stop();
+ }
+ });
+
+ test("Scenario: Чужой проект — не предлагается и не создаётся", async () => {
+ setDefaultOwner(bobUser.id);
+ const sec = await project({ turns: [] });
+ setDefaultOwner(pmUser.id);
+ const secProj = await core.getProject(db, sec.key);
+ tg.userSends(PM, `в ${sec.key}: украсть данные`);
+ // The key isn't one of the PM's projects: the whole text is the story, the project is asked.
+ const ask = await botMsg(new RegExp(`Новая стори «в ${sec.key}: украсть данные»`));
+ assert.ok(!ask.reply_markup!.inline_keyboard.flat().some((b) => b.text === sec.key), "someone else's project is not offered");
+ const draft = button(ask, /Отмена/).split(":")[1];
+ const cb = tg.userClicks(PM, ask.message_id, `d:${draft}:p:${secProj.id}`);
+ await waitFor("refused", async () => tg.callbackAnswers.find((a) => a.id === cb && /Проект не найден/.test(a.text ?? "")));
+ tg.userClicks(PM, ask.message_id, button(ask, /Отмена/));
+ await waitFor("cancelled", async () => /Отменено/.test(ask.text));
+ assert.equal((await core.listTasks(db, { projectId: secProj.id })).length, 1, "only the helper's own story");
+ // A stranger's message is ignored altogether.
+ tg.userSends(STRANGER, "в PAY: что-нибудь");
+ await new Promise((r) => setTimeout(r, 500));
+ assert.ok(!tg.botMessages(STRANGER.chatId).some((m) => /Новая стори/.test(m.text)));
+ });
+});
diff --git a/packages/testkit/test/ci.test.ts b/packages/testkit/test/ci.test.ts
index 0e7db66c..83c93d59 100644
--- a/packages/testkit/test/ci.test.ts
+++ b/packages/testkit/test/ci.test.ts
@@ -65,7 +65,7 @@ describe("CI: connect a project", () => {
assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos");
const repo = gitea.repo(BOT.login, p.giteaRepo);
assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id));
- assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), ["pull_request", "push"]]]);
+ assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), runner.GITEA_HOOK_EVENTS]]);
assert.match(runner.giteaHookUrl(), /\/api\/hooks\/gitea$/);
assert.ok(r.prUrl?.endsWith("/pulls/1"));
const pr = repo.pulls[0]!;
diff --git a/packages/testkit/test/deploy.test.ts b/packages/testkit/test/deploy.test.ts
index 4b4edc3f..71d0d69e 100644
--- a/packages/testkit/test/deploy.test.ts
+++ b/packages/testkit/test/deploy.test.ts
@@ -239,3 +239,69 @@ describe("Проверка здоровья и откат", () => {
assert.equal((await releases(d.proj.id)).at(-1)!.reason, "сборка образа не удалась");
});
});
+
+// PEP-44, spec delivery-pipeline: «Превью на ревью».
+describe("Превью на ревью", () => {
+ async function storyWithPr(d: Awaited>, pr: number) {
+ const ref = await core.resolveTask(db, d.p.taskKey);
+ await core.updateTask(db, ref, { prUrl: `${gitea.url}/${d.proj.giteaOwner}/${d.proj.giteaRepo}/pulls/${pr}` });
+ return core.resolveTask(db, d.p.taskKey);
+ }
+
+ test("Scenario: Стенд поднят — ссылка «Посмотреть», дифф и проверки; Scenario: Скриншоты — снимок в карточке", async () => {
+ const d = await deployable();
+ const ref = await storyWithPr(d, 3);
+ const sha = d.merge(`${d.p.key}-1`);
+ const r = await d.run("preview", sha, { PEPPA_PR: "3" });
+ assert.equal(r.code, 0, r.out);
+ assert.match(r.out, /скриншот \/ снят/);
+ const [rel] = await releases(d.proj.id);
+ assert.equal(rel!.status, "healthy");
+ assert.equal(rel!.screenshots.length, 1);
+ assert.equal(rel!.screenshots[0]!.path, "/");
+ const shot = await runner.releaseScreenshot(db, rel!.id, 0);
+ assert.ok(shot && shot.png.subarray(1, 4).toString() === "PNG", "a PNG is kept");
+ assert.equal(shot!.projectId, d.proj.id);
+ assert.equal(await runner.releaseScreenshot(db, rel!.id, 5), null);
+
+ const p = await core.reviewPreview(db, ref);
+ assert.equal(p.previewUrl, `https://${d.proj.slug}-pr3.telecom.quest`);
+ assert.equal(p.releaseId, rel!.id);
+ assert.deepEqual(p.screenshots, [{ n: 0, path: "/" }]);
+ assert.match(p.diffUrl!, /\/pulls\/3\/files$/);
+ const note = core.reviewPreviewNote(p);
+ assert.match(note, new RegExp(`Посмотреть: https://${d.proj.slug}-pr3\\.telecom\\.quest`));
+ assert.match(note, /Дифф: .*\/pulls\/3\/files/);
+ assert.match(note, /Проверки/);
+ // The card (getTaskDetails) carries the same summary.
+ assert.equal((await core.getTaskDetails(db, ref)).preview.previewUrl, p.previewUrl);
+ });
+
+ test("Scenario: Скриншоты не сняты — превью здоровое, ссылка без скриншотов", async () => {
+ const d = await deployable();
+ const ref = await storyWithPr(d, 4);
+ const r = await d.run("preview", d.merge(`${d.p.key}-1`), { PEPPA_PR: "4", MOCK_DOCKER_SCREENSHOT_FAIL: "1" });
+ assert.equal(r.code, 0, r.out);
+ assert.match(r.out, /скриншот \/ не снят/);
+ const [rel] = await releases(d.proj.id);
+ assert.equal(rel!.status, "healthy");
+ assert.deepEqual(rel!.screenshots, []);
+ const p = await core.reviewPreview(db, ref);
+ assert.ok(p.previewUrl);
+ assert.deepEqual(p.screenshots, []);
+ });
+
+ test("screenshots are opt-out (deploy.screenshots: []) and only for previews; junk is not stored", async () => {
+ const d = await deployable({ compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz", screenshots: [] });
+ const sha = d.merge(`${d.p.key}-1`);
+ assert.equal((await d.run("preview", sha, { PEPPA_PR: "5" })).code, 0);
+ assert.equal((await d.run("staging", sha)).code, 0);
+ assert.ok(!d.calls().includes("docker run"), "no screenshot container started");
+ const [rel] = (await releases(d.proj.id)).filter((x) => x.env === "preview");
+ const out = await runner.recordScreenshots(db, d.proj, { sha, prNumber: 5, shots: [{ path: "/", png: Buffer.from("not a png").toString("base64") }] });
+ assert.deepEqual(out, { release: rel!.id, saved: 0 });
+ // Unsigned report is refused.
+ const bad = await runner.handleGiteaHook(db, { event: "screenshots", signature: "x", body: JSON.stringify({ repository: `${d.proj.giteaOwner}/${d.proj.giteaRepo}`, sha, shots: [] }) });
+ assert.equal(bad.status, 401);
+ });
+});
diff --git a/packages/testkit/test/gitea-events.test.ts b/packages/testkit/test/gitea-events.test.ts
new file mode 100644
index 00000000..7735e55a
--- /dev/null
+++ b/packages/testkit/test/gitea-events.test.ts
@@ -0,0 +1,190 @@
+// PEP-46, spec gitea-integration: «Issues становятся стори», «Комментарии в PR уходят агенту»,
+// «Мерж руками закрывает стори» — Gitea webhooks (signed like Gitea) against mock Gitea and
+// mock-claude runners.
+import assert from "node:assert/strict";
+import { createHmac } from "node:crypto";
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { core, db, project, runner, setDefaultOwner, teardown, type TestProject } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-gev-")), "gitea"));
+const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
+let pm: Awaited>;
+
+before(async () => {
+ await gitea.start();
+ process.env.GITEA_URL = gitea.url;
+ process.env.GITEA_TOKEN = BOT.token;
+ gitea.addUser(BOT);
+ pm = await core.upsertUserFromGitea(db, { id: 61, login: "mock-pm" }, { access_token: "x" });
+ setDefaultOwner(pm.id);
+});
+after(async () => {
+ await gitea.stop();
+ await teardown();
+});
+
+interface GitTask {
+ p: TestProject;
+ proj: Awaited>;
+ ref: () => ReturnType;
+ pr: number;
+ repo: string;
+ hook(event: string, payload: Record): ReturnType;
+}
+
+/** Project (owned by mock-pm) with a repo in mock Gitea and a story with an open PR. */
+async function gitTask(turns: Parameters[0]["turns"] = []): Promise {
+ const p = await project({ turns });
+ const proj = await core.getProject(db, p.key);
+ const pj = JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: "http://test" });
+ writeFileSync(join(p.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 branch = `task/${p.taskKey}`;
+ gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { "a.txt": "a" });
+ const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
+ const ref = () => core.resolveTask(db, p.taskKey);
+ await core.updateTask(db, await ref(), { status: "in_progress", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
+ const repo = `${proj.giteaOwner}/${proj.giteaRepo}`;
+ return {
+ p,
+ proj,
+ ref,
+ pr: pr.number,
+ repo,
+ hook(event, payload) {
+ const body = JSON.stringify({ repository: { full_name: repo }, ...payload });
+ const signature = createHmac("sha256", core.projectHookSecret(proj.id)).update(body).digest("hex");
+ return runner.handleGiteaHook(db, { event, signature, body });
+ },
+ };
+}
+
+const issuePayload = (t: GitTask, i: { number: number; title: string; body: string; author: string }, action = "opened") => ({
+ action,
+ number: i.number,
+ issue: { number: i.number, title: i.title, body: i.body, html_url: `${gitea.url}/${t.repo}/issues/${i.number}`, user: { login: i.author } },
+ sender: { login: i.author },
+});
+
+const prComment = (t: GitTask, from: string, body: string) => ({
+ action: "created",
+ is_pull: true,
+ issue: { number: t.pr, title: "PR", pull_request: { merged: false } },
+ comment: { body, user: { login: from }, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}#issuecomment-1` },
+ sender: { login: from },
+});
+
+const action = (r: Awaited>) => (r.body as { action: string }).action;
+
+describe("Issues становятся стори", () => {
+ test("Scenario: Участник открыл issue — стори в бэклоге со ссылкой, комментарий в issue", async () => {
+ const t = await gitTask();
+ const issue = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Экспорт в CSV", "mock-pm", "Нужна кнопка");
+ const r = await t.hook("issues", issuePayload(t, { ...issue, author: "mock-pm" }));
+ assert.equal(r.status, 200);
+ assert.equal(action(r), "imported");
+ const key = (r.body as { task: string }).task;
+ const story = await core.resolveTask(db, key);
+ assert.equal(story.task.title, "Экспорт в CSV");
+ assert.equal(story.task.status, "backlog");
+ assert.equal(story.task.giteaIssue, issue.number);
+ assert.match(story.task.description!, /Нужна кнопка[\s\S]*issues\/100/);
+ assert.equal(issue.comments.length, 1);
+ assert.equal(issue.comments[0]!.author, BOT.login);
+ assert.match(issue.comments[0]!.body, new RegExp(`Стори ${key} в Пеппе: .*/t/${key}`));
+ assert.match((await core.reviewPreview(db, story)).issueUrl!, /\/issues\/100$/);
+ // Redelivery (or "reopened") doesn't duplicate.
+ assert.equal(action(await t.hook("issues", issuePayload(t, { ...issue, author: "mock-pm" }, "reopened"))), "exists");
+ assert.equal(issue.comments.length, 1);
+ });
+
+ test("Scenario: Чужой issue — стори не создаётся; бот и подделка подписи тоже", async () => {
+ const t = await gitTask();
+ const before = (await core.listTasks(db, { projectId: t.proj.id })).length;
+ assert.equal(action(await t.hook("issues", issuePayload(t, { number: 100, title: "spam", body: "", author: "random-user" }))), "no_access");
+ assert.equal(action(await t.hook("issues", issuePayload(t, { number: 101, title: "bot", body: "", author: BOT.login }))), "none");
+ const forged = await runner.handleGiteaHook(db, { event: "issues", signature: "deadbeef", body: JSON.stringify({ repository: { full_name: t.repo }, ...issuePayload(t, { number: 102, title: "x", body: "", author: "mock-pm" }) }) });
+ assert.equal(forged.status, 401);
+ assert.equal((await core.listTasks(db, { projectId: t.proj.id })).length, before);
+ });
+
+ test("Scenario: Стори готова — issue закрыт с комментарием; разовый импорт открытых issues", async () => {
+ const t = await gitTask();
+ const a = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Старый баг", "someone");
+ const b = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Ещё один", "mock-pm");
+ const out = await runner.importIssues(db, t.proj);
+ assert.deepEqual(out.map((x) => x.created), [true, true]);
+ assert.deepEqual((await runner.importIssues(db, t.proj)).map((x) => x.created), [false, false]);
+ const story = await core.resolveTask(db, out[0]!.key);
+ await runner.moveTask(db, story, "done");
+ assert.equal(a.state, "closed");
+ assert.match(a.comments.at(-1)!.body, new RegExp(`Стори ${out[0]!.key} готова`));
+ assert.equal(b.state, "open");
+ });
+});
+
+describe("Комментарии в PR уходят агенту", () => {
+ test("Scenario: Комментарий в PR — агент получает текст, стори снова в работе", async () => {
+ const t = await gitTask([[{ say: "PR открыт" }], [{ say: "исправляю" }]]);
+ const id = await t.p.start();
+ await t.p.waitLog("agent started", (e) => e.ev === "prompt");
+ await core.updateTask(db, await t.ref(), { status: "review" });
+ const r = await t.hook("issue_comment", prComment(t, "mock-pm", "Переименуй кнопку"));
+ assert.equal(action(r), "agent");
+ await t.p.waitLog("comment delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("Переименуй кнопку") && String(e.prompt).includes("mock-pm"));
+ assert.equal((await t.ref()).task.status, "in_progress");
+ await runner.stopSession(db, id);
+ });
+
+ test("review «changes requested» with no live runner starts the agent; approval is ignored", async () => {
+ const t = await gitTask([[{ say: "чиню" }]]);
+ await core.updateTask(db, await t.ref(), { status: "review" });
+ const pull = { number: t.pr, merged: false, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}`, head: { ref: `task/${t.p.taskKey}` } };
+ assert.equal(action(await t.hook("pull_request_approved", { action: "reviewed", pull_request: pull, review: { type: "pull_request_review_approved", content: "LGTM" }, sender: { login: "mock-pm" } })), "none");
+ assert.equal((await t.ref()).task.status, "review");
+ const r = await t.hook("pull_request_rejected", { action: "reviewed", pull_request: pull, review: { type: "pull_request_review_rejected", content: "Нет тестов" }, sender: { login: "mock-pm" } });
+ assert.equal(action(r), "restarted");
+ await t.p.waitLog("review delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("Нет тестов") && String(e.prompt).includes("просит изменений"));
+ assert.equal((await t.ref()).task.status, "in_progress");
+ for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id);
+ });
+
+ test("Scenario: Комментарий бота — агенту ничего; чужой комментатор тоже", async () => {
+ const t = await gitTask();
+ await core.updateTask(db, await t.ref(), { status: "review" });
+ assert.equal(action(await t.hook("issue_comment", prComment(t, BOT.login, "Стори готова"))), "none");
+ assert.equal(action(await t.hook("issue_comment", prComment(t, "random-user", "сделай мне ещё"))), "no_access");
+ assert.equal((await t.ref()).task.status, "review");
+ assert.equal((await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })).length, 0);
+ });
+});
+
+describe("Мерж руками закрывает стори", () => {
+ test("Scenario: PM смержил PR в Gitea — стори «Готово», «готово к ревью» закрыто", async () => {
+ const t = await gitTask();
+ const ref = await t.ref();
+ await core.updateTask(db, ref, { status: "review" });
+ const q = await core.askPm(db, ref, { kind: "attention", text: `✅ Стори ${ref.key} готова к ревью` });
+ const pull = { number: t.pr, merged: true, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}`, head: { ref: `task/${t.p.taskKey}` } };
+ assert.equal(action(await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: { ...pull, merged: false }, sender: { login: "mock-pm" } })), "none");
+ assert.equal((await t.ref()).task.status, "review");
+ const r = await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: pull, sender: { login: "mock-pm" } });
+ assert.equal(action(r), "done");
+ assert.equal((await t.ref()).task.status, "done");
+ const closed = await core.getQuestion(db, q.id);
+ assert.ok(closed.answeredAt);
+ assert.match(closed.answer!, /смержен в Gitea/);
+ // A redelivery does nothing.
+ assert.equal(action(await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: pull, sender: { login: "mock-pm" } })), "none");
+ });
+
+ test("the project webhook subscribes to issues, comments and reviews", () => {
+ for (const e of ["issues", "issue_comment", "pull_request_comment", "pull_request_review", "pull_request", "push"]) assert.ok(runner.GITEA_HOOK_EVENTS.includes(e), e);
+ });
+});
diff --git a/template/.gitea/peppa-deploy.sh b/template/.gitea/peppa-deploy.sh
index 98eabe51..2586968f 100644
--- a/template/.gitea/peppa-deploy.sh
+++ b/template/.gitea/peppa-deploy.sh
@@ -83,6 +83,39 @@ healthy() {
return 1
}
+# PEP-44: скриншоты превью для ревью PM. Headless Chromium в контейнере в сети Traefik
+# (job сам в контейнере — PNG идёт через stdout в base64, без томов). Страницы —
+# deploy.screenshots (по умолчанию ["/"], [] — выключить). Сбой не валит деплой.
+screenshots() {
+ local peppa_url paths shots=() p url png body sig file
+ peppa_url=$(jq -r '.peppaUrl // empty' "$cfg")
+ [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]] || return 0
+ paths=()
+ while IFS= read -r p; do [[ -n "$p" ]] && paths+=("$p"); done < <(jq -r '(.deploy.screenshots // ["/"])[:6][]' "$cfg" 2>/dev/null)
+ ((${#paths[@]})) || return 0
+ local limit=()
+ command -v timeout >/dev/null && limit=(timeout "${PEPPA_SCREENSHOT_TIMEOUT:-90}")
+ local base="${PEPPA_SCREENSHOT_BASE:-${PEPPA_HEALTH_BASE:-http://$container:$port}}"
+ base="${base//\{project\}/$project}"
+ file=$(mktemp)
+ echo '[]' > "$file"
+ for p in "${paths[@]}"; do
+ url="$base$p"
+ png=$(${limit[@]+"${limit[@]}"} docker run --rm --network "${PEPPA_SCREENSHOT_NETWORK:-traefik_default}" --entrypoint sh \
+ "${PEPPA_SCREENSHOT_IMAGE:-zenika/alpine-chrome:124}" -c \
+ 'chromium-browser --headless --no-sandbox --disable-gpu --hide-scrollbars --window-size=1280,800 --virtual-time-budget=5000 --screenshot=/tmp/s.png "$1" >/dev/null 2>&1 && base64 /tmp/s.png | tr -d "\n"' _ "$url" 2>/dev/null) || png=""
+ if [[ -z "$png" ]]; then echo "peppa: скриншот $p не снят"; continue; fi
+ jq --arg path "$p" --rawfile png <(printf '%s' "$png") '. + [{path:$path, png:$png}]' "$file" > "$file.n" && mv "$file.n" "$file"
+ echo "peppa: скриншот $p снят"
+ done
+ [[ $(jq length "$file") -gt 0 ]] || return 0
+ body=$(jq -c --arg repo "${GITHUB_REPOSITORY:-}" --arg sha "$sha" --arg pr "$pr" '{repository:$repo, sha:$sha, pr:($pr|tonumber? // null), shots:.}' "$file")
+ sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}')
+ printf '%s' "$body" | curl -fsS -o /dev/null -m 60 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \
+ -H "X-Peppa-Event: screenshots" -H "X-Gitea-Signature: $sig" --data-binary @- || echo "peppa: скриншоты не отправлены"
+ rm -f "$file"
+}
+
if [[ $mode == preview-down ]]; then
dc "$image" down --remove-orphans || true
report removed
@@ -99,6 +132,7 @@ fi
dc "$image" up -d --remove-orphans || { report failed "docker compose up не удался"; exit 1; }
if healthy; then
report healthy
+ [[ $env_name == preview ]] && screenshots
docker image prune -af --filter "label=peppa.project=$slug" --filter "until=336h" >/dev/null 2>&1 || true
exit 0
fi