diff --git a/AGENTS.md b/AGENTS.md index 5828c4be..eca7ba56 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,8 @@ - Терминал в вебе (PEP-9): `runner/terminal.ts` — `TerminalFeed` опрашивает pane (`capture-pane -e` + `display-message`, 250 мс, один цикл на раннер для всех зрителей, `globalThis`), шлёт изменившиеся строки и ушедшие в историю; `terminalInput` (`send-keys -H` / `paste-buffer -p`; только владелец/участник, живая сессия, ≤1 КБ нажатий / 64 КБ вставки, 40 запросов за 5 с, сброс `auto_nudges`, событие `terminal_input` раз в минуту). Веб: `GET/POST /api/runners//terminal` (SSE + JSON, пинг 15 с для Cloudflare), `components/RunnerTerminal.tsx` (xterm.js); pane браузер не ресайзит - Шаги агента (PEP-33): хуки `PostToolUse`/`PostToolUseFailure` с `async: true` → `peppa-hook tool-use` → `recordStep` (core/steps.ts: событие `step` `{tool, kind, text, ok}`, последние 200 на сессию, `last_activity_at` без `notify()`); шаги исключены из журнала стори, `get_task` и «Событий» раннера; лента — `components/AgentSteps.tsx` (у живой сессии на странице стори и в панели раннера, новые шаги — событием `step` из `/api/live?scope=steps:`); прогресс tasks.md («7/12» и текущий пункт) — на карточках доски «В работе» и в шапке стори. Codex/OpenCode шагов не шлют - **Раннеры (PEP-10/27/53)**: настройки `core/runners.ts` с наследованием `platform.runner` → `project.runner:` → `task.runner:` (строки `settings`): `mode` story (по умолчанию, один раннер на стори) / queue, `context` fresh / continue, `workspace` shared / worktree, `maxRunners`. История и очередь — таблица `runner_tasks`, имя — `sessions.name`. `moveTask` → `startTaskOnRunner` (runner/runners.ts); переход к следующей стори и переезд очереди упавшего раннера — `runnerTick` в вачдоге; queue: «Готово» освобождает раннер (`releaseRunner`), fresh = `relaunchFresh` (тот же tmux, новое поколение без resume). Worktree — runner/worktree.ts (`$PEPPA_HOME/worktrees//s`, `sessions.workspace_path`, ветка `task/`, уборка когда чисто и всё запушено). Свободный раннер — `startFreeRunner` (без стори; хук не пингует), `promoteRunner` («Оформить стори»), `renameRunner`; CLI `peppa runner new|rename|promote|queue|show|settings` + - **Раннер-сервис (PEP-21)**: процессы агентов запускает только вачдог (`peppa watchdog` = раннер-сервис, `serveRunnerCommands` в runner/runner-service.ts). Веб (`instrumentation.ts`) и бот (`apps/bot/src/index.ts`) — клиенты (`setRunnerClient`, флаг в `globalThis`): функции жизненного цикла (`startSession`, `startFreeRunner`, `startTaskOnRunner`, `resumeSession`, `stopSession`, `sendToSession`, `moveTask`, `archiveTask`, `acceptTask`, `acceptStory`, `answerAndDeliver`, `queueTaskOnRunner`, `promoteRunner`) первой строкой уходят в `runnerCall` (runner/runner-client.ts): строка в `runner_commands` (payload — id, автор PEP-48 → `runAsActor` в сервисе) + пинок в `$PEPPA_HOME/runner.sock`, ожидание результата; изменяющие tmux-операции (`newSession`/`killSession`/`sendText`/`sendKeys`/`sendHex`) из прочих путей — командой `tmux` (payload стирается после выполнения). Ключ `task:`/`session:` — одна стори по очереди. Нет сокета → сразу ошибка «Раннер-сервис не запущен», не взял за 15 с (`PEPPA_RUNNER_PICKUP_SEC`) → `expired` и ошибка, поздно не выполняется; рестарт сервиса → `running` → `failed`. Тесты по умолчанию «на месте» (флаг ставят только бинари); `runAsRunnerService` — контекст сервиса в одном процессе с клиентом. `PEPPA_RUNNER_MODE=inline` — аварийный откат. CLI `session start|send|resume|stop`, `runner new|promote|queue`, `q answer` — через сервис, если он жив; `peppa runner commands`, `peppa status` + - **Вачдог 2.0 (PEP-28, runner/recovery.ts)**: пороги `platform.watchdog` ← env `PEPPA_WATCHDOG_*` ← умолчания (`peppa platform watchdog key=value|reset`: restartMax 3, restartWindowMin 1440, restartDelaysMin 1,5,15, stallRestartMin 60, remindMin 30, escalateMin 120, idleStopHours 24; 0 = выкл). Упал/пропал раннер стори в `proposing`/`in_progress` (не лимит, не пауза бюджета) → `failed` + `watch_state.restartAt` вместо вопроса, `restartTick` делает `resumeSession` (`auto_restarted`); предел исчерпан — вопрос PM с причиной. Зависший без ответа `stallRestartMin` после алерта — kill + перезапуск. `remindTick`: вопросы question/permission/approval моложе суток — напоминания аудитории (`questions.reminders` 1,2; событие `questions`), затем `alertAdmins` (3); claim атомарный. `idleStopTick`: `waiting_input` без открытых вопросов дольше `idleStopHours` → `stopSession` + сообщение. Память вачдога (хэш экрана, `limitGen`, `thresholdGen`, перезапуски, `stallAlertAt`) — `sessions.watch_state`, переживает рестарт - хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s-g/settings.json` (`claude --settings`) - `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется - PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux diff --git a/apps/bot/src/index.ts b/apps/bot/src/index.ts index 270725ed..594f6e49 100644 --- a/apps/bot/src/index.ts +++ b/apps/bot/src/index.ts @@ -1,6 +1,7 @@ // Entry point: `peppa-bot` (launchd agent quest.telecom.peppa.bot). import { createDb } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; +import { setRunnerClient } from "@peppa/runner"; import { createBot } from "./bot.ts"; import { TelegramApi } from "./telegram.ts"; @@ -9,8 +10,11 @@ if (!env.TELEGRAM_BOT_TOKEN) { console.error("TELEGRAM_BOT_TOKEN is not set"); process.exit(1); } +const db = createDb(env.PEPPA_DB); +// PEP-21: the bot only enqueues runner commands; the runner service (watchdog) runs them. +setRunnerClient(true, db); const bot = createBot({ - db: createDb(env.PEPPA_DB), + db, api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL), secret: env.TELEGRAM_BOT_TOKEN, webUrl: env.PEPPA_WEB_URL, diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts index 1d13f9ad..98b8e31e 100644 --- a/apps/web/instrumentation.ts +++ b/apps/web/instrumentation.ts @@ -1,8 +1,11 @@ -// Runs once when the Next server starts: the web's heartbeat for service monitoring (PEP-20). +// Runs once when the Next server starts: the web's heartbeat for service monitoring (PEP-20) +// and the runner-client mode (PEP-21): the web enqueues runner commands, the watchdog runs them. export async function register() { if (process.env.NEXT_RUNTIME !== "nodejs") return; const { beat } = await import("@peppa/core"); const { db } = await import("@/lib/db"); + const { setRunnerClient } = await import("@peppa/runner"); + setRunnerClient(true, db); const version = process.env.NEXT_PUBLIC_PEPPA_VERSION; const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`)); void tick(); diff --git a/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/design.md b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/design.md new file mode 100644 index 00000000..544e4930 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/design.md @@ -0,0 +1,65 @@ +# Design + +## Где живёт сервис +В процессе вачдога. Он и так единственный долгоживущий процесс, который уже запускает +раннеры (`runnerTick`, авто-resume, ротация), работает под launchd с `caffeinate`, и его +падение уже видит мониторинг PEP-20. Отдельный launchd-агент дал бы ещё одну точку отказа +без выигрыша; при нескольких машинах-раннерах каждая машина запустит свой `peppa watchdog` +(колонка `host` в `runner_commands` оставлена под это, сейчас всегда null = любой). + +## Транспорт: SQLite + unix-сокет +Как `notify()` у бота: данные — в БД (переживают рестарт обеих сторон), сокет — только +пинок, чтобы не ждать опроса. Сокет же — проверка живости: нет файла или +`ECONNREFUSED` — сервис не запущен, ошибка сразу, без 15 с ожидания. Клиент ждёт +результат опросом строки раз в 100 мс (дёшево для SQLite в WAL). + +Захват команды — `UPDATE … SET status='running' WHERE id=? AND status='queued'`; отказ +клиента — `UPDATE … SET status='expired' WHERE id=? AND status='queued'`. Обе стороны +атомарны, так что команда либо выполнится, либо гарантированно нет. + +## Два уровня перехвата +1. **Функции жизненного цикла** (`moveTask`, `startSession`, …) первой строкой проверяют + `isRunnerClient()` и уходят в `runnerCall`. Весь поток (БД + tmux) выполняется в + сервисе одним куском: рестарт веба посреди него ничего не ломает, а ключ + сериализации (`task:` / `session:`) убирает гонки двух процессов на одной стори. + Payload — простые id (TaskRef с датами по JSON не передаётся), результат — тоже id; + клиент перечитывает `SessionView` / `Question` / `TaskRef` из БД. +2. **Изменяющие операции tmux** — страховочная сетка: любой путь в клиенте, не покрытый + уровнем 1 (вебхук Gitea → красный CI в живой раннер, ввод в терминал PEP-9, ревьюер), + всё равно не трогает tmux сам. Чтение (`hasSession`, `capture-pane`) остаётся на месте — + оно не порождает процессов. Эти команды без ключа и выполняются сразу, параллельно. + +Флаг клиента — в `globalThis` (у Next инструментирование и server actions — разные бандлы +одного процесса). Флаг ставят только `instrumentation.ts` и бинарь бота: e2e-тесты, +где бот и раннер живут в одном процессе, по умолчанию остаются «на месте». + +## Автор действия (PEP-48) +Клиент кладёт `currentActor()` в команду, сервис выполняет обработчик под `runAsActor` — +журнал показывает того же автора, что и раньше. + +## Пределы ожидания +Взять команду — 15 с (`PEPPA_RUNNER_PICKUP_SEC`); выполнить — 120 с для потоков (`acceptTask` +мержит PR и синхронизирует копию), 15 с для tmux. После предела выполнения ошибка +честная: «команда ещё выполняется — результат появится на странице»; строку не отменяем. +Готовые команды старше суток удаляются тиком сервиса. + +## Вачдог 2.0 +`recovery.ts` — чистые решения + действия, вызываются из `checkSession` и `tick`: +- перезапуск: `watch_state.restarts` — метки времени; окно и предел из настроек; пауза + перед попыткой n — `[1, 5, 15]` мин (последняя повторяется). Только стори в `in_progress` + без паузы бюджета и не `rate_limited`; free-раннеры и сессии без стори — как раньше + (вопрос PM). Пока ждём паузу, сессия `failed` с `watch_state.restartAt`, вопрос не задан; + тик после `restartAt` делает `resumeSession`. Ручной resume/stop PM отменяет план. +- зависание: время алерта — `watch_state.stallAlertAt`; если вопрос всё ещё без ответа + через `stallRestartMin` — kill + перезапуск (засчитывается в предел). +- напоминания: колонка `questions.reminders` (0,1,2 — напоминания, 3 — эскалация). + Сообщение — `sendProjectMessage` (ключ `remind:q:`), эскалация — `alertAdmins` + (ключ `esc:q`). Не напоминаем о `awaitingHook`-вопросах младше их ожидания и о + вопросах без раннера старше суток (их и так закрывают). +- уборка `waiting_input`: `lastActivityAt` старше `idleStopHours`, нет открытых вопросов, + у сессии есть стори → `stopSession` + `sendProjectMessage`. +- состояние экрана: `watch_state = { screen, limitGen, thresholdGen, restarts, restartAt, + stallAlertAt }` вместо Map/Set в памяти. + +Настройки: `platform.watchdog` (JSON) поверх env `PEPPA_WATCHDOG_*` поверх умолчаний; +`restartMax=0` выключает авто-перезапуск. diff --git a/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/proposal.md b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/proposal.md new file mode 100644 index 00000000..b2cd07c2 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/proposal.md @@ -0,0 +1,65 @@ +# PEP-21 + PEP-28: раннер как отдельный сервис; вачдог 2.0 — авто-восстановление и эскалация + +## Why +Веб (server actions, вебхуки в `after()`), удалённый MCP и бот сами запускают и гасят tmux +в своём процессе. tmux-сервер наследует окружение того процесса, что поднял его первым, +рестарт веба посреди `moveTask` оставляет полузаписанное состояние, а два процесса, +одновременно двигающие одну стори, гоняются друг с другом. Нужен один владелец процессов +агентов — раннер-сервис, — а остальные только ставят ему команды; это же основа для +нескольких машин-раннеров. + +Вачдог при этом в основном сообщает: упавший раннер ждёт человека, неотвеченный вопрос +висит молча, сессия в `waiting_input` держит слот сутками, а то, что вачдог помнит об +экране (хэш, «уже сообщил о лимите»), теряется при его рестарте. + +## What Changes +- **Очередь команд раннера** — таблица `runner_commands` (kind, payload, ключ сериализации, + статус queued → running → done | failed | expired, результат/ошибка, автор). Раннер-сервис + живёт в процессе вачдога (`peppa watchdog`, тот же launchd-агент): слушает unix-сокет + `$PEPPA_HOME/runner.sock` (пинок «есть команда») и раз в 0,5 с смотрит таблицу; команды с + одним ключом (стори / раннер) выполняются по очереди, разные — параллельно. +- **Клиентский режим**: веб (`instrumentation.ts`) и бот (бинарь) объявляют себя клиентами + раннера. В клиенте функции жизненного цикла `@peppa/runner` (`startSession`, + `startFreeRunner`, `resumeSession`, `stopSession`, `sendToSession`, `moveTask`, + `archiveTask`, `acceptTask`, `acceptStory`, `answerAndDeliver`, `queueTaskOnRunner`, + `promoteRunner`) не выполняются на месте, а ставят команду и ждут результат; изменяющие + операции tmux (`newSession`, `killSession`, `sendText`, `sendKeys`, `sendHex`) из любых + прочих путей (вебхуки, ввод в терминал) — тоже через сервис. Код веба/бота/MCP не меняется. +- **Без тихих отказов**: сокет недоступен → сразу ошибка «Раннер-сервис не запущен…», + команда помечается `expired`; сервис не взял команду за 15 с → `expired` и ошибка; + выполняется дольше предела → ошибка «выполняется дольше обычного» (результат придёт + на страницу). Просроченная команда сервисом не выполняется (не будет запуска через час). + Рестарт сервиса посреди команды → `failed` с причиной. Ошибки домена (`PeppaError`) + доходят до клиента тем же текстом. `PEPPA_RUNNER_MODE=inline` — аварийный откат на + прежний запуск из процесса. +- **CLI**: `peppa session start|resume|stop|send` идут через сервис, если он жив, иначе + выполняются на месте с пометкой. `peppa runner commands` — последние команды; `peppa status` + показывает раннер-сервис. +- **Вачдог 2.0** (настройка `platform.watchdog` поверх env, CLI `peppa platform watchdog`): + - упавший раннер (код ≠ 0 или пропал tmux) стори «в работе» перезапускается сам + (`resumeSession`) — не больше `restartMax` (3) за `restartWindowMin` (24 ч), с паузой + 1 → 5 → 15 мин; исчерпан лимит — вопрос PM, как раньше; + - зависший раннер: после алерта, если PM молчит `stallRestartMin` (60) мин — + перезапуск по тем же правилам; + - неотвеченный вопрос: напоминание аудитории проекта через `remindMin` (30) мин, ещё раз + через столько же; после `escalateMin` (120) — эскалация админам платформы; дедуп по + ключам outbox и состоянию у вопроса; + - `waiting_input` без открытых вопросов дольше `idleStopHours` (24) — раннер стори + останавливается (разговор можно продолжить resume), PM получает сообщение; + - состояние вачдога по раннеру (хэш экрана, «лимит уже замечен», «порог уже замечен», + перезапуски) — в `sessions.watch_state` и переживает рестарт. + Лимиты (PEP-56), ротация (PEP-39) и бюджеты (PEP-43) не меняются: авто-перезапуск не + трогает `rate_limited` и стори на паузе бюджета. + +## Capabilities +- New: `runner-service`, `watchdog-recovery` + +## Impact +- Миграция `0011_runner_service`: таблица `runner_commands`, `sessions.watch_state`, + `questions.reminders`. +- `packages/runner/src/runner-client.ts` (клиент очереди), `runner-service.ts` (сервис и + реестр команд), `recovery.ts` (вачдог 2.0); guards в `sessions.ts`, `runners.ts`, + `flow.ts`, `tmux.ts`; `watchdog.ts` — состояние в БД. +- Веб `instrumentation.ts`, бот `bin` — клиентский режим; CLI. +- Живая система: после мержа — `peppa db backup && peppa db migrate`, затем перезапустить + вачдог раньше веба и бота (новый launchd-агент не нужен — сервис внутри вачдога). diff --git a/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/runner-service/spec.md b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/runner-service/spec.md new file mode 100644 index 00000000..00b8852c --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/runner-service/spec.md @@ -0,0 +1,60 @@ +## ADDED Requirements + +### Requirement: Процессы агентов запускает только раннер-сервис +Веб, бот и удалённый MCP SHALL NOT запускать, останавливать и вводить текст в tmux-сессии агентов в своём процессе; они ставят команду в очередь `runner_commands`, а выполняет её раннер-сервис (процесс вачдога). + +#### Scenario: PM двигает стори в работу из веба +- **GIVEN** раннер-сервис запущен +- **WHEN** PM переносит стори PEP-42 в «В работе» в вебе +- **THEN** в `runner_commands` появляется команда `move` от этого PM +- **AND** раннер-сервис выполняет её и запускает агента +- **AND** веб получает номер раннера, а журнал показывает автором PM через веб + +#### Scenario: Ответ на вопрос из Telegram +- **GIVEN** агент ждёт ответа PM +- **WHEN** PM отвечает в Telegram +- **THEN** ответ печатает в терминал агента раннер-сервис, а не бот + +#### Scenario: Вебхук Gitea с красной проверкой +- **WHEN** веб получает отчёт о красной проверке для стори с живым раннером +- **THEN** текст для агента отправляется в tmux через раннер-сервис + +### Requirement: Команды одной стори не гоняются +Раннер-сервис SHALL выполнять команды с одним ключом (стори или раннер) по очереди, а с разными — независимо. + +#### Scenario: Двойное «В работу» +- **WHEN** веб и бот почти одновременно двигают одну стори в работу +- **THEN** вторая команда выполняется после первой и видит уже запущенного агента +- **AND** второй агент не запускается + +### Requirement: Недоступный сервис — понятная ошибка +Если раннер-сервис не запущен или не взял команду за 15 секунд, клиент SHALL получить ошибку с причиной, а команда SHALL быть помечена просроченной и не выполняться позже. + +#### Scenario: Вачдог остановлен +- **GIVEN** раннер-сервис не запущен +- **WHEN** PM нажимает «Возобновить» у раннера +- **THEN** PM видит «Раннер-сервис не запущен (вачдог)… — команда не выполнена» +- **AND** команда в `runner_commands` имеет статус `expired` + +#### Scenario: Сервис завис +- **GIVEN** сокет сервиса отвечает, но команды он не берёт +- **WHEN** проходит 15 секунд +- **THEN** клиент получает ошибку «не взял команду за 15 с» +- **AND** когда сервис оживает, он эту команду не выполняет + +#### Scenario: Ошибка домена +- **WHEN** команда запуска падает с «Лимит раннеров проекта: 2» +- **THEN** PM видит тот же текст ошибки + +#### Scenario: Рестарт сервиса посреди команды +- **GIVEN** команда выполнялась, когда процесс вачдога перезапустился +- **WHEN** сервис стартует снова +- **THEN** команда помечена `failed` «раннер-сервис перезапустился во время выполнения» + +### Requirement: Аварийный режим на месте +При `PEPPA_RUNNER_MODE=inline` клиенты SHALL выполнять команды в своём процессе, как до PEP-21. + +#### Scenario: Откат +- **GIVEN** у веба `PEPPA_RUNNER_MODE=inline` +- **WHEN** PM запускает раннер +- **THEN** tmux запускается из процесса веба без очереди diff --git a/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/watchdog-recovery/spec.md b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/watchdog-recovery/spec.md new file mode 100644 index 00000000..e2cede8f --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/watchdog-recovery/spec.md @@ -0,0 +1,66 @@ +## ADDED Requirements + +### Requirement: Авто-перезапуск упавшего раннера +Вачдог SHALL сам перезапускать (resume) упавший раннер стори в работе не больше `restartMax` раз за `restartWindowMin`, с паузой 1, 5, 15 минут перед попытками, и только после исчерпания предела SHALL спрашивать PM. + +#### Scenario: Падение и восстановление +- **GIVEN** агент стори PEP-42 «в работе» упал с кодом 1 +- **WHEN** вачдог видит мёртвый pane +- **THEN** раннер получает статус `failed` и план перезапуска через 1 минуту, вопрос PM не задаётся +- **AND** через минуту вачдог делает resume того же разговора +- **AND** в журнале раннера событие `auto_restarted` с номером попытки + +#### Scenario: Предел исчерпан +- **GIVEN** раннер уже перезапускался 3 раза за сутки +- **WHEN** он падает снова +- **THEN** PM получает «Claude в PEP-42 упал (код 1)… авто-перезапуски исчерпаны (3 за 24 ч)» + +#### Scenario: Не трогаем лимит, бюджет и чужое +- **WHEN** упал раннер без стори, раннер стори не «в работе» или стори на паузе бюджета +- **THEN** авто-перезапуска нет, PM получает вопрос, как раньше + +#### Scenario: PM вмешался +- **GIVEN** перезапуск запланирован +- **WHEN** PM сам делает resume или stop +- **THEN** вачдог план не выполняет + +### Requirement: Зависший раннер перезапускается +Если PM не ответил на алерт о зависании `stallRestartMin` минут, вачдог SHALL перезапустить раннер по правилам авто-перезапуска. + +#### Scenario: Экран не меняется час +- **GIVEN** вачдог сообщил о зависании раннера PEP-42 +- **WHEN** проходит 60 минут без ответа и экран не изменился +- **THEN** tmux-сессия убита, раннер продолжает разговор заново, алерт закрыт + +### Requirement: Напоминание и эскалация вопросов +Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. + +#### Scenario: Вопрос висит +- **GIVEN** агент спросил PM в 10:00 +- **WHEN** в 10:30 ответа нет +- **THEN** участники проекта получают «⏰ Вопрос #N ждёт ответа 30 мин» +- **AND** в 11:00 — второе напоминание, в 12:00 — эскалация админам +- **AND** повторные тики вачдога новых сообщений не создают + +### Requirement: Уборка давних waiting_input +Раннер стори в `waiting_input` без открытых вопросов дольше `idleStopHours` SHALL останавливаться с сообщением PM. + +#### Scenario: Раннер ждёт сутки +- **GIVEN** раннер PEP-42 в `waiting_input` 25 часов и вопросов нет +- **WHEN** тикает вачдог +- **THEN** раннер остановлен, событие `idle_stopped`, PM получает сообщение, что его можно продолжить + +### Requirement: Состояние вачдога в БД +Хэш экрана и отметки «лимит/порог уже замечен» SHALL храниться у раннера в БД и переживать рестарт вачдога. + +#### Scenario: Рестарт вачдога +- **GIVEN** вачдог уже сообщил о лимите в поколении 3 +- **WHEN** вачдог перезапускается и снова видит баннер лимита на экране +- **THEN** повторного сообщения нет + +### Requirement: Настраиваемые пороги +Пороги SHALL задаваться `platform.watchdog` (CLI `peppa platform watchdog key=value`) поверх env `PEPPA_WATCHDOG_*`; `restartMax=0` выключает авто-перезапуск. + +#### Scenario: Выключить перезапуск +- **WHEN** админ выполняет `peppa platform watchdog restartMax=0` +- **THEN** упавший раннер сразу даёт вопрос PM diff --git a/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/tasks.md b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/tasks.md new file mode 100644 index 00000000..ce0be6f8 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-21-28-runner-service/tasks.md @@ -0,0 +1,19 @@ +## 1. Очередь команд (PEP-21) +- [x] 1.1 Миграция 0011: `runner_commands`, `sessions.watch_state`, `questions.reminders` +- [x] 1.2 `runner-client.ts`: флаг клиента, `runnerCall` (сокет-проверка, пинок, ожидание, expired), ошибки +- [x] 1.3 `runner-service.ts`: реестр команд, захват, ключи сериализации, восстановление после рестарта, уборка +- [x] 1.4 Guards в функциях жизненного цикла и в изменяющих операциях tmux +- [x] 1.5 Сервис внутри `runWatchdog`; клиентский режим в вебе и боте; `PEPPA_RUNNER_MODE=inline` +- [x] 1.6 CLI: session через сервис с откатом, `peppa runner commands`, `peppa status` + +## 2. Вачдог 2.0 (PEP-28) +- [x] 2.1 Настройки `platform.watchdog` + env, CLI `peppa platform watchdog` +- [x] 2.2 Состояние вачдога в `sessions.watch_state` +- [x] 2.3 Авто-перезапуск упавшего/зависшего раннера с пределом и паузой +- [x] 2.4 Напоминания о вопросах и эскалация админам +- [x] 2.5 Уборка давних `waiting_input` + +## 3. Проверка и документация +- [x] 3.1 e2e: очередь (выполнение, ошибки, недоступный сервис, expired, автор), tmux через сервис +- [x] 3.2 e2e: авто-перезапуск, предел, напоминания/эскалация, уборка, состояние после рестарта +- [x] 3.3 AGENTS.md, /help (если касается), `pnpm run ci` diff --git a/openspec/specs/runner-service/spec.md b/openspec/specs/runner-service/spec.md new file mode 100644 index 00000000..3ecc7e67 --- /dev/null +++ b/openspec/specs/runner-service/spec.md @@ -0,0 +1,65 @@ +# runner-service Specification + +## Purpose +Определяет, что процессы агентов (tmux) запускает, останавливает и вводит в них текст только раннер-сервис в процессе вачдога, а веб, бот и удалённый MCP ставят ему команды и получают понятную ошибку, если сервис недоступен. + +## Requirements + +### Requirement: Процессы агентов запускает только раннер-сервис +Веб, бот и удалённый MCP SHALL NOT запускать, останавливать и вводить текст в tmux-сессии агентов в своём процессе; они ставят команду в очередь `runner_commands`, а выполняет её раннер-сервис (процесс вачдога). + +#### Scenario: PM двигает стори в работу из веба +- **GIVEN** раннер-сервис запущен +- **WHEN** PM переносит стори PEP-42 в «В работе» в вебе +- **THEN** в `runner_commands` появляется команда `move` от этого PM +- **AND** раннер-сервис выполняет её и запускает агента +- **AND** веб получает номер раннера, а журнал показывает автором PM через веб + +#### Scenario: Ответ на вопрос из Telegram +- **GIVEN** агент ждёт ответа PM +- **WHEN** PM отвечает в Telegram +- **THEN** ответ печатает в терминал агента раннер-сервис, а не бот + +#### Scenario: Вебхук Gitea с красной проверкой +- **WHEN** веб получает отчёт о красной проверке для стори с живым раннером +- **THEN** текст для агента отправляется в tmux через раннер-сервис + +### Requirement: Команды одной стори не гоняются +Раннер-сервис SHALL выполнять команды с одним ключом (стори или раннер) по очереди, а с разными — независимо. + +#### Scenario: Двойное «В работу» +- **WHEN** веб и бот почти одновременно двигают одну стори в работу +- **THEN** вторая команда выполняется после первой и видит уже запущенного агента +- **AND** второй агент не запускается + +### Requirement: Недоступный сервис — понятная ошибка +Если раннер-сервис не запущен или не взял команду за 15 секунд, клиент SHALL получить ошибку с причиной, а команда SHALL быть помечена просроченной и не выполняться позже. + +#### Scenario: Вачдог остановлен +- **GIVEN** раннер-сервис не запущен +- **WHEN** PM нажимает «Возобновить» у раннера +- **THEN** PM видит «Раннер-сервис не запущен (вачдог)… — команда не выполнена» +- **AND** команда в `runner_commands` имеет статус `expired` + +#### Scenario: Сервис завис +- **GIVEN** сокет сервиса отвечает, но команды он не берёт +- **WHEN** проходит 15 секунд +- **THEN** клиент получает ошибку «не взял команду за 15 с» +- **AND** когда сервис оживает, он эту команду не выполняет + +#### Scenario: Ошибка домена +- **WHEN** команда запуска падает с «Лимит раннеров проекта: 2» +- **THEN** PM видит тот же текст ошибки + +#### Scenario: Рестарт сервиса посреди команды +- **GIVEN** команда выполнялась, когда процесс вачдога перезапустился +- **WHEN** сервис стартует снова +- **THEN** команда помечена `failed` «раннер-сервис перезапустился во время выполнения» + +### Requirement: Аварийный режим на месте +При `PEPPA_RUNNER_MODE=inline` клиенты SHALL выполнять команды в своём процессе, как до PEP-21. + +#### Scenario: Откат +- **GIVEN** у веба `PEPPA_RUNNER_MODE=inline` +- **WHEN** PM запускает раннер +- **THEN** tmux запускается из процесса веба без очереди diff --git a/openspec/specs/watchdog-recovery/spec.md b/openspec/specs/watchdog-recovery/spec.md new file mode 100644 index 00000000..b014e587 --- /dev/null +++ b/openspec/specs/watchdog-recovery/spec.md @@ -0,0 +1,71 @@ +# watchdog-recovery Specification + +## Purpose +Определяет, что вачдог сам восстанавливает упавшие и зависшие раннеры в пределах лимита, напоминает о неотвеченных вопросах и эскалирует их, убирает раннеры, которые никого не ждут, и помнит своё состояние между рестартами. + +## Requirements + +### Requirement: Авто-перезапуск упавшего раннера +Вачдог SHALL сам перезапускать (resume) упавший раннер стори в работе не больше `restartMax` раз за `restartWindowMin`, с паузой 1, 5, 15 минут перед попытками, и только после исчерпания предела SHALL спрашивать PM. + +#### Scenario: Падение и восстановление +- **GIVEN** агент стори PEP-42 «в работе» упал с кодом 1 +- **WHEN** вачдог видит мёртвый pane +- **THEN** раннер получает статус `failed` и план перезапуска через 1 минуту, вопрос PM не задаётся +- **AND** через минуту вачдог делает resume того же разговора +- **AND** в журнале раннера событие `auto_restarted` с номером попытки + +#### Scenario: Предел исчерпан +- **GIVEN** раннер уже перезапускался 3 раза за сутки +- **WHEN** он падает снова +- **THEN** PM получает «Claude в PEP-42 упал (код 1)… авто-перезапуски исчерпаны (3 за 24 ч)» + +#### Scenario: Не трогаем лимит, бюджет и чужое +- **WHEN** упал раннер без стори, раннер стори не «в работе» или стори на паузе бюджета +- **THEN** авто-перезапуска нет, PM получает вопрос, как раньше + +#### Scenario: PM вмешался +- **GIVEN** перезапуск запланирован +- **WHEN** PM сам делает resume или stop +- **THEN** вачдог план не выполняет + +### Requirement: Зависший раннер перезапускается +Если PM не ответил на алерт о зависании `stallRestartMin` минут, вачдог SHALL перезапустить раннер по правилам авто-перезапуска. + +#### Scenario: Экран не меняется час +- **GIVEN** вачдог сообщил о зависании раннера PEP-42 +- **WHEN** проходит 60 минут без ответа и экран не изменился +- **THEN** tmux-сессия убита, раннер продолжает разговор заново, алерт закрыт + +### Requirement: Напоминание и эскалация вопросов +Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. + +#### Scenario: Вопрос висит +- **GIVEN** агент спросил PM в 10:00 +- **WHEN** в 10:30 ответа нет +- **THEN** участники проекта получают «⏰ Вопрос #N ждёт ответа 30 мин» +- **AND** в 11:00 — второе напоминание, в 12:00 — эскалация админам +- **AND** повторные тики вачдога новых сообщений не создают + +### Requirement: Уборка давних waiting_input +Раннер стори в `waiting_input` без открытых вопросов дольше `idleStopHours` SHALL останавливаться с сообщением PM. + +#### Scenario: Раннер ждёт сутки +- **GIVEN** раннер PEP-42 в `waiting_input` 25 часов и вопросов нет +- **WHEN** тикает вачдог +- **THEN** раннер остановлен, событие `idle_stopped`, PM получает сообщение, что его можно продолжить + +### Requirement: Состояние вачдога в БД +Хэш экрана и отметки «лимит/порог уже замечен» SHALL храниться у раннера в БД и переживать рестарт вачдога. + +#### Scenario: Рестарт вачдога +- **GIVEN** вачдог уже сообщил о лимите в поколении 3 +- **WHEN** вачдог перезапускается и снова видит баннер лимита на экране +- **THEN** повторного сообщения нет + +### Requirement: Настраиваемые пороги +Пороги SHALL задаваться `platform.watchdog` (CLI `peppa platform watchdog key=value`) поверх env `PEPPA_WATCHDOG_*`; `restartMax=0` выключает авто-перезапуск. + +#### Scenario: Выключить перезапуск +- **WHEN** админ выполняет `peppa platform watchdog restartMax=0` +- **THEN** упавший раннер сразу даёт вопрос PM diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index a0261119..37dded95 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -61,7 +61,7 @@ import { setDefaultActor, } from "@peppa/core"; import { createDb, migrateDb } from "@peppa/db"; -import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner } from "@peppa/runner"; +import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner"; import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core"; import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; @@ -101,11 +101,14 @@ const USAGE = `peppa — Peppa software factory CLI peppa runner promote <название стори> [-d <описание>] (the free runner's work becomes a story) peppa runner queue [-p <промпт>] (story into the runner's queue, PEP-10) peppa runner show (history and queue of the runner) + peppa runner commands [N] (PEP-21: last commands of the runner service) peppa runner settings [system|KEY|PEP-42] [mode=story|queue context=fresh|continue workspace=shared|worktree max=N|- | reset] (PEP-10/27: system → project → story; a story overrides mode/context only) peppa platform allowlist | allow | deny (who may log into Peppa) peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch) peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist) + peppa platform watchdog [key=value… | key=- | reset] (PEP-28: restartMax restartWindowMin restartDelaysMin=1,5,15 + stallRestartMin remindMin escalateMin idleStopHours; 0 = off) peppa status (services, outbox, runners, questions, admins) peppa telegram pair | status | unpair (users normally pair in web Settings) peppa user add [--name <имя>] [--admin] (local user without Gitea, PEP-68; --admin → platform.admins) @@ -216,8 +219,17 @@ function status(s: string | undefined): TaskStatus | undefined { return s as TaskStatus; } +// PEP-21: commands that start, stop or type into runners go through the runner service when +// it is up (the same path as the web and the bot); without it the CLI runs them itself. +const RUNNER_CMDS = new Set(["session start", "session send", "session resume", "session stop", "runner new", "runner promote", "runner queue", "q answer"]); + async function main(): Promise { - switch (`${group ?? ""} ${cmd ?? ""}`.trim()) { + const command = `${group ?? ""} ${cmd ?? ""}`.trim(); + if (RUNNER_CMDS.has(command) && process.env.PEPPA_RUNNER_MODE !== "inline") { + if (await runnerServiceAlive()) setRunnerClient(true, db); + else console.error("peppa: раннер-сервис (вачдог) не запущен — выполняю команду в этом процессе"); + } + switch (command) { case "project add": { const [slug, key, name] = args; if (!slug || !key || !name) throw new PeppaError("usage: peppa project add "); @@ -469,6 +481,21 @@ async function main(): Promise { for (const r of queue) console.log(` queued ${r.taskKey.padEnd(10)} ${r.taskTitle}${r.prompt ? ` (${r.prompt.slice(0, 40)})` : ""}`); break; } + case "runner commands": { + // PEP-21: what web/bot/CLI asked the runner service to do. + for (const c of (await recentRunnerCommands(db, Number(args[0]) || 20)).reverse()) { + const took = c.finishedAt && c.startedAt ? `${c.finishedAt.getTime() - c.startedAt.getTime()}ms` : ""; + const who = c.actor ? `${(c.actor as { kind?: string; channel?: string }).kind ?? ""}/${(c.actor as { channel?: string }).channel ?? ""}` : "-"; + console.log(`#${String(c.id).padEnd(5)} ${c.createdAt.toISOString().slice(5, 19).replace("T", " ")} ${c.kind.padEnd(11)} ${c.status.padEnd(8)} ${took.padEnd(8)} ${who.padEnd(14)} ${c.error ?? ""}`); + } + break; + } + case "platform watchdog": { + // PEP-28: thresholds of auto-recovery and escalation. + const w = args.length ? await setWatchdogSettings(db, args) : await getWatchdogSettings(db); + for (const [k, v] of Object.entries(w)) console.log(`${k}=${Array.isArray(v) ? v.join(",") : v}`); + break; + } case "runner settings": { // PEP-10/27: peppa runner settings [system|KEY|KEY-N] [key=value…|reset] const [target = "system", ...rest] = args; @@ -523,6 +550,7 @@ async function main(): Promise { const info = hb ? ` v${hb.version} pid ${hb.pid} ${hb.host}, с ${hb.startedAt.slice(0, 16).replace("T", " ")}` : ""; console.log(`${SERVICE_NAMES[s.service].padEnd(7)} ${describeState(s).padEnd(16)}${info}`); } + console.log(`раннер-сервис: ${(await runnerServiceAlive()) ? "слушает" : "не отвечает"} (команды веба и бота выполняет вачдог)`); const ob = await outboxStats(db); console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`); console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`); diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index d5cce3db..f8c4d444 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -77,7 +77,7 @@ export async function listUserSessions(db: Db, userId: number, opts: { filter?: export async function updateSession( db: Db, id: number, - patch: Partial>, + patch: Partial>, ): Promise { const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning(); if (!row) throw new PeppaError(`Session #${id} not found`); diff --git a/packages/db/migrations/0012_runner_service.sql b/packages/db/migrations/0012_runner_service.sql new file mode 100644 index 00000000..3830339c --- /dev/null +++ b/packages/db/migrations/0012_runner_service.sql @@ -0,0 +1,19 @@ +CREATE TABLE `runner_commands` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `kind` text NOT NULL, + `payload` text NOT NULL, + `key` text, + `status` text DEFAULT 'queued' NOT NULL, + `result` text, + `error` text, + `error_kind` text, + `actor` text, + `host` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `started_at` integer, + `finished_at` integer +); +--> statement-breakpoint +CREATE INDEX `runner_commands_status_idx` ON `runner_commands` (`status`,`id`);--> statement-breakpoint +ALTER TABLE `questions` ADD `reminders` integer DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE `sessions` ADD `watch_state` text; \ No newline at end of file diff --git a/packages/db/migrations/meta/0012_snapshot.json b/packages/db/migrations/meta/0012_snapshot.json new file mode 100644 index 00000000..ace19479 --- /dev/null +++ b/packages/db/migrations/meta/0012_snapshot.json @@ -0,0 +1,3519 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "ae1ab7d5-713e-4d63-818f-23fffee72696", + "prevId": "c952eda0-bbdd-4908-b51b-9b0e893c4895", + "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 + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "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 81b9c235..46b59e11 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -85,6 +85,13 @@ "when": 1794621835010, "tag": "0011_project_secrets", "breakpoints": true + }, + { + "idx": 12, + "version": "6", + "when": 1794623649272, + "tag": "0012_runner_service", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 657661d1..dfa13a02 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -282,6 +282,9 @@ export const sessions = sqliteTable("sessions", { // PEP-5: tokens (per conversation, from the transcript), cost (per generation, from the // statusLine), context window — see core/usage.ts. usage: text("usage", { mode: "json" }).$type(), + // PEP-28: what the watchdog remembers about the runner (screen hash, alerts, restarts) — + // survives its restart (core/sessions.ts WatchState). + watchState: text("watch_state", { mode: "json" }).$type(), status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"), lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }), startedAt: createdAt(), @@ -326,10 +329,57 @@ export const questions = sqliteTable("questions", { // A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer, // so it must not also be typed into the terminal. awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false), + // PEP-28: reminders sent about it while unanswered (1, 2 = reminders; 3 = escalated to admins). + reminders: integer("reminders").notNull().default(0), createdAt: createdAt(), answeredAt: integer("answered_at", { mode: "timestamp_ms" }), }); +/** PEP-28: the watchdog's memory of a runner (sessions.watch_state). */ +export type WatchState = { + /** sha1 of the last seen screen. */ + screen?: string; + /** Generation whose limit banner was already handled / threshold warning already seen. */ + limitGen?: number; + thresholdGen?: number; + /** Times (ms) of automatic restarts — the limit counts those inside the window. */ + restarts?: number[]; + /** A planned automatic restart (ms) and why ("crash" | "gone" | "stall"). */ + restartAt?: number; + restartReason?: string; + /** When the stall alert went out (ms). */ + stallAlertAt?: number; +}; + +/** + * PEP-21: commands for the runner service (the watchdog process). Web, bot and the remote + * MCP enqueue; the service claims (`queued` → `running`) and runs them; a client that gave + * up marks a still-queued command `expired`, so it never runs late. + */ +export const runnerCommands = sqliteTable( + "runner_commands", + { + id: integer("id").primaryKey({ autoIncrement: true }), + kind: text("kind").notNull(), + payload: text("payload", { mode: "json" }).$type>().notNull(), + // Commands with the same key run one after another (task: / session:); null = at once. + key: text("key"), + status: text("status", { enum: ["queued", "running", "done", "failed", "expired"] }).notNull().default("queued"), + result: text("result", { mode: "json" }).$type(), + error: text("error"), + // PeppaError (shown to the user as is) or an internal failure. + errorKind: text("error_kind", { enum: ["peppa", "internal"] }), + // Who asked (PEP-48 actor) — the service runs the command as them. + actor: text("actor", { mode: "json" }).$type>(), + // A runner machine for the command (several runner hosts later); null = any. + host: text("host"), + createdAt: createdAt(), + startedAt: integer("started_at", { mode: "timestamp_ms" }), + finishedAt: integer("finished_at", { mode: "timestamp_ms" }), + }, + (t) => [index("runner_commands_status_idx").on(t.status, t.id)], +); + export type UsageTokens = { input: number; output: number; cacheRead: number; cacheWrite: number }; /** PEP-5: what a session spent (core/usage.ts). */ export type SessionUsage = { diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 8512fbb0..a1e9e65b 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -9,6 +9,7 @@ import { mergeTaskPr } from "./ci-feedback.ts"; import { syncWorkspace } from "./workspace-sync.ts"; import { closeLinkedIssue } from "./gitea-events.ts"; import type { GiteaClient } from "@peppa/core"; +import { isRunnerClient, runnerCall } from "./runner-client.ts"; export type BoardColumn = "backlog" | "in_progress" | "review" | "done"; @@ -39,6 +40,8 @@ export async function reviewGate(ref: TaskRef): Promise { * "backlog"/"done": active sessions are stopped. */ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}, gitea?: GiteaClient): Promise<{ started?: number; runner?: number; queued?: boolean; stopped: number }> { + // PEP-21: the whole move runs in the runner service (one at a time per story). + if (isRunnerClient()) return runnerCall(db, "move", { task: ref.key, to, start }, { key: `task:${ref.task.id}` }); const from = columnOf(ref.task.status); let stopped = 0; if (to === "in_progress") { @@ -82,6 +85,7 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta * backlog first. */ export async function archiveTask(db: Db, ref: TaskRef, archived: boolean): Promise<{ stopped: number }> { + if (isRunnerClient()) return runnerCall(db, "archive", { task: ref.key, archived }, { key: `task:${ref.task.id}` }); let stopped = 0; if (archived) { for (const s of await activeSessions(db, ref.task.id)) { @@ -107,6 +111,10 @@ export async function reorderBoardTask(db: Db, ref: TaskRef, r: ReorderTo) { */ export async function acceptTask(db: Db, questionId: number, via: NonNullable, answer = "✅ Принято"): Promise { const q = await getQuestion(db, questionId); + if (isRunnerClient()) { + const r = await runnerCall<{ key: string }>(db, "accept", { questionId, via, answer }, { key: q.taskId ? `task:${q.taskId}` : null }); + return resolveTask(db, r.key); + } if (!q.taskId) throw new PeppaError("Вопрос не привязан к стори"); if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${q.answer}`); const [t] = await db @@ -132,6 +140,7 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable = "web"): Promise { + if (isRunnerClient()) return resolveTask(db, (await runnerCall<{ key: string }>(db, "acceptStory", { task: ref.key, via }, { key: `task:${ref.task.id}` })).key); if (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${ref.task.status})`); const [open] = (await pendingQuestions(db, ref.project.id)).filter((q) => q.taskId === ref.task.id && q.kind === "attention").slice(-1); if (open) return acceptTask(db, open.id, via); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index b62e8e5d..fe2f7cb7 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -30,3 +30,6 @@ export * from "./planner.ts"; export * from "./runners.ts"; export * from "./worktree.ts"; export * from "./budgets.ts"; +export * from "./runner-client.ts"; +export * from "./runner-service.ts"; +export * from "./recovery.ts"; diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts new file mode 100644 index 00000000..01d0689b --- /dev/null +++ b/packages/runner/src/recovery.ts @@ -0,0 +1,295 @@ +// PEP-28: watchdog 2.0 — the watchdog fixes what it can by itself (restarts a crashed or +// stalled runner within a limit), reminds about unanswered questions and escalates them, +// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env. +import { and, eq, gte, inArray, isNull, sql } from "drizzle-orm"; +import { + alertAdmins, + deleteSetting, + deliverToUser, + getBudgetState, + getSession, + getSetting, + listSessions, + logSessionEvent, + pendingSessionQuestions, + PeppaError, + projectAudience, + raiseSessionQuestion, + sendProjectMessage, + setSetting, + updateSession, + type SessionView, +} from "@peppa/core"; +import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { resumeSession, stopSession } from "./sessions.ts"; +import * as tmux from "./tmux.ts"; + +export interface WatchdogSettings { + /** Automatic restarts of one runner within the window; 0 = off. */ + restartMax: number; + restartWindowMin: number; + /** Pause before restart attempt 1, 2, 3… (the last one repeats). */ + restartDelaysMin: number[]; + /** A stalled runner whose alert got no answer this long is restarted; 0 = never. */ + stallRestartMin: number; + /** Reminders about an unanswered question (after 1× and 2× this); 0 = off. */ + remindMin: number; + /** Then the platform admins hear about it; 0 = off. */ + escalateMin: number; + /** A story runner in waiting_input with nothing asked is stopped after this; 0 = never. */ + idleStopHours: number; +} + +export const WATCHDOG_DEFAULTS: WatchdogSettings = { + restartMax: 3, + restartWindowMin: 24 * 60, + restartDelaysMin: [1, 5, 15], + stallRestartMin: 60, + remindMin: 30, + escalateMin: 120, + idleStopHours: 24, +}; + +const KEY = "platform.watchdog"; +const envName = (k: string) => `PEPPA_WATCHDOG_${k.replace(/[A-Z]/g, (c) => `_${c}`).toUpperCase()}`; + +function parseValue(k: keyof WatchdogSettings, v: string): number | number[] { + if (k === "restartDelaysMin") { + const list = v.split(",").map((x) => Number(x.trim())); + if (!list.length || list.some((n) => !Number.isFinite(n) || n < 0)) throw new PeppaError(`${k}: список минут через запятую, напр. 1,5,15`); + return list; + } + const n = Number(v); + if (!Number.isFinite(n) || n < 0) throw new PeppaError(`${k}: нужно число ≥ 0`); + return n; +} + +/** Defaults ← env `PEPPA_WATCHDOG_*` ← `platform.watchdog`. */ +export async function getWatchdogSettings(db: Db): Promise { + const out: WatchdogSettings = { ...WATCHDOG_DEFAULTS, restartDelaysMin: [...WATCHDOG_DEFAULTS.restartDelaysMin] }; + for (const k of Object.keys(out) as (keyof WatchdogSettings)[]) { + const v = process.env[envName(k)]; + if (v) (out as any)[k] = parseValue(k, v); + } + return { ...out, ...((await getSetting>(db, KEY)) ?? {}) }; +} + +/** `peppa platform watchdog key=value…` / `reset`. */ +export async function setWatchdogSettings(db: Db, pairs: string[]): Promise { + if (pairs.length === 1 && pairs[0] === "reset") { + await deleteSetting(db, KEY); + return getWatchdogSettings(db); + } + const cur = (await getSetting>(db, KEY)) ?? {}; + for (const p of pairs) { + const [k, v] = p.split("="); + if (!k || v === undefined || !(k in WATCHDOG_DEFAULTS)) throw new PeppaError(`неизвестная настройка «${p}»; есть: ${Object.keys(WATCHDOG_DEFAULTS).join(", ")}`); + if (v === "-") delete (cur as any)[k]; + else (cur as any)[k] = parseValue(k as keyof WatchdogSettings, v); + } + await setSetting(db, KEY, cur); + return getWatchdogSettings(db); +} + +// ── runner state ────────────────────────────────────────────────────────────────── + +/** Merges into `sessions.watch_state` (and into the view in hand). */ +export async function patchWatch(db: Db, s: SessionView, patch: Partial, extra: Parameters[2] = {}): Promise { + const next: WatchState = { ...(s.watchState ?? {}), ...patch }; + for (const k of Object.keys(next) as (keyof WatchState)[]) if (next[k] === undefined) delete next[k]; + s.watchState = next; + await updateSession(db, s.id, { ...extra, watchState: next }); +} + +// ── automatic restarts ──────────────────────────────────────────────────────────── + +const RESTARTABLE_TASK = ["proposing", "in_progress"]; + +/** Why the runner may not be restarted automatically (null = it may). */ +async function restartBlocker(db: Db, s: SessionView, cfg: WatchdogSettings, now: number): Promise { + if (cfg.restartMax <= 0) return "выключен"; + if (!s.taskId || !s.taskStatus || !RESTARTABLE_TASK.includes(s.taskStatus)) return "не стори в работе"; + if (s.status === "rate_limited" || s.resumeAt) return "лимит"; + if (await getBudgetState(db, s.taskId)) return "бюджет"; + const recent = restartsInWindow(s, cfg, now); + if (recent.length >= cfg.restartMax) return `авто-перезапуски исчерпаны (${cfg.restartMax} за ${fmtWindow(cfg.restartWindowMin)})`; + return null; +} + +const restartsInWindow = (s: SessionView, cfg: WatchdogSettings, now: number) => (s.watchState?.restarts ?? []).filter((t) => now - t < cfg.restartWindowMin * 60_000); +const fmtWindow = (min: number) => (min % 60 === 0 ? `${min / 60} ч` : `${min} мин`); + +/** + * The agent process died (non-zero exit) or its tmux session is gone. A story at work gets + * a planned restart after a pause instead of a question; otherwise the PM is asked as before. + * Returns true when a restart was planned. + */ +export async function onRunnerCrash( + db: Db, + s: SessionView, + reason: "crash" | "gone", + alert: string, + o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }, +): Promise { + const now = o.now.getTime(); + const blocker = await restartBlocker(db, s, o.cfg, now); + if (!blocker) { + const n = restartsInWindow(s, o.cfg, now).length; + const delays = o.cfg.restartDelaysMin.length ? o.cfg.restartDelaysMin : [0]; + const at = now + delays[Math.min(n, delays.length - 1)]! * 60_000; + await patchWatch(db, s, { restartAt: at, restartReason: reason }, { status: "failed", endedAt: o.now }); + await logSessionEvent(db, s, "restart_planned", { reason, attempt: n + 1, of: o.cfg.restartMax, at: new Date(at).toISOString() }); + o.log(`#${s.id} ${s.taskKey ?? ""}: ${reason}, restart ${n + 1}/${o.cfg.restartMax} at ${new Date(at).toISOString()}`); + return true; + } + await updateSession(db, s.id, { status: "failed", endedAt: o.now }); + const tail = restartsInWindow(s, o.cfg, now).length && blocker.startsWith("авто-перезапуски") ? `\n\n${blocker}.` : ""; + await raiseSessionQuestion(db, s, "attention", `${alert}${tail}`); + return false; +} + +/** Planned restarts that are due (`failed` runners with `watch_state.restartAt`). */ +export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { + const rows = await db + .select({ id: sessions.id }) + .from(sessions) + .where(and(eq(sessions.status, "failed"), sql`json_extract(${sessions.watchState}, '$.restartAt') is not null`)); + for (const { id } of rows) { + const s = await getSession(db, id); + const ws = s.watchState ?? {}; + if (ws.restartAt == null || ws.restartAt > o.now.getTime()) continue; + const clear = { restartAt: undefined, restartReason: undefined }; + // The PM may have started another runner for the story, or moved it on. + const other = s.taskId ? (await listSessions(db, { active: true, taskId: s.taskId })).length : 0; + const blocker = other ? "стори уже ведёт другой раннер" : await restartBlocker(db, s, o.cfg, o.now.getTime()); + if (blocker) { + await patchWatch(db, s, clear); + await logSessionEvent(db, s, "restart_skipped", { why: blocker }); + if (!other && s.taskStatus && RESTARTABLE_TASK.includes(s.taskStatus)) + await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Раннер ${s.id}`} упал, авто-перезапуск не сделан: ${blocker}.`); + continue; + } + const restarts = [...restartsInWindow(s, o.cfg, o.now.getTime()), o.now.getTime()]; + await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined }); + try { + await resumeSession(db, s.id, { + prompt: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`, + }); + await logSessionEvent(db, s, "auto_restarted", { reason: ws.restartReason, attempt: restarts.length, of: o.cfg.restartMax }); + o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`); + } catch (e) { + await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message }); + await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Раннер ${s.id}`}: не удалось перезапустить автоматически — ${(e as Error).message}`); + } + } +} + +/** + * The PM did not react to a stall alert for `stallRestartMin`: kill the stuck agent and + * restart it now (counts against the restart limit). Returns true when it did. + */ +export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { + const at = s.watchState?.stallAlertAt; + if (!at || o.cfg.stallRestartMin <= 0 || o.now.getTime() - at < o.cfg.stallRestartMin * 60_000) return false; + const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime()); + if (blocker) { + await patchWatch(db, s, { stallAlertAt: undefined }); + await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker }); + return false; + } + await tmux.killSession(s.tmuxName).catch(() => {}); + await patchWatch(db, s, { stallAlertAt: undefined, restartAt: o.now.getTime(), restartReason: "stall" }, { status: "failed", endedAt: o.now }); + await logSessionEvent(db, s, "restart_planned", { reason: "stall", attempt: restartsInWindow(s, o.cfg, o.now.getTime()).length + 1, of: o.cfg.restartMax }); + await restartTick(db, o); + return true; +} + +// ── reminders and escalation ────────────────────────────────────────────────────── + +const REMIND_KINDS = ["question", "permission", "approval"] as const; +const KIND_RU: Record = { question: "Вопрос", permission: "Разрешение", approval: "Одобрение proposal" }; + +/** + * Unanswered questions: reminders to the project's people after `remindMin` and 2×, then the + * platform admins after `escalateMin`. `questions.reminders` is claimed atomically, so every + * message goes out once whoever ticks. Only questions of the last day (no flood of old ones). + */ +export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { + const { remindMin, escalateMin } = o.cfg; + if (remindMin <= 0 && escalateMin <= 0) return 0; + const now = o.now.getTime(); + const rows = await db + .select({ q: questions, projectKey: projects.key, taskNumber: tasks.number }) + .from(questions) + .innerJoin(projects, eq(questions.projectId, projects.id)) + .leftJoin(tasks, eq(questions.taskId, tasks.id)) + .where(and(isNull(questions.answeredAt), inArray(questions.kind, [...REMIND_KINDS]), gestDay(now))); + let sent = 0; + for (const { q, projectKey, taskNumber } of rows) { + const age = now - q.createdAt.getTime(); + const ageMin = Math.round(age / 60_000); + const n = q.reminders; + const escalate = escalateMin > 0 && n < 3 && age >= escalateMin * 60_000; + const remind = !escalate && remindMin > 0 && n < 2 && age >= (n + 1) * remindMin * 60_000; + if (!escalate && !remind) continue; + const next = escalate ? 3 : n + 1; + const [claimed] = await db + .update(questions) + .set({ reminders: next }) + .where(and(eq(questions.id, q.id), eq(questions.reminders, n), isNull(questions.answeredAt))) + .returning({ id: questions.id }); + if (!claimed) continue; + const where = taskNumber != null ? formatTaskKey(projectKey, taskNumber) : projectKey; + const url = taskNumber != null ? `/t/${where}` : "/"; + const body = q.text.length > 300 ? `${q.text.slice(0, 300)}…` : q.text; + if (escalate) { + await alertAdmins(db, `esc:q${q.id}`, `🚨 ${where}: ${KIND_RU[q.kind]?.toLowerCase() ?? "вопрос"} #${q.id} без ответа ${ageMin} мин — агент ждёт.\n\n${body}`, o.log); + } else { + for (const u of await projectAudience(db, q.projectId)) { + const text = `⏰ ${where}: ${KIND_RU[q.kind] ?? "Вопрос"} #${q.id} ждёт ответа ${ageMin} мин.\n\n${body}`; + const r = await deliverToUser(db, u, { + event: "questions", + projectId: q.projectId, + dedupeKey: `remind:q${q.id}:${next}:${u.telegramChatId}`, + pushKey: `remind:q${q.id}:${next}:u${u.id}`, + telegram: { params: { text } }, + push: { title: `Ждёт ответа: ${where}`, body: body.slice(0, 200), url, tag: `remind:q${q.id}` }, + now: o.now, + }); + if (r.telegram || r.push) sent++; + } + } + o.log(`question #${q.id}: ${escalate ? "escalated to admins" : `reminder ${next}`} (${ageMin} min)`); + } + return sent; +} + +const gestDay = (now: number) => gte(questions.createdAt, new Date(now - 24 * 60 * 60_000)); + +// ── idle runners ────────────────────────────────────────────────────────────────── + +/** A story runner in waiting_input with nothing asked for `idleStopHours` is stopped (resumable). */ +export async function idleStopTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { + if (o.cfg.idleStopHours <= 0) return 0; + let stopped = 0; + for (const s of await listSessions(db, { active: true })) { + if (s.status !== "waiting_input" || !s.taskId || !s.lastActivityAt) continue; + const idleMs = o.now.getTime() - s.lastActivityAt.getTime(); + if (idleMs < o.cfg.idleStopHours * 3600_000) continue; + if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) continue; + await stopSession(db, s.id); + await logSessionEvent(db, s, "idle_stopped", { idleHours: Math.round(idleMs / 3600_000) }); + const who = s.taskKey ?? `Раннер ${s.id}`; + await sendProjectMessage( + db, + s.projectId, + `💤 ${who}: раннер ждал ${Math.round(idleMs / 3600_000)} ч без вопросов — остановлен. Продолжить разговор — «Возобновить» у раннера.`, + `idle-stop:s${s.id}:${s.generation}`, + { title: `Раннер остановлен: ${who}`, url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}` }, + ); + o.log(`#${s.id} ${s.taskKey ?? ""}: idle ${Math.round(idleMs / 3600_000)}h in waiting_input, stopped`); + stopped++; + } + return stopped; +} diff --git a/packages/runner/src/runner-client.ts b/packages/runner/src/runner-client.ts new file mode 100644 index 00000000..ce79f788 --- /dev/null +++ b/packages/runner/src/runner-client.ts @@ -0,0 +1,127 @@ +// PEP-21: the client side of the runner service. Web, bot and the remote MCP are "clients": +// they never start, stop or type into agent tmux sessions themselves — they enqueue a +// command in `runner_commands`, poke the service over a unix socket and wait for the result. +// The service lives in the watchdog process (runner-service.ts). +import { AsyncLocalStorage } from "node:async_hooks"; +import { connect } from "node:net"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { and, eq } from "drizzle-orm"; +import { currentActor, PeppaError } from "@peppa/core"; +import { runnerCommands, type Db } from "@peppa/db"; +import { peppaHome } from "@peppa/shared"; + +export const runnerSocket = () => join(peppaHome(), "runner.sock"); + +const CLIENT_FLAG = Symbol.for("peppa.runnerClient"); +const DB_KEY = Symbol.for("peppa.runnerClientDb"); +const SERVICE_CTX = Symbol.for("peppa.runnerServiceCtx"); +type G = { [CLIENT_FLAG]?: boolean; [DB_KEY]?: Db; [SERVICE_CTX]?: AsyncLocalStorage }; +const g = globalThis as G; +const serviceCtx = (g[SERVICE_CTX] ??= new AsyncLocalStorage()); + +/** Runs `fn` as the runner service: lifecycle calls inside run here, never re-enqueued. */ +export function runAsRunnerService(fn: () => T): T { + return serviceCtx.run(true, fn); +} + +/** + * Declares this process a client of the runner service (web: instrumentation.ts, bot: its + * bin). Kept on globalThis — Next loads instrumentation and server actions as separate + * bundles of one process. `PEPPA_RUNNER_MODE=inline` is the escape hatch: run in-process + * as before PEP-21. `db` is used by the tmux safety net, which has no db of its own. + */ +export function setRunnerClient(on: boolean, db?: Db): void { + g[CLIENT_FLAG] = on && process.env.PEPPA_RUNNER_MODE !== "inline"; + if (db) g[DB_KEY] = db; +} + +export function isRunnerClient(): boolean { + return g[CLIENT_FLAG] === true && !serviceCtx.getStore(); +} + +export function runnerClientDb(): Db { + const db = g[DB_KEY]; + if (!db) throw new PeppaError("Клиент раннер-сервиса не настроен (нет базы)"); + return db; +} + +/** The runner service failed to take or finish a command (not a domain error). */ +export class RunnerUnavailableError extends PeppaError {} + +const SERVICE_HINT = "проверьте `peppa status` и launchd-агент quest.telecom.peppa.watchdog"; + +/** Pokes the service; false when nobody listens on the socket (service not running). */ +export function pokeRunner(): Promise { + return new Promise((resolve) => { + const path = runnerSocket(); + if (!existsSync(path)) return resolve(false); + const sock = connect(path); + sock.setTimeout(500, () => (sock.destroy(), resolve(false))); + // Connected = someone listens; the poke is in the kernel buffer once written. + sock.on("connect", () => sock.end("poke\n", () => (sock.destroy(), resolve(true)))); + sock.on("error", () => resolve(false)); + }); +} + +/** Whether the runner service answers on its socket (CLI fallback, `peppa status`). */ +export const runnerServiceAlive = (): Promise => pokeRunner(); + +export interface CallOptions { + /** Serialization key: commands with the same key run one after another. */ + key?: string | null; + /** How long the service may take to pick the command up (default 15 s). */ + pickupMs?: number; + /** How long to wait for the result once it runs (default 120 s). */ + timeoutMs?: number; +} + +const sec = (env: string | undefined, def: number) => (env && Number(env) > 0 ? Number(env) * 1000 : def); + +/** + * Enqueues a command and waits for its result. Errors are never silent: the service not + * running or not picking the command up expires it (it will not run later) and throws; + * a domain error from the service comes back as a PeppaError with the same text. + */ +export async function runnerCall(db: Db, kind: string, payload: Record, o: CallOptions = {}): Promise { + const pickupMs = o.pickupMs ?? sec(process.env.PEPPA_RUNNER_PICKUP_SEC, 15_000); + const timeoutMs = o.timeoutMs ?? sec(process.env.PEPPA_RUNNER_TIMEOUT_SEC, 120_000); + const actor = currentActor(); + const [row] = await db + .insert(runnerCommands) + .values({ kind, payload, key: o.key ?? null, actor: actor ? { ...actor } : null }) + .returning({ id: runnerCommands.id }); + const id = row!.id; + const expire = async () => + (await db + .update(runnerCommands) + .set({ status: "expired", finishedAt: new Date() }) + .where(and(eq(runnerCommands.id, id), eq(runnerCommands.status, "queued"))) + .returning({ id: runnerCommands.id })).length > 0; + + if (!(await pokeRunner())) { + if (await expire()) throw new RunnerUnavailableError(`Раннер-сервис не запущен (вачдог) — команда не выполнена; ${SERVICE_HINT}`); + } + const started = Date.now(); + let runningSince: number | null = null; + for (let delay = 20; ; delay = Math.min(delay * 2, 100)) { + await new Promise((r) => setTimeout(r, delay)); + const [c] = await db.select().from(runnerCommands).where(eq(runnerCommands.id, id)); + if (!c) throw new RunnerUnavailableError(`Команда раннера #${id} пропала`); + if (c.status === "done") return c.result as T; + if (c.status === "failed") { + if (c.errorKind === "peppa") throw new PeppaError(c.error ?? "ошибка"); + throw new RunnerUnavailableError(`Раннер-сервис: ${c.error ?? "ошибка"}`); + } + if (c.status === "expired") throw new RunnerUnavailableError(`Команда раннера #${id} просрочена — не выполнена`); + if (c.status === "queued" && Date.now() - started > pickupMs) { + if (await expire()) + throw new RunnerUnavailableError(`Раннер-сервис не взял команду за ${Math.round(pickupMs / 1000)} с — команда не выполнена; ${SERVICE_HINT}`); + } + if (c.status === "running") { + runningSince ??= Date.now(); + if (Date.now() - runningSince > timeoutMs) + throw new RunnerUnavailableError(`Команда «${kind}» выполняется дольше ${Math.round(timeoutMs / 1000)} с — результат появится на странице`); + } + } +} diff --git a/packages/runner/src/runner-service.ts b/packages/runner/src/runner-service.ts new file mode 100644 index 00000000..c5b93b5b --- /dev/null +++ b/packages/runner/src/runner-service.ts @@ -0,0 +1,197 @@ +// PEP-21: the runner service — the only process that starts, stops and types into agent +// tmux sessions. Runs inside the watchdog (`peppa watchdog`). Clients (web, bot, remote MCP) +// enqueue commands in `runner_commands` and poke `$PEPPA_HOME/runner.sock` (runner-client.ts). +import { createServer, type Server } from "node:net"; +import { rmSync } from "node:fs"; +import { and, asc, desc, eq, inArray, lt } from "drizzle-orm"; +import { PeppaError, resolveTask, runAsActor, type Actor, type Question } from "@peppa/core"; +import { runnerCommands, type Db } from "@peppa/db"; +import { pokeRunner, runAsRunnerService, runnerSocket } from "./runner-client.ts"; +import { resumeSession, sendToSession, startSession, stopSession, answerAndDeliver, type StartOptions } from "./sessions.ts"; +import { promoteRunner, queueTaskOnRunner, startFreeRunner, startTaskOnRunner, type FreeRunnerOptions } from "./runners.ts"; +import { acceptStory, acceptTask, archiveTask, moveTask, type BoardColumn } from "./flow.ts"; +import * as tmux from "./tmux.ts"; + +type P = Record; +type Handler = (db: Db, p: P) => Promise; +type Via = NonNullable; + +/** Commands the service runs. Payloads and results are plain JSON (ids, not views). */ +export const RUNNER_COMMANDS: Record = { + start: async (db, p) => ({ sessionId: (await startSession(db, p.task as string, p.opts as StartOptions)).id }), + startFree: async (db, p) => ({ sessionId: (await startFreeRunner(db, p.projectId as number, p.opts as FreeRunnerOptions)).id }), + assign: async (db, p) => startTaskOnRunner(db, await resolveTask(db, p.task), p.opts as StartOptions), + resume: async (db, p) => ({ sessionId: (await resumeSession(db, p.sessionId, p.opts as StartOptions)).id }), + stop: async (db, p) => (await stopSession(db, p.sessionId), {}), + send: async (db, p) => (await sendToSession(db, p.sessionId, p.text), {}), + move: async (db, p) => moveTask(db, await resolveTask(db, p.task), p.to as BoardColumn, p.start as StartOptions), + archive: async (db, p) => archiveTask(db, await resolveTask(db, p.task), !!p.archived), + accept: async (db, p) => ({ key: (await acceptTask(db, p.questionId, p.via as Via, p.answer)).key }), + acceptStory: async (db, p) => ({ key: (await acceptStory(db, await resolveTask(db, p.task), p.via as Via)).key }), + answer: async (db, p) => { + const r = await answerAndDeliver(db, p.questionId, p.answer, p.via as Via); + return { delivered: r.delivered, questionId: r.question.id }; + }, + queue: async (db, p) => (await queueTaskOnRunner(db, p.sessionId, await resolveTask(db, p.task), p.prompt), {}), + promote: async (db, p) => ({ key: (await promoteRunner(db, p.sessionId, p.story)).key }), + // Safety net: a mutating tmux call from a client path not covered above. + tmux: async (_db, p) => { + const a = p.args as any[]; + switch (p.op) { + case "newSession": return tmux.newSession(a[0]); + case "killSession": return tmux.killSession(a[0]); + case "sendText": return tmux.sendText(a[0], a[1], a[2]); + case "sendKeys": return tmux.sendKeys(a[0], ...(a.slice(1) as string[])); + case "sendHex": return tmux.sendHex(a[0], Uint8Array.from(a[1] as number[])); + default: throw new Error(`unknown tmux op ${p.op}`); + } + }, +}; + +export interface ServiceOptions { + log?: (m: string) => void; + /** Table poll interval (pokes wake it sooner). */ + pollMs?: number; + /** A queued command older than this is expired, not run (the client gave up). */ + pickupMs?: number; +} + +export interface RunnerService { + stop(): Promise; + /** Runs the queue now (tests). */ + drain(): Promise; +} + +const DAY = 24 * 60 * 60 * 1000; + +/** + * Starts serving runner commands: listens on the socket, polls the table, runs commands + * with the same key one after another and the rest at once. Refuses to start a second + * service next to a live one. + */ +export async function serveRunnerCommands(db: Db, o: ServiceOptions = {}): Promise { + const log = o.log ?? (() => {}); + const pickupMs = o.pickupMs ?? (Number(process.env.PEPPA_RUNNER_PICKUP_SEC) > 0 ? Number(process.env.PEPPA_RUNNER_PICKUP_SEC) * 1000 : 15_000); + if (await pokeRunner()) throw new PeppaError(`раннер-сервис уже запущен (${runnerSocket()})`); + + // Commands cut short by the previous run of the service. + const orphans = await db + .update(runnerCommands) + .set({ status: "failed", error: "раннер-сервис перезапустился во время выполнения", errorKind: "internal", finishedAt: new Date() }) + .where(eq(runnerCommands.status, "running")) + .returning({ id: runnerCommands.id }); + if (orphans.length) log(`runner service: ${orphans.length} command(s) interrupted by a restart`); + + const busyKeys = new Set(); + const inflight = new Set>(); + let draining = false; + let again = false; + let stopped = false; + let lastCleanup = 0; + + const run = async (c: typeof runnerCommands.$inferSelect) => { + const handler = RUNNER_COMMANDS[c.kind]; + const actor = (c.actor as Actor | null) ?? { kind: "system", channel: "watchdog" }; + // Raw tmux payloads may carry a launch env (tokens) or a login code: not kept once run. + const payload = c.kind === "tmux" ? { op: c.payload.op, redacted: true } : c.payload; + try { + if (!handler) throw new Error(`неизвестная команда ${c.kind}`); + const result = await runAsRunnerService(() => runAsActor(actor, () => handler(db, c.payload))); + await db.update(runnerCommands).set({ status: "done", result: result ?? null, payload, finishedAt: new Date() }).where(eq(runnerCommands.id, c.id)); + } catch (e) { + const peppa = e instanceof PeppaError; + if (!peppa) log(`runner command #${c.id} ${c.kind} failed: ${(e as Error).stack ?? e}`); + await db + .update(runnerCommands) + .set({ status: "failed", error: (e as Error).message, errorKind: peppa ? "peppa" : "internal", payload, finishedAt: new Date() }) + .where(eq(runnerCommands.id, c.id)); + } + }; + + const drainOnce = async () => { + const now = Date.now(); + const queued = await db.select().from(runnerCommands).where(eq(runnerCommands.status, "queued")).orderBy(asc(runnerCommands.id)).limit(100); + const seen = new Set(); + for (const c of queued) { + if (now - c.createdAt.getTime() > pickupMs) { + await db.update(runnerCommands).set({ status: "expired", finishedAt: new Date() }).where(and(eq(runnerCommands.id, c.id), eq(runnerCommands.status, "queued"))); + log(`runner command #${c.id} ${c.kind} expired before it was taken`); + continue; + } + // Same key: wait for the earlier one (in flight or earlier in this batch). + if (c.key && (busyKeys.has(c.key) || seen.has(c.key))) { + seen.add(c.key); + continue; + } + if (c.key) seen.add(c.key); + const [claimed] = await db + .update(runnerCommands) + .set({ status: "running", startedAt: new Date() }) + .where(and(eq(runnerCommands.id, c.id), eq(runnerCommands.status, "queued"))) + .returning(); + if (!claimed) continue; + if (claimed.key) busyKeys.add(claimed.key); + const p = run(claimed).finally(() => { + if (claimed.key) busyKeys.delete(claimed.key); + inflight.delete(p); + void drain(); // the next command with this key + }); + inflight.add(p); + } + if (now - lastCleanup > 60 * 60 * 1000) { + lastCleanup = now; + await db.delete(runnerCommands).where(and(inArray(runnerCommands.status, ["done", "failed", "expired"]), lt(runnerCommands.createdAt, new Date(now - DAY)))); + } + }; + + async function drain(): Promise { + if (stopped) return; + if (draining) { + again = true; + return; + } + draining = true; + try { + do { + again = false; + await drainOnce().catch((e) => log(`runner service: ${(e as Error).message}`)); + } while (again && !stopped); + } finally { + draining = false; + } + } + + const path = runnerSocket(); + rmSync(path, { force: true }); // left over from a crashed run + const server: Server = createServer((sock) => { + sock.on("data", () => void drain()); + sock.on("error", () => {}); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(path, resolve); + }); + const timer = setInterval(() => void drain(), o.pollMs ?? 500); + timer.unref(); + log(`runner service listening on ${path}`); + void drain(); + + return { + drain: async () => { + await drain(); + await Promise.all([...inflight]); + }, + stop: async () => { + stopped = true; + clearInterval(timer); + await new Promise((resolve) => server.close(() => resolve())); + rmSync(path, { force: true }); + await Promise.all([...inflight]); + }, + }; +} + +/** Recent commands for `peppa runner commands`. */ +export async function recentRunnerCommands(db: Db, limit = 20) { + return db.select().from(runnerCommands).orderBy(desc(runnerCommands.id)).limit(limit); +} diff --git a/packages/runner/src/runners.ts b/packages/runner/src/runners.ts index a9b4a817..5c828a5f 100644 --- a/packages/runner/src/runners.ts +++ b/packages/runner/src/runners.ts @@ -19,6 +19,7 @@ import { pendingSessionQuestions, queuedItems, raiseSessionQuestion, + resolveTask, resolveRunnerSettings, updateSession, updateTask, @@ -30,6 +31,7 @@ import { and, eq } from "drizzle-orm"; import * as tmux from "./tmux.ts"; import { relaunchFresh, resolveTaskById, resumeSession, sendToSession, startRunner, startSession, type StartOptions } from "./sessions.ts"; import { removeWorktree, switchWorktreeStory } from "./worktree.ts"; +import { isRunnerClient, runnerCall } from "./runner-client.ts"; /** Task statuses of the "in progress" board column: the runner is busy with the story. */ const WORKING = ["proposing", "awaiting_approval", "in_progress", "blocked"]; @@ -68,6 +70,7 @@ export interface AssignResult { * takes it, else a new runner while the limit allows, else the shortest queue. */ export async function startTaskOnRunner(db: Db, ref: TaskRef, opts: StartOptions = {}): Promise { + if (isRunnerClient()) return runnerCall(db, "assign", { task: ref.key, opts }, { key: `task:${ref.task.id}` }); const rs = await resolveRunnerSettings(db, ref.project.id, ref.task.id); if (rs.mode === "story") return { started: (await startSession(db, ref.key, opts)).id }; if ((await queuedItems(db, { taskId: ref.task.id })).length) return { queued: true }; @@ -91,6 +94,7 @@ export async function startTaskOnRunner(db: Db, ref: TaskRef, opts: StartOptions /** PM puts a story into a runner's queue explicitly (web, CLI); taken when the runner is free. */ export async function queueTaskOnRunner(db: Db, sessionId: number, ref: TaskRef, prompt?: string): Promise { + if (isRunnerClient()) return void (await runnerCall(db, "queue", { sessionId, task: ref.key, prompt }, { key: `session:${sessionId}` })); const s = await getSession(db, sessionId); if (s.projectId !== ref.project.id) throw new PeppaError("Раннер из другого проекта"); if (FINISHED_SESSION_STATUSES.includes(s.status)) throw new PeppaError(`Раннер #${s.id} не работает`); @@ -236,6 +240,10 @@ export interface FreeRunnerOptions extends Pick { + if (isRunnerClient()) { + const r = await runnerCall<{ sessionId: number }>(db, "startFree", { projectId, opts }, { key: `project:${projectId}` }); + return getSession(db, r.sessionId); + } const project = await projectOf(db, projectId); const intro = `Это свободный раннер в проекте ${project.key} без стори: работай по просьбам человека в терминале, правила Пеппы (AGENTS.md) в силе. Стори, OpenSpec и PR — только если попросят.`; const prompt = opts.prompt?.trim() ? `${intro}\n\n${opts.prompt.trim()}` : `${intro}\n\nПока просто жди указаний.`; @@ -254,6 +262,7 @@ export async function renameRunner(db: Db, sessionId: number, name: string): Pro * that runner; the agent is told to carry on by Peppa's rules. */ export async function promoteRunner(db: Db, sessionId: number, t: { title: string; description?: string; goalId?: number | null }): Promise { + if (isRunnerClient()) return resolveTask(db, (await runnerCall<{ key: string }>(db, "promote", { sessionId, story: t }, { key: `session:${sessionId}` })).key); const s = await getSession(db, sessionId); if (s.taskId) throw new PeppaError(`Раннер #${s.id} уже ведёт стори ${s.taskKey}`); if (t.title.trim().length < 3) throw new PeppaError("Нужно название стори"); diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index fa478a3f..ff25f745 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -11,6 +11,7 @@ import { expireSessionQuestions, FINISHED_SESSION_STATUSES, getSession, + getQuestion, listSessions, loadSharedRules, PeppaError, @@ -38,6 +39,7 @@ import { runDir } from "./run-settings.ts"; import * as tmux from "./tmux.ts"; import { onReleaseAnswer } from "./deploy.ts"; import { ensureWorktree } from "./worktree.ts"; +import { isRunnerClient, runnerCall } from "./runner-client.ts"; export interface StartOptions { /** Extra instructions appended to the default "work on " prompt. */ @@ -65,6 +67,11 @@ const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`; /** Starts an interactive agent session (Claude Code or Codex) for a task in a detached tmux session. */ export async function startSession(db: Db, taskInput: string, opts: StartOptions = {}): Promise { const ref = await resolveTask(db, taskInput, opts.defaultProjectKey); + // PEP-21: web and bot only enqueue — the runner service starts the agent. + if (isRunnerClient()) { + const r = await runnerCall<{ sessionId: number }>(db, "start", { task: ref.key, opts }, { key: `task:${ref.task.id}` }); + return getSession(db, r.sessionId); + } // PEP-23: the project's autonomy (PM approves proposals, Peppa merges) goes into the prompt. const note = agentAutonomyNote(await getAutonomy(db, ref.project.id)); const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, opts.prompt].filter(Boolean).join("\n\n"); @@ -134,6 +141,10 @@ export async function runnerCwd(db: Db, s: SessionView): Promise { * the same conversation (claude --resume / codex resume) when its id is known. */ export async function resumeSession(db: Db, sessionId: number, opts: StartOptions = {}): Promise { + if (isRunnerClient()) { + await runnerCall(db, "resume", { sessionId, opts }, { key: `session:${sessionId}` }); + return getSession(db, sessionId); + } const s = await getSession(db, sessionId); await assertBudgetOpen(db, s.taskId); if (await tmux.hasSession(s.tmuxName)) { @@ -245,6 +256,7 @@ async function launch( } export async function sendToSession(db: Db, sessionId: number, text: string): Promise { + if (isRunnerClient()) return void (await runnerCall(db, "send", { sessionId, text }, { key: `session:${sessionId}` })); const s = await getSession(db, sessionId); if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`); // Recorded before typing: the prompt hook answers only questions older than this input. @@ -254,6 +266,7 @@ export async function sendToSession(db: Db, sessionId: number, text: string): Pr } export async function stopSession(db: Db, sessionId: number): Promise { + if (isRunnerClient()) return void (await runnerCall(db, "stop", { sessionId }, { key: `session:${sessionId}` })); const s = await getSession(db, sessionId); if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName); await expireSessionQuestions(db, s.id, "(неактуально: сессия остановлена)"); @@ -283,6 +296,12 @@ export async function answerAndDeliver( answer: string, via: NonNullable, ): Promise<{ delivered: boolean; question: Question }> { + if (isRunnerClient()) { + const pre = await getQuestion(db, questionId); + const key = pre.sessionId ? `session:${pre.sessionId}` : pre.taskId ? `task:${pre.taskId}` : null; + const r = await runnerCall<{ delivered: boolean; questionId: number }>(db, "answer", { questionId, answer, via }, { key }); + return { delivered: r.delivered, question: await getQuestion(db, r.questionId) }; + } const q = await answerQuestion(db, questionId, answer, via); // A human answered: the agent may again continue on its own a couple of times. if (q.sessionId) await updateSession(db, q.sessionId, { autoNudges: 0 }); diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 96b263ac..d9fb996b 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -1,6 +1,7 @@ import { execFile, spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { promisify } from "node:util"; +import { isRunnerClient, runnerCall, runnerClientDb } from "./runner-client.ts"; const run = promisify(execFile); const TMUX = process.env.PEPPA_TMUX_BIN ?? "tmux"; @@ -20,7 +21,16 @@ export interface NewTmuxSession { width?: number; } +/** + * PEP-21 safety net: in a client process (web, bot) operations that create, kill or type into + * tmux sessions run in the runner service. Reading the screen stays local. + */ +async function viaService(op: string, args: unknown[]): Promise { + await runnerCall(runnerClientDb(), "tmux", { op, args }, { timeoutMs: 15_000 }); +} + export async function newSession(s: NewTmuxSession): Promise { + if (isRunnerClient()) return viaService("newSession", [s]); const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]); // Keep the server up when its last session ends: otherwise a session created while the // previous last one is being killed can land on a server that is shutting down. @@ -83,6 +93,7 @@ export async function capturePane(name: string, history = 0): Promise { * lands as one prompt instead of being submitted line by line. */ export async function sendText(name: string, text: string, submit = true): Promise { + if (isRunnerClient()) return viaService("sendText", [name, text, submit]); const buffer = `peppa-${process.pid}-${Date.now()}`; await new Promise((resolve, reject) => { const p = spawn(TMUX, [...SOCKET, "load-buffer", "-b", buffer, "-"], { stdio: ["pipe", "ignore", "pipe"] }); @@ -102,10 +113,12 @@ export async function sendText(name: string, text: string, submit = true): Promi /** Sends tmux key names (e.g. "1", "Enter", "Escape", "C-c"). */ export async function sendKeys(name: string, ...keys: string[]): Promise { + if (isRunnerClient()) return viaService("sendKeys", [name, ...keys]); await tmux("send-keys", "-t", `=${name}:`, ...keys); } export async function killSession(name: string): Promise { + if (isRunnerClient()) return viaService("killSession", [name]); await tmux("kill-session", "-t", `=${name}`); } @@ -137,5 +150,6 @@ export async function capturePaneAnsi(name: string, start: number | "-", end?: n /** Sends raw bytes to the pane as keys (`send-keys -H`): arrows, Ctrl-C, UTF-8 — as typed. */ export async function sendHex(name: string, bytes: Uint8Array): Promise { if (!bytes.length) return; + if (isRunnerClient()) return viaService("sendHex", [name, Array.from(bytes)]); await tmux("send-keys", "-t", `=${name}:`, "-H", ...Array.from(bytes, (b) => b.toString(16).padStart(2, "0"))); } diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index db59a943..644a1f9c 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -27,6 +27,8 @@ import { pollChecks } from "./ci-feedback.ts"; import { reviewTick } from "./reviewer.ts"; import { autonomyTick } from "./autonomy.ts"; import { budgetTick } from "./budgets.ts"; +import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts"; +import { serveRunnerCommands, type RunnerService } from "./runner-service.ts"; export interface WatchdogOptions { /** Current time (tests move it instead of waiting). */ @@ -35,6 +37,8 @@ export interface WatchdogOptions { /** A running session with an unchanged screen for this long is "stalled". */ stallMs: number; log?: (msg: string) => void; + /** PEP-21: serve runner commands in this process (default true for runWatchdog). */ + serveCommands?: boolean; } // Claude Code's limit banners ("…usage limit reached… resets 3pm", "You've hit your limit"). @@ -45,11 +49,6 @@ function screenTail(screen: string, lines: number): string { return screen.split("\n").map((l) => l.trimEnd()).filter(Boolean).slice(-lines).join("\n"); } -// Screen hash per session, kept across ticks. -const lastScreen = new Map(); -const limitAlerted = new Set(); -const thresholdSeen = new Set(); - export async function tick(db: Db, opts: WatchdogOptions): Promise { // PEP-48: what the watchdog does is Peppa's own doing. return runAsActor({ kind: "system", channel: "watchdog" }, () => tickInner(db, opts)); @@ -57,13 +56,20 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise { async function tickInner(db: Db, opts: WatchdogOptions): Promise { const log = opts.log ?? (() => {}); + const now = opts.now ?? new Date(); + // PEP-28: thresholds of the watchdog (platform.watchdog over env). + const cfg = await getWatchdogSettings(db); for (const s of await listSessions(db, { active: true })) { try { - await checkSession(db, s, opts, log); + await checkSession(db, s, opts, cfg, log); } catch (e) { log(`session #${s.id}: ${(e as Error).message}`); } } + // PEP-28: planned automatic restarts, reminders/escalation, runners waiting for nobody. + await restartTick(db, { now, cfg, log }).catch((e) => log(`restarts: ${(e as Error).message}`)); + await remindTick(db, { now, cfg, log }).catch((e) => log(`reminders: ${(e as Error).message}`)); + await idleStopTick(db, { now, cfg, log }).catch((e) => log(`idle: ${(e as Error).message}`)); // Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup. await runnerTick(db, { log }).catch((e) => log(`runners: ${(e as Error).message}`)); // Story budgets (PEP-43): over the limit → pause and ask the PM. @@ -76,7 +82,7 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`)); } -async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) { +async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) { if (s.tmuxName.startsWith("pending-")) return; const nowDate = opts.now ?? new Date(); // Rate-limited runner: move it to a free subscription of its pool (PEP-39), else continue @@ -103,9 +109,9 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: if (!(await tmux.hasSession(s.tmuxName))) { log(`${label}: tmux session gone`); - await updateSession(db, s.id, { status: "failed", endedAt: new Date() }); await logSessionEvent(db, s, "tmux_gone"); - await raiseSessionQuestion(db, s, "attention", `Сессия ${s.taskKey ?? s.id} пропала (tmux-сессии больше нет).`); + // PEP-28: a story at work is restarted by itself (within the limit), else the PM is asked. + await onRunnerCrash(db, s, "gone", `Сессия ${s.taskKey ?? s.id} пропала (tmux-сессии больше нет).`, { now: nowDate, cfg, log }); return; } @@ -114,12 +120,10 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: const ok = pane.exitStatus === 0; log(`${label}: claude exited with ${pane.exitStatus}`); const tail = screenTail(await tmux.capturePane(s.tmuxName, 200), 15); - await updateSession(db, s.id, { status: ok ? "done" : "failed", endedAt: new Date() }); await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail }); - if (!ok) { - await raiseSessionQuestion(db, s, "attention", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`); - } await tmux.killSession(s.tmuxName).catch(() => {}); + if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() }); + else await onRunnerCrash(db, s, "crash", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`, { now: nowDate, cfg, log }); return; } @@ -127,18 +131,18 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: const hash = createHash("sha1").update(screen).digest("hex"); const now = (opts.now ?? new Date()).getTime(); let last = s.lastActivityAt?.getTime() ?? now; - if (lastScreen.get(s.id) !== hash) { + // PEP-28: the screen hash lives in the DB — a restarted watchdog does not see "new activity". + if (s.watchState?.screen !== hash) { last = now; - lastScreen.set(s.id, hash); - await updateSession(db, s.id, { + await patchWatch(db, s, { screen: hash, stallAlertAt: undefined }, { lastActivityAt: new Date(now), ...(s.status === "stalled" ? { status: "running" as const } : {}), }); } // Fallback for limits that don't come through the StopFailure hook. - if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && !limitAlerted.has(`${s.id}:${s.generation}`)) { - limitAlerted.add(`${s.id}:${s.generation}`); + if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) { + await patchWatch(db, s, { limitGen: s.generation }); const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? ""; log(`${label}: usage limit`); await logSessionEvent(db, s, "usage_limit", { line }); @@ -148,8 +152,8 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: } // PEP-39: the CLI warns the subscription is close to its limit — switch at the turn end. - if (!s.rotateReason && s.subscriptionId != null && rotationEnabled() && !thresholdSeen.has(`${s.id}:${s.generation}`) && usageWarning(screen)) { - thresholdSeen.add(`${s.id}:${s.generation}`); + if (!s.rotateReason && s.subscriptionId != null && rotationEnabled() && s.watchState?.thresholdGen !== s.generation && usageWarning(screen)) { + await patchWatch(db, s, { thresholdGen: s.generation }); const line = screen.split("\n").reverse().find((l) => usageWarning(l))?.trim() ?? ""; await logSessionEvent(db, s, "usage_threshold", { line }); if (await planRotation(db, s, "threshold", new Date(now))) { @@ -158,9 +162,12 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: } } + // PEP-28: the stall alert went unanswered long enough — restart the runner. + if (s.status === "stalled" && (await restartStalled(db, s, { now: nowDate, cfg, log }))) return; + if (s.status === "running" && now - last > opts.stallMs) { log(`${label}: stalled`); - await updateSession(db, s.id, { status: "stalled" }); + await patchWatch(db, s, { stallAlertAt: now }, { status: "stalled" }); await logSessionEvent(db, s, "stalled", { idleMinutes: Math.round((now - last) / 60000) }); if ((await pendingSessionQuestions(db, s.id)).length === 0) { const tail = screenTail(screen, 12); @@ -179,6 +186,14 @@ let lastCiPoll = 0; export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise { const log = opts.log ?? (() => {}); log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`); + // PEP-21: the runner service — web, bot and the remote MCP hand their runner commands here. + let service: RunnerService | null = null; + if (opts.serveCommands !== false) { + service = await serveRunnerCommands(db, { log }).catch((e) => { + log(`runner service not started: ${(e as Error).message}`); + return null; + }); + } while (!signal?.aborted) { await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); // Heartbeat and the check on the bot and the web (PEP-20). @@ -194,6 +209,7 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`)); await new Promise((r) => setTimeout(r, opts.intervalMs)); } + await service?.stop(); } /** diff --git a/packages/testkit/test/recovery.test.ts b/packages/testkit/test/recovery.test.ts new file mode 100644 index 00000000..4b797743 --- /dev/null +++ b/packages/testkit/test/recovery.test.ts @@ -0,0 +1,205 @@ +// PEP-28: watchdog 2.0 — automatic restarts, reminders and escalation, idle cleanup, +// the watchdog's memory in the DB. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { after, afterEach, describe, test } from "node:test"; +import { and, eq, like } from "drizzle-orm"; +process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; +import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; + +const { events, questions, telegramOutbox, users } = await import("@peppa/db"); + +after(teardown); +afterEach(() => runner.setWatchdogSettings(db, ["reset"])); + +const MIN = 60_000; +const sess = (id: number) => core.getSession(db, id); +const tickAt = (now: Date, stallMs = 3_600_000) => runner.tick(db, { intervalMs: 0, stallMs, now }); +const eventsOf = async (sid: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, type))); + +async function storyAtWork(scenario: Parameters[0]) { + const p = await project(scenario); + const ref = await core.resolveTask(db, p.taskKey); + await core.updateTask(db, ref, { status: "in_progress" }); + return p; +} + +describe("Авто-перезапуск упавшего раннера", () => { + test("Падение и восстановление", async () => { + const p = await storyAtWork({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "Поднялся." }]] }); + const sid = await p.start(); + await p.waitLog("crashed", (e) => e.ev === "exit"); + const t0 = new Date(); + await waitFor("restart planned", async () => { + await tickAt(t0); + return (await sess(sid)).watchState?.restartAt; + }); + const s = await sess(sid); + assert.equal(s.status, "failed"); + assert.ok(Math.abs(s.watchState!.restartAt! - (t0.getTime() + MIN)) < 1000, "after 1 minute"); + assert.equal((await p.pending(sid)).length, 0, "no question for the PM"); + + await tickAt(new Date(t0.getTime() + 30_000)); + assert.equal((await sess(sid)).status, "failed", "waits for the pause"); + + await tickAt(new Date(t0.getTime() + MIN + 1000)); + const start = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2"); + assert.equal(start.resume, s.conversationId, "same conversation"); + const [ev] = await eventsOf(sid, "auto_restarted"); + assert.deepEqual({ attempt: (ev!.payload as any).attempt, of: (ev!.payload as any).of }, { attempt: 1, of: 3 }); + assert.equal((await sess(sid)).watchState?.restarts?.length, 1); + await runner.stopSession(db, sid); + }); + + test("Предел исчерпан", async () => { + await runner.setWatchdogSettings(db, ["restartMax=1"]); + const p = await storyAtWork({ turns: [[{ crash: 1 }]] }); + const sid = await p.start(); + await core.updateSession(db, sid, { watchState: { restarts: [Date.now() - 10 * MIN] } }); + await p.waitLog("crashed", (e) => e.ev === "exit"); + const q = await waitFor("question", async () => (await tickAt(new Date()), (await p.pending(sid)).find((q) => q.kind === "attention"))); + assert.match(q.text, /упал \(код 1\)/); + assert.match(q.text, /авто-перезапуски исчерпаны \(1 за 24 ч\)/); + assert.equal((await sess(sid)).watchState?.restartAt, undefined); + }); + + test("Выключить перезапуск: restartMax=0", async () => { + await runner.setWatchdogSettings(db, ["restartMax=0"]); + assert.equal((await runner.getWatchdogSettings(db)).restartMax, 0); + const p = await storyAtWork({ turns: [[{ crash: 2 }]] }); + const sid = await p.start(); + await p.waitLog("crashed", (e) => e.ev === "exit"); + const q = await waitFor("question", async () => (await tickAt(new Date()), (await p.pending(sid)).find((q) => q.kind === "attention"))); + assert.doesNotMatch(q.text, /исчерпаны/); + }); + + test("Не трогаем стори не в работе", async () => { + const p = await project({ turns: [[{ crash: 1 }]] }); // backlog + const sid = await p.start(); + await p.waitLog("crashed", (e) => e.ev === "exit"); + await waitFor("question", async () => (await tickAt(new Date()), (await p.pending(sid)).find((q) => q.kind === "attention"))); + assert.equal((await sess(sid)).watchState?.restartAt, undefined); + }); + + test("PM вмешался: stop отменяет план", async () => { + const p = await storyAtWork({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "?" }]] }); + const sid = await p.start(); + await p.waitLog("crashed", (e) => e.ev === "exit"); + const t0 = new Date(); + await waitFor("restart planned", async () => (await tickAt(t0), (await sess(sid)).watchState?.restartAt)); + await runner.stopSession(db, sid); + await tickAt(new Date(t0.getTime() + 2 * MIN)); + assert.equal((await sess(sid)).status, "done"); + assert.equal((await eventsOf(sid, "auto_restarted")).length, 0); + }); + + test("Пропавший tmux тоже перезапускается", async () => { + const p = await storyAtWork({ turns: [[{ say: "Жду." }]], resumeTurns: [[{ say: "Вернулся." }]] }); + const sid = await p.start(); + await p.waitLog("turn 0", (e) => e.ev === "prompt"); + execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await sess(sid)).tmuxName}`]); + const t0 = new Date(); + await tickAt(t0); + assert.equal((await sess(sid)).watchState?.restartReason, "gone"); + await tickAt(new Date(t0.getTime() + MIN + 1000)); + await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2"); + await runner.stopSession(db, sid); + }); +}); + +describe("Зависший раннер перезапускается", () => { + test("Экран не меняется час после алерта", async () => { + const p = await storyAtWork({ turns: [[{ say: "Думаю." }, { hang: true }]], resumeTurns: [[{ say: "Отвис." }]] }); + const sid = await p.start(); + await p.waitLog("turn 0", (e) => e.ev === "prompt"); + await new Promise((r) => setTimeout(r, 1500)); + const t0 = Date.now(); + await tickAt(new Date(t0)); // remembers the screen + await tickAt(new Date(t0 + 10 * MIN), 5 * MIN); // stalled → alert + const s = await sess(sid); + assert.equal(s.status, "stalled"); + assert.ok(s.watchState?.stallAlertAt); + await tickAt(new Date(t0 + 30 * MIN), 5 * MIN); + assert.equal((await sess(sid)).status, "stalled", "not yet"); + await tickAt(new Date(t0 + 75 * MIN), 5 * MIN); + await p.waitLog("restarted", (e) => e.ev === "start" && e.gen === "2"); + const [ev] = await eventsOf(sid, "auto_restarted"); + assert.equal((ev!.payload as any).reason, "stall"); + await runner.stopSession(db, sid); + }); +}); + +describe("Напоминание и эскалация вопросов", () => { + test("Вопрос висит", async () => { + const p = await project({ turns: [] }); + const owner = await core.upsertUserFromGitea(db, { id: 8101, login: "mock-owner-rem" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 8101, telegramUserId: 8101 }).where(eq(users.id, owner.id)); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + await core.setPlatformAdmins(db, ["mock-owner-rem"]); + const t0 = Date.now(); + const [q] = await db.insert(questions).values({ projectId: proj.id, kind: "question", text: "Какую БД берём?", createdAt: new Date(t0) }).returning(); + const sent = async () => + (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `%q${q!.id}%`))).map((r) => String(r.params.text)); + const at = (m: number) => ({ now: new Date(t0 + m * MIN), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} }); + + await runner.remindTick(db, at(10)); + assert.equal((await sent()).length, 0); + await runner.remindTick(db, at(31)); + assert.match((await sent())[0]!, /⏰ .*Вопрос #\d+ ждёт ответа 31 мин/); + await runner.remindTick(db, at(32)); + assert.equal((await sent()).length, 1, "once"); + await runner.remindTick(db, at(61)); + assert.equal((await sent()).length, 2); + await runner.remindTick(db, at(121)); + const all = await sent(); + assert.equal(all.length, 3); + assert.match(all[2]!, /🚨 .*без ответа 121 мин/); + await runner.remindTick(db, at(200)); + assert.equal((await sent()).length, 3, "escalated once"); + assert.equal((await core.getQuestion(db, q!.id)).reminders, 3); + }); +}); + +describe("Уборка давних waiting_input", () => { + test("Раннер ждёт сутки", async () => { + const p = await storyAtWork({ turns: [[{ say: "Готов." }]] }); + const sid = await p.start(); + await p.waitLog("turn 0", (e) => e.ev === "prompt"); + await core.updateSession(db, sid, { status: "waiting_input", lastActivityAt: new Date(Date.now() - 25 * 3600_000) }); + const n = await runner.idleStopTick(db, { now: new Date(), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} }); + assert.equal(n, 1); + assert.equal((await sess(sid)).status, "done"); + assert.equal((await eventsOf(sid, "idle_stopped")).length, 1); + }); + + test("Открытый вопрос не даёт остановить", async () => { + const p = await storyAtWork({ turns: [[{ say: "Готов." }]] }); + const sid = await p.start(); + await p.waitLog("turn 0", (e) => e.ev === "prompt"); + await core.updateSession(db, sid, { status: "waiting_input", lastActivityAt: new Date(Date.now() - 25 * 3600_000) }); + await core.raiseSessionQuestion(db, await sess(sid), "question", "Что дальше?"); + const n = await runner.idleStopTick(db, { now: new Date(), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} }); + assert.equal(n, 0); + await runner.stopSession(db, sid); + }); +}); + +describe("Состояние вачдога в БД", () => { + test("Рестарт вачдога не повторяет сообщение о лимите", async () => { + const p = await project({ turns: [[{ say: "You've hit your limit · resets 5pm" }]] }); + const sid = await p.start(); + await p.waitLog("turn 0", (e) => e.ev === "prompt"); + await waitFor("banner on screen", async () => (await runner.tmux.capturePane((await sess(sid)).tmuxName)).includes("hit your limit")); + const s = await sess(sid); + // What a previous watchdog run remembered: the limit of this generation was handled. + await core.updateSession(db, sid, { watchState: { limitGen: s.generation } }); + await tickAt(new Date()); + assert.equal((await eventsOf(sid, "usage_limit")).length, 0, "no repeat after a restart"); + await core.updateSession(db, sid, { watchState: {} }); + await tickAt(new Date()); + assert.equal((await eventsOf(sid, "usage_limit")).length, 1); + assert.equal((await sess(sid)).watchState?.limitGen, s.generation); + await runner.stopSession(db, sid); + }); +}); diff --git a/packages/testkit/test/runner-service.test.ts b/packages/testkit/test/runner-service.test.ts new file mode 100644 index 00000000..054f47bb --- /dev/null +++ b/packages/testkit/test/runner-service.test.ts @@ -0,0 +1,159 @@ +// PEP-21: web, bot and the remote MCP enqueue runner commands; the runner service (the +// watchdog process) runs them. Here one test process plays both roles: the client flag is +// on, the service runs its handlers in its own context. +import assert from "node:assert/strict"; +import { createServer } from "node:net"; +import { rmSync } from "node:fs"; +import { after, afterEach, before, describe, test } from "node:test"; +import { eq, desc } from "drizzle-orm"; +process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; +import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; + +const { runnerCommands, events } = await import("@peppa/db"); + +let service: Awaited> | null = null; +const logs: string[] = []; + +async function startService() { + service = await runner.serveRunnerCommands(db, { pollMs: 100, log: (m) => void logs.push(m) }); +} +async function stopService() { + await service?.stop(); + service = null; +} +const lastCommand = async () => (await db.select().from(runnerCommands).orderBy(desc(runnerCommands.id)).limit(1))[0]!; + +before(startService); +afterEach(() => runner.setRunnerClient(false)); +after(async () => { + await stopService(); + await teardown(); +}); + +describe("Процессы агентов запускает только раннер-сервис", () => { + test("PM двигает стори в работу из веба", async () => { + const p = await project({ turns: [[{ say: "Работаю." }]] }); + const pm = await core.upsertUserFromGitea(db, { id: 7001, login: "mock-pm-rs" }, { access_token: "x" }); + const ref = await core.resolveTask(db, p.taskKey); + runner.setRunnerClient(true, db); + const r = await core.runAsActor({ kind: "user", userId: pm.id, channel: "web" }, () => runner.moveTask(db, ref, "in_progress")); + assert.ok(r.started, "runner started"); + const c = await lastCommand(); + assert.equal(c.kind, "move"); + assert.equal(c.status, "done"); + assert.equal(c.key, `task:${ref.task.id}`); + assert.equal((c.actor as { userId?: number }).userId, pm.id); + await p.waitLog("agent started", (e) => e.ev === "start"); + const [started] = await db.select().from(events).where(eq(events.sessionId, r.started!)).orderBy(events.id); + assert.equal(started!.type, "started"); + assert.equal(started!.actorUserId, pm.id, "the journal shows the PM as the author"); + assert.equal(started!.actorChannel, "web"); + await runner.stopSession(db, r.started!); + assert.equal((await core.getSession(db, r.started!)).status, "done"); + assert.equal((await lastCommand()).kind, "stop"); + }); + + test("Ответ и ввод идут в tmux через сервис; payload tmux не хранится", async () => { + const p = await project({ turns: [[{ say: "Жду." }], [{ say: "Получил." }]] }); + const sid = await p.start(); + await p.waitLog("turn 0", (e) => e.ev === "prompt"); + runner.setRunnerClient(true, db); + await runner.tmux.sendText((await core.getSession(db, sid)).tmuxName, "секретный код 123"); + const c = await lastCommand(); + assert.equal(c.kind, "tmux"); + assert.equal(c.status, "done"); + assert.deepEqual(c.payload, { op: "sendText", redacted: true }); + await p.waitLog("typed through the service", (e) => e.ev === "prompt" && String(e.prompt).includes("секретный код")); + await runner.stopSession(db, sid); + }); + + test("Двойное «В работу» запускает одного агента", async () => { + const p = await project({ turns: [[{ say: "Один." }]] }); + const ref = await core.resolveTask(db, p.taskKey); + runner.setRunnerClient(true, db); + const [a, b] = await Promise.all([runner.moveTask(db, ref, "in_progress"), runner.moveTask(db, ref, "in_progress")]); + const live = await core.listSessions(db, { active: true, taskId: ref.task.id }); + assert.equal(live.length, 1, "one agent"); + assert.equal([a.started, b.started].filter(Boolean).length, 1); + await runner.stopSession(db, live[0]!.id); + }); + + test("Ошибка домена доходит тем же текстом", async () => { + const p = await project({ turns: [[{ say: "Жив." }]] }); + const sid = await p.start(); + runner.setRunnerClient(true, db); + await assert.rejects(runner.resumeSession(db, sid), (e: Error) => e instanceof core.PeppaError && /is still running/.test(e.message)); + assert.equal((await lastCommand()).errorKind, "peppa"); + runner.setRunnerClient(false); + await runner.stopSession(db, sid); + }); +}); + +describe("Недоступный сервис — понятная ошибка", () => { + test("Вачдог остановлен", async () => { + const p = await project({ turns: [[{ say: "Жив." }]] }); + const sid = await p.start(); + await stopService(); + runner.setRunnerClient(true, db); + await assert.rejects(runner.stopSession(db, sid), /Раннер-сервис не запущен/); + assert.equal((await lastCommand()).status, "expired"); + runner.setRunnerClient(false); + assert.notEqual((await core.getSession(db, sid)).status, "done", "nothing happened"); + await startService(); + await service!.drain(); + assert.notEqual((await core.getSession(db, sid)).status, "done", "the expired command never runs"); + await runner.stopSession(db, sid); + }); + + test("Сервис завис: не взял команду за отведённое время", async () => { + const p = await project({ turns: [[{ say: "Жив." }]] }); + const sid = await p.start(); + await stopService(); + // Something listens on the socket but never takes commands. + const fake = createServer((s) => (s.on("error", () => {}), s.resume())); + await new Promise((r) => fake.listen(runner.runnerSocket(), r)); + process.env.PEPPA_RUNNER_PICKUP_SEC = "1"; + try { + runner.setRunnerClient(true, db); + await assert.rejects(runner.stopSession(db, sid), /не взял команду за 1 с/); + assert.equal((await lastCommand()).status, "expired"); + } finally { + delete process.env.PEPPA_RUNNER_PICKUP_SEC; + runner.setRunnerClient(false); + await new Promise((r) => fake.close(() => r())); + rmSync(runner.runnerSocket(), { force: true }); + } + await startService(); + await service!.drain(); + assert.notEqual((await core.getSession(db, sid)).status, "done", "the late command is not run when the service wakes up"); + await runner.stopSession(db, sid); + }); + + test("Рестарт сервиса посреди команды", async () => { + await stopService(); + const [row] = await db.insert(runnerCommands).values({ kind: "stop", payload: { sessionId: 1 }, status: "running", startedAt: new Date() }).returning(); + await startService(); + const [c] = await db.select().from(runnerCommands).where(eq(runnerCommands.id, row!.id)); + assert.equal(c!.status, "failed"); + assert.match(c!.error!, /перезапустился во время выполнения/); + }); + + test("Второй сервис рядом с живым не запускается", async () => { + await assert.rejects(runner.serveRunnerCommands(db), /уже запущен/); + }); + + test("Аварийный режим на месте", async () => { + process.env.PEPPA_RUNNER_MODE = "inline"; + try { + runner.setRunnerClient(true, db); + assert.equal(runner.isRunnerClient(), false); + } finally { + delete process.env.PEPPA_RUNNER_MODE; + } + }); +}); + +test("CLI видит сервис", async () => { + assert.equal(await runner.runnerServiceAlive(), true); + await waitFor("log line", async () => logs.some((l) => l.includes("listening"))); +});