From acf2bb9623c366d604adf4ced3ff43e254eeb15d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 07:25:19 +0500
Subject: [PATCH 001/444] PEP-21/28: runner service (command queue in the
watchdog), watchdog 2.0 auto-recovery and escalation
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 2 +
apps/bot/src/index.ts | 6 +-
apps/web/instrumentation.ts | 5 +-
.../design.md | 65 +
.../proposal.md | 65 +
.../specs/runner-service/spec.md | 60 +
.../specs/watchdog-recovery/spec.md | 66 +
.../tasks.md | 19 +
openspec/specs/runner-service/spec.md | 65 +
openspec/specs/watchdog-recovery/spec.md | 71 +
packages/cli/src/index.ts | 32 +-
packages/core/src/sessions.ts | 2 +-
.../db/migrations/0012_runner_service.sql | 19 +
.../db/migrations/meta/0012_snapshot.json | 3519 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 50 +
packages/runner/src/flow.ts | 9 +
packages/runner/src/index.ts | 3 +
packages/runner/src/recovery.ts | 295 ++
packages/runner/src/runner-client.ts | 127 +
packages/runner/src/runner-service.ts | 197 +
packages/runner/src/runners.ts | 9 +
packages/runner/src/sessions.ts | 19 +
packages/runner/src/tmux.ts | 14 +
packages/runner/src/watchdog.ts | 58 +-
packages/testkit/test/recovery.test.ts | 205 +
packages/testkit/test/runner-service.test.ts | 159 +
27 files changed, 5122 insertions(+), 26 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-21-28-runner-service/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-21-28-runner-service/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/runner-service/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-21-28-runner-service/specs/watchdog-recovery/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-21-28-runner-service/tasks.md
create mode 100644 openspec/specs/runner-service/spec.md
create mode 100644 openspec/specs/watchdog-recovery/spec.md
create mode 100644 packages/db/migrations/0012_runner_service.sql
create mode 100644 packages/db/migrations/meta/0012_snapshot.json
create mode 100644 packages/runner/src/recovery.ts
create mode 100644 packages/runner/src/runner-client.ts
create mode 100644 packages/runner/src/runner-service.ts
create mode 100644 packages/testkit/test/recovery.test.ts
create mode 100644 packages/testkit/test/runner-service.test.ts
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")));
+});
--
2.45.2
From 53ac7efdcc352d342337a89fcaa94ebd758ff79d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 07:13:57 +0500
Subject: [PATCH 002/444] PEP-30/41/31: project memory, agent model per story
with escalation, first-run checklist
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- PEP-30: .peppa/memory.md in the project repo (core/memory.ts), agent MCP get_memory/remember
(dedupe, 12k size limit, replace to compact), runner appends memory + last finished stories
to the launch rules, RULES.md rule, memory on the project «Спеки» tab.
- PEP-41: agent settings platform → project → story (provider, model, effort, escalation model
after N failures, fallback provider); Claude --effort / Codex model_reasoning_effort;
sticky escalation relaunches a live runner on the stronger model (sendWithEscalation from
CI feedback and the reviewer); fallback provider when the main one has no working
subscription; web panels, MCP PM `agent`, CLI `peppa project agent`.
- PEP-31: first-run checklist on the home page (core/onboarding.ts), hide button,
«Агенты не запустятся» warning on the project page when its pool has no working subscription.
No migrations.
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 3 +
apps/web/app/(app)/actions.ts | 28 +++
apps/web/app/(app)/help/page.tsx | 6 +-
apps/web/app/(app)/p/[key]/page.tsx | 28 ++-
apps/web/app/(app)/p/[key]/tabs.tsx | 17 ++
apps/web/app/(app)/page.tsx | 6 +-
apps/web/app/(app)/settings/page.tsx | 4 +-
apps/web/app/(app)/t/[key]/page.tsx | 7 +
apps/web/components/AgentModel.tsx | 115 ++++++++++
apps/web/components/Onboarding.tsx | 52 +++++
.../design.md | 10 +
.../proposal.md | 33 +++
.../specs/project-memory/spec.md | 35 +++
.../2026-11-14-pep-30-project-memory/tasks.md | 11 +
.../2026-11-14-pep-31-onboarding/design.md | 14 ++
.../2026-11-14-pep-31-onboarding/proposal.md | 25 +++
.../specs/onboarding/spec.md | 25 +++
.../2026-11-14-pep-31-onboarding/tasks.md | 8 +
.../2026-11-14-pep-41-agent-model/design.md | 17 ++
.../2026-11-14-pep-41-agent-model/proposal.md | 37 ++++
.../specs/agent-model/spec.md | 37 ++++
.../2026-11-14-pep-41-agent-model/tasks.md | 12 +
openspec/specs/agent-model/spec.md | 42 ++++
openspec/specs/onboarding/spec.md | 30 +++
openspec/specs/project-memory/spec.md | 40 ++++
packages/cli/src/index.ts | 28 +++
packages/core/src/agent-model.ts | 209 ++++++++++++++++++
packages/core/src/index.ts | 3 +
packages/core/src/memory.ts | 148 +++++++++++++
packages/core/src/onboarding.ts | 87 ++++++++
packages/core/src/subscriptions.ts | 2 +-
packages/mcp/src/index.ts | 44 ++++
packages/mcp/src/manager.ts | 59 ++++-
packages/runner/src/ci-feedback.ts | 4 +-
packages/runner/src/escalation.ts | 27 +++
packages/runner/src/index.ts | 1 +
packages/runner/src/providers.ts | 5 +
packages/runner/src/reviewer.ts | 3 +-
packages/runner/src/sessions.ts | 49 +++-
packages/testkit/test/agent-smarts.test.ts | 202 +++++++++++++++++
template/RULES.md | 7 +
41 files changed, 1499 insertions(+), 21 deletions(-)
create mode 100644 apps/web/components/AgentModel.tsx
create mode 100644 apps/web/components/Onboarding.tsx
create mode 100644 openspec/changes/archive/2026-11-14-pep-30-project-memory/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-30-project-memory/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-30-project-memory/specs/project-memory/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-30-project-memory/tasks.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-31-onboarding/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-31-onboarding/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-31-onboarding/specs/onboarding/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-31-onboarding/tasks.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-41-agent-model/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-41-agent-model/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-41-agent-model/specs/agent-model/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-41-agent-model/tasks.md
create mode 100644 openspec/specs/agent-model/spec.md
create mode 100644 openspec/specs/onboarding/spec.md
create mode 100644 openspec/specs/project-memory/spec.md
create mode 100644 packages/core/src/agent-model.ts
create mode 100644 packages/core/src/memory.ts
create mode 100644 packages/core/src/onboarding.ts
create mode 100644 packages/runner/src/escalation.ts
create mode 100644 packages/testkit/test/agent-smarts.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index eca7ba56..a30f38fc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -47,6 +47,9 @@
- **Агент-ревьюер (PEP-26)**: настройка проекта `review_settings` (вкл/выкл, по умолчанию выкл; `max_iterations` = 2; `rules` PM) — веб «⋯ Настройки проекта → Ревьюер». Агент зовёт MCP `update_task(status: review)`, гейт PEP-57 пройден → `requestReview` (runner/reviewer.ts): ставит `code_reviews` (queued, головной SHA PR) и сразу запускает в процессе MCP, агенту — «закончи ход» (стори остаётся `in_progress`; Stop-хук не подгоняет, пока `pendingReview`). Ревью: дифф `GiteaClient.pullDiff` → `$PEPPA_REVIEW_BIN -p --output-format json --model ${PEPPA_REVIEW_MODEL:-sonnet}` (общий запуск `runner/claude-print.ts`, токен пула проекта, как триаж). `changes` → замечания агенту (`sendToSession` или новый раннер), `ok`/ошибка → стори в `review` и «готово к ревью» с резюме (если ход агента ещё идёт — его шлёт Stop-хук с той же заметкой `reviewNote`). Тот же одобренный SHA не ревьюится повторно; после `max_iterations` возвратов — к PM с последними замечаниями. Зависшие/непринятые — `reviewTick` в вачдоге (раз в минуту). Карточка и `get_task` — последнее ревью. PM, двигающий карточку сам, ревьюера не зовёт. Мок `mock-reviewer` (`MOCK_REVIEW_SCENARIO`)
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
- **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` терпим к вариантам полей — формат live-CLI не сверен, `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:` / `budget.task:` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой
+- **Память проекта (PEP-30)**: `.peppa/memory.md` в репо проекта (разделы Команды/Соглашения/Грабли/Решения), `core/memory.ts` (`rememberFact` — дубли пропускаются, предел `PEPPA_MEMORY_MAX_CHARS` 12 000 → отказ с просьбой ужать; `replaceMemory`; `memoryContext` = файл рабочей копии + 5 последних `done` стори). MCP агента `get_memory`/`remember` (файл рядом с `.peppa/project.json`, коммитит агент в ветке стори). Раннер (`launch` в runner/sessions.ts) дописывает `memoryContext` к общим правилам при каждом запуске/resume. Правило — «Завершение» в `template/RULES.md`; веб — вкладка «Спеки» (`MemorySection`)
+- **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:` → `task.agent:` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent k=v…`
+- **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index e62bc174..e571ab09 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -43,6 +43,10 @@ import {
listSessions,
setProjectRunnerSettings,
setTaskRunnerSettings,
+ dismissOnboarding,
+ AGENT_FIELDS,
+ setProjectAgentSettings,
+ setTaskAgentSettings,
cleanBudget,
logEvent,
setProjectBudget,
@@ -88,6 +92,12 @@ async function ownedSession(userId: number, sessionId: number) {
return s;
}
+/** PEP-31: hide the first-run checklist on the home page. */
+export async function dismissOnboardingAction(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, () => dismissOnboarding(db, user.id));
+}
+
export async function answerQuestion(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
@@ -256,6 +266,24 @@ export async function setRunnerSettingsAction(f: FormData) {
});
}
+/** PEP-41: agent provider/model/effort of a project (all fields) or a story ("" = inherit). */
+export async function setAgentSettingsAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const patch: Record = {};
+ for (const k of AGENT_FIELDS) if (f.has(k)) patch[k] = str(f, k);
+ if (patch.escalateAfter === "0") patch.escalateAfter = null;
+ if (str(f, "taskKey")) {
+ const ref = await resolveTask(db, str(f, "taskKey"));
+ await projectForUser(db, user.id, ref.project.id);
+ await setTaskAgentSettings(db, ref.task.id, patch);
+ return;
+ }
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await setProjectAgentSettings(db, p.id, patch);
+ });
+}
+
export async function stopTaskSession(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 320ad56e..833c0ec6 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -24,7 +24,7 @@ const TOOLS: Array<[string, string]> = [
["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"],
["get_usage", "лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали"],
["get_metrics", "метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"],
- ["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое"],
+ ["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)"],
["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"],
];
@@ -40,6 +40,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
{ title: "Автономность", say: "Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR", how: "update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»" },
+ { title: "Модель агента", say: "Рутину в PAY делай на sonnet, а если проверки дважды красные — переходи на opus", how: "update_project_settings agent={model: sonnet, escalate_model: opus, escalate_after: 2}. Для одной стори — update_task с agent. То же — «⋯ Настройки проекта» → «Модель агента» и раздел «Агент» на странице стори" },
{ title: "Видимость репозитория", say: "Сделай репозиторий PAY приватным", how: "set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»" },
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»" },
{ title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" },
@@ -84,6 +85,9 @@ export default async function Help() {
ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите (Gitea, eGov или логин и пароль) и нажмите «Разрешить». В чате включите коннектор Peppa.
Codex, Claude и другие MCP-клиенты: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.
Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в Настройках.
+
Модель агента — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (Claude Code, Codex, OpenCode), модель (sonnet, opus, gpt-5-codex…) и усилия. Эскалация: после N неудач стори (красные проверки по разным коммитам и возвраты ревьюера, по умолчанию 2) она до конца идёт на сильной модели — живой раннер перезапускается в том же разговоре. Запасной провайдер — если у основного нет рабочей подписки в пуле (все в лимите или с ошибкой входа), раннер стартует на нём.
+
Память проекта — .peppa/memory.md в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP remember). Раннер подкладывает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер ограничен — разросшуюся память агент ужимает сам. Посмотреть — вкладка проекта «Спеки».
+
Первый запуск — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся».
Подписки — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; свободных нет — ждёт сброса и продолжает сам.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 7e621b59..37611a6d 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
-import { DEFAULT_RUNNER_SETTINGS, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -10,6 +10,7 @@ import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/com
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
import { AutonomyPanel } from "@/components/Autonomy";
import { NewRunnerForm, RunnerSettingsPanel } from "@/components/Runners";
+import { AgentModelPanel } from "@/components/AgentModel";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
@@ -21,7 +22,7 @@ import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
-import { CodeTab, EpicsPanel, ProgressBar, PullsTab, SpecsTab } from "./tabs";
+import { CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
import { saveProjectBudgetAction } from "../../actions";
@@ -101,6 +102,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const [pool, pools, autonomy] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id)]);
// PEP-10/27: runner settings of the project over the system ones.
const [runnerOwn, runnerSystem, secrets] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id)]);
+ // PEP-41: agent provider/model of the project over the platform's.
+ const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
+ // PEP-31: the project's pool has no working subscription — agents won't start.
+ const agentWarning = await projectAgentWarning(db, p.id);
// Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
@@ -124,6 +129,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
// Gitea and the working copy are read only for the open tab.
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
const specs = tab === "specs" ? listSpecs(p) : [];
+ const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
const metrics = tab === "metrics" ? await projectMetrics(db, p.id, { weeks: Number(weeks) || 8 }) : null;
const journal = tab === "journal" ? await listJournal(db, { projectId: p.id, actorKind: (actor || undefined) as ActorKind | undefined, channel: (channel || undefined) as ActorChannel | undefined, limit: 200 }) : [];
@@ -177,6 +183,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
+
+
+
+
@@ -345,6 +355,13 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{repo.fullName} · {repoVisibilityLabel(repo.private)}
+ {agentWarning && (
+
+ Агенты не запустятся: {agentWarning}.
+ {superadmin ? Подписки → : Попроси суперадмина проверить подписки или сменить пул в «⋯ Настройки проекта».}
+
+ )}
+
-
+
{egov === "linked" && eGov привязан — теперь можно входить по QR}
{user.egovIin ? (
@@ -126,7 +126,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
)}
-
+
{user.telegramChatId ? (
)}
+
{live ? (
// PEP-9 terminal + PEP-33 step feed of the newest unfinished runner.
diff --git a/apps/web/components/AgentModel.tsx b/apps/web/components/AgentModel.tsx
new file mode 100644
index 00000000..4f05a3e0
--- /dev/null
+++ b/apps/web/components/AgentModel.tsx
@@ -0,0 +1,115 @@
+// PEP-41: provider / model / effort of the agent and escalation (project and story).
+import { AGENT_EFFORT_RU, AGENT_EFFORTS, AGENT_PROVIDERS, agentSettingsLabel, type AgentSettings, type AgentSettingsPatch, type Escalation } from "@peppa/core";
+import { setAgentSettingsAction } from "@/app/(app)/actions";
+import { Hidden } from "@/components/cards";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input, Label, NativeSelect } from "@/components/ui/input";
+
+const PROVIDER_RU: Record = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" };
+const inherit = (v: string | number | null | undefined, none = "по умолчанию") => (v == null ? none : `как выше: ${v}`);
+
+function ProviderSelect({ name, own, inherited, none }: { name: string; own?: string | null; inherited?: string | null; none?: string }) {
+ return (
+
+
+ {AGENT_PROVIDERS.map((p) => (
+
+ ))}
+
+ );
+}
+
+function EffortSelect({ name, own, inherited }: { name: string; own?: string | null; inherited?: string | null }) {
+ return (
+
+
+ {AGENT_EFFORTS.map((e) => (
+
+ ))}
+
+ );
+}
+
+/** «⋯ Настройки проекта → Модель агента». */
+export function AgentModelPanel({ projectId, own, inherited, back }: { projectId: number; own: AgentSettingsPatch; inherited: AgentSettings; back: string }) {
+ return (
+
+ );
+}
+
+/** Story page: provider / model / effort for this story only, and the escalation mark. */
+export function TaskAgentModel({ taskKey, own, inherited, escalation, back }: { taskKey: string; own: AgentSettingsPatch; inherited: AgentSettings; escalation: Escalation | null; back: string }) {
+ return (
+
+ );
+}
diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx
new file mode 100644
index 00000000..03179740
--- /dev/null
+++ b/apps/web/components/Onboarding.tsx
@@ -0,0 +1,52 @@
+// PEP-31: first-run checklist on the home page.
+import { CircleCheck, Circle, X } from "lucide-react";
+import type { Onboarding } from "@peppa/core";
+import { dismissOnboardingAction } from "@/app/(app)/actions";
+import { Hidden } from "@/components/cards";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+export function OnboardingChecklist({ data }: { data: Onboarding }) {
+ const next = data.steps.find((s) => !s.done && !s.optional);
+ return (
+
+
+ ))}
+
+
+ );
+}
diff --git a/openspec/changes/archive/2026-11-14-pep-30-project-memory/design.md b/openspec/changes/archive/2026-11-14-pep-30-project-memory/design.md
new file mode 100644
index 00000000..7789a816
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-30-project-memory/design.md
@@ -0,0 +1,10 @@
+# Design
+
+- Формат: Markdown, разделы `## Команды`, `## Соглашения`, `## Грабли`, `## Решения`, пункты
+ `- …`. `remember` создаёт файл с шапкой при первом вызове, раздел — если его нет; пункт
+ нормализуется (одна строка, ≤ 500 символов); дубль (без учёта регистра и пробелов) — no-op.
+- Источник — рабочая копия раннера (`PEPPA_PROJECT_DIR` у MCP; у раннера cwd запуска,
+ worktree тоже). Пеппа файл не коммитит: коммит — часть работы агента в ветке стори.
+- Предел 12 000 символов (`PEPPA_MEMORY_MAX_CHARS`). В правила запуска идёт не больше предела
+ (обрезка с пометкой), чтобы разросшийся вручную файл не съел контекст.
+- Сводка стори: `tasks` проекта со статусом `done`, последние 5 по `updated_at`, без архивных.
diff --git a/openspec/changes/archive/2026-11-14-pep-30-project-memory/proposal.md b/openspec/changes/archive/2026-11-14-pep-30-project-memory/proposal.md
new file mode 100644
index 00000000..09ba8fdc
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-30-project-memory/proposal.md
@@ -0,0 +1,33 @@
+# PEP-30: Память проекта — агент накапливает знания между стори
+
+## Why
+Каждая сессия агента начинает с нуля: заново ищет команды сборки и тестов, наступает на те
+же грабли, переспрашивает соглашения. Знания из прошлых стори теряются вместе с разговором.
+
+## What Changes
+- **Файл памяти в репо проекта** — `.peppa/memory.md`: короткие пункты по разделам
+ «Команды», «Соглашения», «Грабли», «Решения». Живёт в git, меняется в ветке стори и
+ попадает в main вместе с PR (ревьюится как код). Не `AGENTS.md`: тот пишет человек, а
+ память — агент, и её размер Пеппа контролирует сама.
+- **MCP агента**: `get_memory` (файл + сводка последних завершённых стори проекта) и
+ `remember` (добавить пункт в раздел; дубликаты не добавляются; `replace: true` —
+ переписать память целиком, чтобы ужать).
+- **Предел размера**: 12 000 символов. `remember`, который вывел бы память за предел,
+ отклоняется с просьбой ужать её (`remember` с `replace`); `get_memory` и сводка в правилах
+ предупреждают, когда память занимает больше 80 % предела.
+- **Раннер подсовывает память**: к общим правилам запуска (`--append-system-prompt-file`,
+ Codex `developer_instructions`, OpenCode `instructions`) добавляется раздел «Память
+ проекта» — содержимое `.peppa/memory.md` рабочей копии раннера и сводка последних 5
+ завершённых стори (ключ, название, OpenSpec change, когда). При каждом запуске и resume.
+- **Правило в `template/RULES.md`**: перед PR агент записывает через `remember` то, что
+ пригодится следующему (команды, грабли, соглашения), и следит за размером; спеки
+ обновляются архивом OpenSpec, как раньше.
+- **Веб**: вкладка проекта «Спеки» показывает память проекта (с размером и предупреждением).
+
+## Capabilities
+- New: `project-memory`
+
+## Impact
+- `packages/core/src/memory.ts` (чтение/запись, предел, сводка стори), `packages/mcp/src/index.ts`
+ (инструменты), `packages/runner/src/sessions.ts` (раздел к правилам запуска),
+ `template/RULES.md`, веб `p/[key]` вкладка «Спеки». Без миграций.
diff --git a/openspec/changes/archive/2026-11-14-pep-30-project-memory/specs/project-memory/spec.md b/openspec/changes/archive/2026-11-14-pep-30-project-memory/specs/project-memory/spec.md
new file mode 100644
index 00000000..3c902c56
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-30-project-memory/specs/project-memory/spec.md
@@ -0,0 +1,35 @@
+## ADDED Requirements
+
+### Requirement: Файл памяти проекта
+Память проекта SHALL храниться в репозитории проекта в `.peppa/memory.md` — пункты по разделам
+«Команды», «Соглашения», «Грабли», «Решения». Агент пополняет её MCP-инструментом `remember`,
+читает — `get_memory`. Повторный пункт не добавляется.
+
+#### Scenario: Запомнить команду
+- **GIVEN** в рабочей копии нет `.peppa/memory.md`
+- **WHEN** агент вызывает `remember` с разделом «Команды» и текстом «тесты: pnpm test»
+- **THEN** создаётся `.peppa/memory.md` с разделом «Команды» и пунктом «- тесты: pnpm test»
+
+#### Scenario: Дубликат
+- **WHEN** агент повторно вызывает `remember` с тем же текстом
+- **THEN** файл не меняется, ответ сообщает, что пункт уже есть
+
+### Requirement: Память не разрастается
+Пеппа SHALL ограничивать память 12 000 символами: `remember`, выводящий её за предел,
+отклоняется с просьбой ужать (`remember` с `replace: true` переписывает файл целиком, тоже в
+пределе). Когда память больше 80 % предела, `get_memory` предупреждает.
+
+#### Scenario: Предел превышен
+- **GIVEN** память занимает 11 990 символов
+- **WHEN** агент вызывает `remember` с пунктом в 100 символов
+- **THEN** вызов отклонён с текстом про предел и `replace`, файл не изменён
+
+### Requirement: Память в контексте раннера
+Раннер SHALL при каждом запуске и resume добавлять к правилам агента раздел «Память проекта»:
+содержимое `.peppa/memory.md` рабочей копии раннера и сводку последних 5 завершённых стори
+проекта (ключ, название, OpenSpec change).
+
+#### Scenario: Новая стори видит прошлые знания
+- **GIVEN** в `.peppa/memory.md` есть «- тесты: pnpm test», стори PAY-3 в `done`
+- **WHEN** раннер запускает агента на PAY-4
+- **THEN** файл правил запуска содержит раздел «Память проекта» с «тесты: pnpm test» и строкой про PAY-3
diff --git a/openspec/changes/archive/2026-11-14-pep-30-project-memory/tasks.md b/openspec/changes/archive/2026-11-14-pep-30-project-memory/tasks.md
new file mode 100644
index 00000000..82f72fa9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-30-project-memory/tasks.md
@@ -0,0 +1,11 @@
+## 1. Ядро
+- [x] 1.1 `core/memory.ts`: readMemory, rememberFact (разделы, дубли, предел), replaceMemory, recentDoneStories, memoryContext
+## 2. MCP и раннер
+- [x] 2.1 MCP агента: `get_memory`, `remember`
+- [x] 2.2 Раннер: раздел «Память проекта» к правилам запуска (start/resume/fresh)
+- [x] 2.3 `template/RULES.md`: правило про память
+## 3. Веб и документация
+- [x] 3.1 Вкладка «Спеки»: память проекта с размером
+- [x] 3.2 AGENTS.md, /help
+## 4. Тесты
+- [x] 4.1 e2e: remember/дубль/предел/replace, раздел в правилах запуска
diff --git a/openspec/changes/archive/2026-11-14-pep-31-onboarding/design.md b/openspec/changes/archive/2026-11-14-pep-31-onboarding/design.md
new file mode 100644
index 00000000..355665d2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-31-onboarding/design.md
@@ -0,0 +1,14 @@
+# Design
+
+- Шаги считаются из БД на каждый рендер (дёшево: несколько COUNT):
+ - `subscription` (только суперадмин): есть подписка в статусе active/limited;
+ - `telegram`: `users.telegram_chat_id` задан;
+ - `egov` (необязательный; только если заданы `EGOV_ORGANISATION_BIN` или `KAZEDS_RELAY_BASE`): `users.egov_iin`;
+ - `project`: есть свой проект или проект, где пользователь участник;
+ - `story`: в его проектах есть стори;
+ - `started`: в его проектах была хоть одна сессия со стори.
+- Готово = все обязательные шаги. Скрытие — флаг в `settings`; новый пользователь видит
+ чек-лист, пока не выполнит или не скроет.
+- Предупреждение проекта: только когда у проекта задан пул. Без пула раннер идёт на входе
+ машины — его Пеппа не проверяет. «Рабочая» подписка = active или limited с прошедшим сроком
+ (та же проверка, что у `pickSubscription`).
diff --git a/openspec/changes/archive/2026-11-14-pep-31-onboarding/proposal.md b/openspec/changes/archive/2026-11-14-pep-31-onboarding/proposal.md
new file mode 100644
index 00000000..b278fcfd
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-31-onboarding/proposal.md
@@ -0,0 +1,25 @@
+# PEP-31: Онбординг — чек-лист первого запуска
+
+## Why
+Новый пользователь не понимает, что нужно подключить подписку агента и Telegram, где
+репозиторий и как запустить первую стори. Если у проекта нет рабочей подписки, сессия
+молча падает.
+
+## What Changes
+- **Чек-лист на Главной** с прогрессом «N из M»: подключить подписку агента (только
+ суперадмину — «Подписки»), привязать Telegram, привязать eGov (необязательный шаг, если
+ вход через eGov настроен), создать проект, завести стори, двинуть стори в работу. Каждый шаг
+ — ссылка туда, где он делается; выполненные отмечены автоматически по данным.
+- Чек-лист скрывается сам, когда все обязательные шаги выполнены, или по кнопке «Скрыть»
+ (`settings` `onboarding.dismissed:`).
+- **Предупреждение на проекте**: у пула подписок проекта нет рабочей подписки (все в лимите,
+ с ошибкой входа, не проверены, пул пуст) — плашка над вкладками проекта «Агенты не
+ запустятся: …» со ссылкой на настройки проекта / «Подписки» (суперадмину).
+
+## Capabilities
+- New: `onboarding`
+
+## Impact
+- `packages/core/src/onboarding.ts` (`onboardingChecklist`, `projectAgentWarning`,
+ `dismissOnboarding`), веб: `components/Onboarding.tsx`, Главная, страница проекта, action.
+ Без миграций.
diff --git a/openspec/changes/archive/2026-11-14-pep-31-onboarding/specs/onboarding/spec.md b/openspec/changes/archive/2026-11-14-pep-31-onboarding/specs/onboarding/spec.md
new file mode 100644
index 00000000..888b6586
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-31-onboarding/specs/onboarding/spec.md
@@ -0,0 +1,25 @@
+## ADDED Requirements
+
+### Requirement: Чек-лист первого запуска
+Главная SHALL показывать новому пользователю чек-лист с прогрессом: подписка агента (только
+суперадмину), Telegram, eGov (необязательно, если вход через eGov настроен), проект, стори,
+стори в работе. Шаги отмечаются по данным; чек-лист исчезает, когда обязательные шаги
+выполнены или пользователь нажал «Скрыть».
+
+#### Scenario: Новый пользователь
+- **GIVEN** пользователь без проектов и без привязки Telegram
+- **WHEN** он открывает Главную
+- **THEN** виден чек-лист «0 из 4» со ссылками «Привязать Telegram», «Создать проект»
+
+#### Scenario: Всё сделано
+- **GIVEN** у пользователя привязан Telegram, есть проект, стори и запущенная сессия
+- **THEN** чек-листа на Главной нет
+
+### Requirement: Предупреждение о подписке проекта
+Страница проекта SHALL предупреждать, если у пула подписок проекта нет рабочей подписки:
+агенты не запустятся.
+
+#### Scenario: Пул в лимите
+- **GIVEN** у проекта PAY пул с одной подпиской в статусе `auth_error`
+- **WHEN** участник открывает проект
+- **THEN** над вкладками плашка «Агенты не запустятся» с причиной
diff --git a/openspec/changes/archive/2026-11-14-pep-31-onboarding/tasks.md b/openspec/changes/archive/2026-11-14-pep-31-onboarding/tasks.md
new file mode 100644
index 00000000..6696c398
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-31-onboarding/tasks.md
@@ -0,0 +1,8 @@
+## 1. Ядро
+- [x] 1.1 `core/onboarding.ts`: onboardingChecklist, dismissOnboarding, projectAgentWarning
+## 2. Веб
+- [x] 2.1 `components/Onboarding.tsx` на Главной, action «Скрыть»
+- [x] 2.2 Плашка на странице проекта
+- [x] 2.3 AGENTS.md, /help
+## 3. Тесты
+- [x] 3.1 e2e: шаги чек-листа, скрытие, предупреждение проекта
diff --git a/openspec/changes/archive/2026-11-14-pep-41-agent-model/design.md b/openspec/changes/archive/2026-11-14-pep-41-agent-model/design.md
new file mode 100644
index 00000000..922002e0
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-41-agent-model/design.md
@@ -0,0 +1,17 @@
+# Design
+
+- Поля сливаются по уровням (умолчания ← платформа ← проект ← стори); пустая строка в форме =
+ «наследовать». `escalateAfter: null` — эскалация выключена; без `escalateModel` её нет.
+- Модель применяется, только если провайдер запуска совпадает с `provider` настройки (или
+ `provider` не задан): `opus` не уйдёт в Codex. На запасном провайдере — `fallbackModel`.
+- Явные `opts.model`/`opts.provider` (CLI `--model`) сильнее настроек.
+- Неудачи стори = `ci_attempts` + `reviewRejections`. При достижении порога пишется
+ `agent.escalated:` (`{at, failures, model}`) — дальше стори всегда на сильной модели,
+ даже когда зелёный CI обнулит `ci_attempts`. Сброс — при `done` (moveTask) не нужен: стори
+ больше не запускается; повторный старт из «Готово» сохранит эскалацию, это ок.
+- Живой раннер: модель текущего запуска — из последнего события `started`/`resumed`
+ (`payload.model`). Если эскалация наступила и модель другая — kill tmux + `resumeSession`
+ с сообщением как промптом (как ротация PEP-39). Иначе — обычный `sendToSession`.
+- Запасной провайдер: `pickSubscription` с основным провайдером бросает (нет рабочих) →
+ повтор с `fallbackProvider`; успех — `provider_fallback` в журнал. Без пула (вход машины)
+ запасного нет: провайдер = `provider` настройки.
diff --git a/openspec/changes/archive/2026-11-14-pep-41-agent-model/proposal.md b/openspec/changes/archive/2026-11-14-pep-41-agent-model/proposal.md
new file mode 100644
index 00000000..9a2145ed
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-41-agent-model/proposal.md
@@ -0,0 +1,37 @@
+# PEP-41: Модель и провайдер на стори, эскалация при неудаче
+
+## Why
+Все стори идут одной моделью по умолчанию CLI. Рутина переплачивает за сильную модель, сложное
+застревает на слабой; когда агент раз за разом валит проверки, Пеппа только зовёт PM; если
+подписки Claude все в лимите или с ошибкой входа, раннер не стартует вовсе.
+
+## What Changes
+- **Настройки агента** с наследованием `platform.agent` → `project.agent:` →
+ `task.agent:` (строки `settings`, без миграций), как у раннеров (PEP-10):
+ - `provider` — claude / codex / opencode (нет = решает подписка, как сейчас);
+ - `model` — строка для `--model` (`sonnet`, `opus`, `gpt-5-codex`, …), `effort` —
+ low / medium / high / xhigh / max (Claude `--effort`, Codex
+ `-c model_reasoning_effort=…`; OpenCode — нет);
+ - эскалация: `escalateModel`, `escalateEffort`, `escalateAfter` (по умолчанию 2) — после
+ N неудач стори (красные проверки `tasks.ci_attempts` + возвраты ревьюера PEP-26)
+ следующие запуски идут на сильной модели; эскалация липкая до конца стори;
+ - запасной провайдер: `fallbackProvider` + `fallbackModel` — если у основного провайдера
+ нет ни одной рабочей подписки (лимит, ошибка входа, нет такой в пуле), раннер стартует на
+ подписке запасного.
+- **Эскалация живого раннера**: красные проверки или замечания ревьюера, после которых
+ наступает эскалация, не печатаются в живой раннер, а перезапускают его (resume того же
+ разговора) на сильной модели с этим же сообщением. Событие `model_escalated`.
+- Модель/усилия каждого запуска пишутся в событие `started`/`resumed`; запуск на
+ запасном провайдере — событие `provider_fallback`.
+- **Веб**: «⋯ Настройки проекта → Модель агента», раздел «Агент» на странице стори — провайдер, модель,
+ усилия (пусто = как у проекта); шапка стори показывает модель и пометку эскалации.
+- **MCP PM**: `get_project_settings` / `update_project_settings` получают `agent`; на стори —
+ `update_task` с `agent`. CLI `peppa project agent key=value…`.
+
+## Capabilities
+- New: `agent-model`
+
+## Impact
+- `packages/core/src/agent-model.ts`; `runner/sessions.ts` (выбор провайдера/модели в запуске),
+ `runner/providers.ts` (`effort`), `runner/escalation.ts` (доставка с эскалацией) в
+ `ci-feedback.ts` и `reviewer.ts`; веб настройки и стори; MCP manager; CLI. Без миграций.
diff --git a/openspec/changes/archive/2026-11-14-pep-41-agent-model/specs/agent-model/spec.md b/openspec/changes/archive/2026-11-14-pep-41-agent-model/specs/agent-model/spec.md
new file mode 100644
index 00000000..3805dde2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-41-agent-model/specs/agent-model/spec.md
@@ -0,0 +1,37 @@
+## ADDED Requirements
+
+### Requirement: Модель и провайдер стори
+Пеппа SHALL выбирать провайдера, модель и уровень усилий запуска агента по настройкам агента с
+наследованием платформа → проект → стори. Модель передаётся CLI флагом `--model`, усилия —
+`--effort` (Claude) или `model_reasoning_effort` (Codex). Модель применяется только к своему
+провайдеру.
+
+#### Scenario: Быстрая модель для рутины
+- **GIVEN** у проекта PAY модель `sonnet`, у стори PAY-7 — `opus` и усилия `high`
+- **WHEN** раннер запускает агента на PAY-7
+- **THEN** команда Claude содержит `--model opus --effort high`, событие `started` — `model: opus`
+
+#### Scenario: Модель не уходит чужому провайдеру
+- **GIVEN** у проекта провайдер claude и модель `opus`, запуск пошёл на Codex (запасной без своей модели)
+- **THEN** команда Codex без `--model`
+
+### Requirement: Эскалация после неудач
+Когда у стори набирается `escalateAfter` неудач (красные проверки по разным коммитам плюс
+возвраты ревьюера) и задана `escalateModel`, Пеппа SHALL запускать агента этой стори на
+`escalateModel` (и `escalateEffort`) до конца стори. Живой раннер с другой моделью
+перезапускается (resume) на сильной модели с сообщением о неудаче как промптом.
+
+#### Scenario: Вторая красная проверка
+- **GIVEN** у проекта `escalateModel: opus`, `escalateAfter: 2`; раннер PAY-7 работает на `sonnet`, одна красная попытка уже была
+- **WHEN** приходит красная проверка нового коммита
+- **THEN** раннер перезапущен с `--model opus --resume …`, промпт — сообщение о красной проверке, событие `model_escalated`
+
+### Requirement: Запасной провайдер
+Если у основного провайдера нет рабочей подписки, а задан `fallbackProvider`, Пеппа SHALL
+запускать раннер на подписке запасного провайдера (с `fallbackModel`) и писать событие
+`provider_fallback`.
+
+#### Scenario: Все подписки Claude в лимите
+- **GIVEN** в пуле проекта подписка Claude «лимит до 18:00» и активная Codex, `fallbackProvider: codex`
+- **WHEN** PM двигает стори в работу
+- **THEN** раннер стартует на Codex, в журнале `provider_fallback`
diff --git a/openspec/changes/archive/2026-11-14-pep-41-agent-model/tasks.md b/openspec/changes/archive/2026-11-14-pep-41-agent-model/tasks.md
new file mode 100644
index 00000000..7df7b3f9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-41-agent-model/tasks.md
@@ -0,0 +1,12 @@
+## 1. Ядро
+- [x] 1.1 `core/agent-model.ts`: настройки по уровням, проверка значений, resolveAgentSettings, неудачи стори и липкая эскалация, модель запуска для провайдера
+## 2. Раннер
+- [x] 2.1 providers: `effort` (Claude `--effort`, Codex `model_reasoning_effort`)
+- [x] 2.2 sessions: провайдер из настроек, запасной провайдер, модель/усилия в launch, событие started с моделью
+- [x] 2.3 escalation: доставка сообщения с эскалацией живого раннера; ci-feedback и reviewer
+## 3. Интерфейсы
+- [x] 3.1 Веб: «Модель агента» в настройках проекта, поля на стори, модель в шапке стори
+- [x] 3.2 MCP PM: agent в get/update_project_settings и update_task; CLI `peppa project agent`
+- [x] 3.3 AGENTS.md, /help
+## 4. Тесты
+- [x] 4.1 e2e: модель в команде, наследование, эскалация живого раннера, запасной провайдер
diff --git a/openspec/specs/agent-model/spec.md b/openspec/specs/agent-model/spec.md
new file mode 100644
index 00000000..d0604948
--- /dev/null
+++ b/openspec/specs/agent-model/spec.md
@@ -0,0 +1,42 @@
+# agent-model Specification
+
+## Purpose
+Провайдер, модель и усилия агента по настройкам платформа → проект → стори, эскалация на сильную модель после неудач и запасной провайдер (PEP-41).
+
+## Requirements
+
+### Requirement: Модель и провайдер стори
+Пеппа SHALL выбирать провайдера, модель и уровень усилий запуска агента по настройкам агента с
+наследованием платформа → проект → стори. Модель передаётся CLI флагом `--model`, усилия —
+`--effort` (Claude) или `model_reasoning_effort` (Codex). Модель применяется только к своему
+провайдеру.
+
+#### Scenario: Быстрая модель для рутины
+- **GIVEN** у проекта PAY модель `sonnet`, у стори PAY-7 — `opus` и усилия `high`
+- **WHEN** раннер запускает агента на PAY-7
+- **THEN** команда Claude содержит `--model opus --effort high`, событие `started` — `model: opus`
+
+#### Scenario: Модель не уходит чужому провайдеру
+- **GIVEN** у проекта провайдер claude и модель `opus`, запуск пошёл на Codex (запасной без своей модели)
+- **THEN** команда Codex без `--model`
+
+### Requirement: Эскалация после неудач
+Когда у стори набирается `escalateAfter` неудач (красные проверки по разным коммитам плюс
+возвраты ревьюера) и задана `escalateModel`, Пеппа SHALL запускать агента этой стори на
+`escalateModel` (и `escalateEffort`) до конца стори. Живой раннер с другой моделью
+перезапускается (resume) на сильной модели с сообщением о неудаче как промптом.
+
+#### Scenario: Вторая красная проверка
+- **GIVEN** у проекта `escalateModel: opus`, `escalateAfter: 2`; раннер PAY-7 работает на `sonnet`, одна красная попытка уже была
+- **WHEN** приходит красная проверка нового коммита
+- **THEN** раннер перезапущен с `--model opus --resume …`, промпт — сообщение о красной проверке, событие `model_escalated`
+
+### Requirement: Запасной провайдер
+Если у основного провайдера нет рабочей подписки, а задан `fallbackProvider`, Пеппа SHALL
+запускать раннер на подписке запасного провайдера (с `fallbackModel`) и писать событие
+`provider_fallback`.
+
+#### Scenario: Все подписки Claude в лимите
+- **GIVEN** в пуле проекта подписка Claude «лимит до 18:00» и активная Codex, `fallbackProvider: codex`
+- **WHEN** PM двигает стори в работу
+- **THEN** раннер стартует на Codex, в журнале `provider_fallback`
diff --git a/openspec/specs/onboarding/spec.md b/openspec/specs/onboarding/spec.md
new file mode 100644
index 00000000..e5e31cca
--- /dev/null
+++ b/openspec/specs/onboarding/spec.md
@@ -0,0 +1,30 @@
+# onboarding Specification
+
+## Purpose
+Чек-лист первого запуска на Главной и предупреждение, когда агенты проекта не запустятся (PEP-31).
+
+## Requirements
+
+### Requirement: Чек-лист первого запуска
+Главная SHALL показывать новому пользователю чек-лист с прогрессом: подписка агента (только
+суперадмину), Telegram, eGov (необязательно, если вход через eGov настроен), проект, стори,
+стори в работе. Шаги отмечаются по данным; чек-лист исчезает, когда обязательные шаги
+выполнены или пользователь нажал «Скрыть».
+
+#### Scenario: Новый пользователь
+- **GIVEN** пользователь без проектов и без привязки Telegram
+- **WHEN** он открывает Главную
+- **THEN** виден чек-лист «0 из 4» со ссылками «Привязать Telegram», «Создать проект»
+
+#### Scenario: Всё сделано
+- **GIVEN** у пользователя привязан Telegram, есть проект, стори и запущенная сессия
+- **THEN** чек-листа на Главной нет
+
+### Requirement: Предупреждение о подписке проекта
+Страница проекта SHALL предупреждать, если у пула подписок проекта нет рабочей подписки:
+агенты не запустятся.
+
+#### Scenario: Пул в лимите
+- **GIVEN** у проекта PAY пул с одной подпиской в статусе `auth_error`
+- **WHEN** участник открывает проект
+- **THEN** над вкладками плашка «Агенты не запустятся» с причиной
diff --git a/openspec/specs/project-memory/spec.md b/openspec/specs/project-memory/spec.md
new file mode 100644
index 00000000..a8a97aa3
--- /dev/null
+++ b/openspec/specs/project-memory/spec.md
@@ -0,0 +1,40 @@
+# project-memory Specification
+
+## Purpose
+Память проекта `.peppa/memory.md`: агенты накапливают знания между стори, раннер подкладывает их в каждый запуск, размер ограничен (PEP-30).
+
+## Requirements
+
+### Requirement: Файл памяти проекта
+Память проекта SHALL храниться в репозитории проекта в `.peppa/memory.md` — пункты по разделам
+«Команды», «Соглашения», «Грабли», «Решения». Агент пополняет её MCP-инструментом `remember`,
+читает — `get_memory`. Повторный пункт не добавляется.
+
+#### Scenario: Запомнить команду
+- **GIVEN** в рабочей копии нет `.peppa/memory.md`
+- **WHEN** агент вызывает `remember` с разделом «Команды» и текстом «тесты: pnpm test»
+- **THEN** создаётся `.peppa/memory.md` с разделом «Команды» и пунктом «- тесты: pnpm test»
+
+#### Scenario: Дубликат
+- **WHEN** агент повторно вызывает `remember` с тем же текстом
+- **THEN** файл не меняется, ответ сообщает, что пункт уже есть
+
+### Requirement: Память не разрастается
+Пеппа SHALL ограничивать память 12 000 символами: `remember`, выводящий её за предел,
+отклоняется с просьбой ужать (`remember` с `replace: true` переписывает файл целиком, тоже в
+пределе). Когда память больше 80 % предела, `get_memory` предупреждает.
+
+#### Scenario: Предел превышен
+- **GIVEN** память занимает 11 990 символов
+- **WHEN** агент вызывает `remember` с пунктом в 100 символов
+- **THEN** вызов отклонён с текстом про предел и `replace`, файл не изменён
+
+### Requirement: Память в контексте раннера
+Раннер SHALL при каждом запуске и resume добавлять к правилам агента раздел «Память проекта»:
+содержимое `.peppa/memory.md` рабочей копии раннера и сводку последних 5 завершённых стори
+проекта (ключ, название, OpenSpec change).
+
+#### Scenario: Новая стори видит прошлые знания
+- **GIVEN** в `.peppa/memory.md` есть «- тесты: pnpm test», стори PAY-3 в `done`
+- **WHEN** раннер запускает агента на PAY-4
+- **THEN** файл правил запуска содержит раздел «Память проекта» с «тесты: pnpm test» и строкой про PAY-3
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 37dded95..ff7f03cf 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -3,6 +3,14 @@ import { parseArgs } from "node:util";
import { resolve } from "node:path";
import {
backupDb,
+ parseAgentPairs,
+ setSystemAgentSettings,
+ getSystemAgentSettings,
+ setTaskAgentSettings,
+ getTaskAgentSettings,
+ setProjectAgentSettings,
+ getProjectAgentSettings,
+ resolveAgentSettings,
describeAutonomy,
getAutonomy,
setAutonomy,
@@ -74,6 +82,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa project add [--owner peppa] [--repo ] [--path ] (register only)
peppa project owner
peppa project autonomy [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes)
+ peppa project agent [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit)
peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot)
peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
peppa project list
@@ -326,6 +335,25 @@ async function main(): Promise {
console.log(`${p.key}\n${describeAutonomy(await getAutonomy(db, p.id))}`);
break;
}
+ case "project agent": {
+ // PEP-41: agent model of the platform, a project or a story (merged over what is stored).
+ const [target, ...rest] = args;
+ if (!target) throw new PeppaError("usage: peppa project agent [provider=claude|codex|opencode model=… effort=low|medium|high|xhigh|max escalateModel=… escalateEffort=… escalateAfter=N|off fallbackProvider=… fallbackModel=…]");
+ const patch = parseAgentPairs(rest);
+ if (target === "--platform") {
+ if (rest.length) await setSystemAgentSettings(db, patch, true);
+ console.log(`platform: ${JSON.stringify(await getSystemAgentSettings(db))}`);
+ } else if (/-\d+$/.test(target)) {
+ const ref = await resolveTask(db, target);
+ if (rest.length) await setTaskAgentSettings(db, ref.task.id, patch, true);
+ console.log(`${ref.key}: own ${JSON.stringify(await getTaskAgentSettings(db, ref.task.id))}\neffective ${JSON.stringify(await resolveAgentSettings(db, ref.project.id, ref.task.id))}`);
+ } else {
+ const p = await getProject(db, target);
+ if (rest.length) await setProjectAgentSettings(db, p.id, patch, true);
+ console.log(`${p.key}: own ${JSON.stringify(await getProjectAgentSettings(db, p.id))}\neffective ${JSON.stringify(await resolveAgentSettings(db, p.id))}`);
+ }
+ break;
+ }
case "project list":
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`);
break;
diff --git a/packages/core/src/agent-model.ts b/packages/core/src/agent-model.ts
new file mode 100644
index 00000000..6849fb1c
--- /dev/null
+++ b/packages/core/src/agent-model.ts
@@ -0,0 +1,209 @@
+// PEP-41: provider, model and effort of the agent per platform → project → story, escalation
+// to a stronger model after failures, a fallback provider when the main one has no login.
+import { events, tasks, type Db } from "@peppa/db";
+import { and, desc, eq, inArray } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+import { reviewRejections } from "./reviews.ts";
+import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+
+export const AGENT_PROVIDERS = ["claude", "codex", "opencode"] as const;
+export type AgentProvider = (typeof AGENT_PROVIDERS)[number];
+export const AGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
+export type AgentEffort = (typeof AGENT_EFFORTS)[number];
+export const AGENT_EFFORT_RU: Record = { low: "низкие", medium: "средние", high: "высокие", xhigh: "очень высокие", max: "максимальные" };
+
+export interface AgentSettings {
+ /** null = the subscription decides (as before PEP-41). */
+ provider: AgentProvider | null;
+ model: string | null;
+ effort: AgentEffort | null;
+ escalateModel: string | null;
+ escalateEffort: AgentEffort | null;
+ /** Failures (red CI attempts + reviewer returns) before escalation; null = never. */
+ escalateAfter: number | null;
+ fallbackProvider: AgentProvider | null;
+ fallbackModel: string | null;
+}
+export type AgentSettingsPatch = { [K in keyof AgentSettings]?: AgentSettings[K] };
+export const AGENT_FIELDS = ["provider", "model", "effort", "escalateModel", "escalateEffort", "escalateAfter", "fallbackProvider", "fallbackModel"] as const satisfies ReadonlyArray;
+
+export const DEFAULT_AGENT_SETTINGS: AgentSettings = {
+ provider: null,
+ model: null,
+ effort: null,
+ escalateModel: null,
+ escalateEffort: null,
+ escalateAfter: 2,
+ fallbackProvider: null,
+ fallbackModel: null,
+};
+
+const SYSTEM_KEY = "platform.agent";
+const projectKey = (projectId: number) => `project.agent:${projectId}`;
+const taskKey = (taskId: number) => `task.agent:${taskId}`;
+const escalatedKey = (taskId: number) => `agent.escalated:${taskId}`;
+
+const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/\[\]-]{0,79}$/;
+
+/** Validates one field; returns undefined for "inherit" (empty), throws on a bad value when strict. */
+function parseField(k: keyof AgentSettings, v: unknown, strict: boolean): AgentSettings[keyof AgentSettings] | undefined {
+ const bad = () => {
+ if (strict) throw new PeppaError(`Недопустимое значение ${k}: ${String(v)}`);
+ return undefined;
+ };
+ if (v === undefined || v === "") return undefined;
+ if (v === null) return k === "escalateAfter" ? null : undefined;
+ switch (k) {
+ case "provider":
+ case "fallbackProvider":
+ return AGENT_PROVIDERS.includes(v as AgentProvider) ? (v as AgentProvider) : bad();
+ case "effort":
+ case "escalateEffort":
+ return AGENT_EFFORTS.includes(v as AgentEffort) ? (v as AgentEffort) : bad();
+ case "escalateAfter": {
+ if (v === "off" || v === "never" || v === 0 || v === "0") return null;
+ const n = typeof v === "string" ? Number(v) : v;
+ return Number.isInteger(n) && (n as number) >= 1 && (n as number) <= 20 ? (n as number) : bad();
+ }
+ default:
+ return typeof v === "string" && MODEL_RE.test(v.trim()) ? v.trim() : bad();
+ }
+}
+
+function clean(p: Record | null, strict = false): AgentSettingsPatch {
+ const out: Record = {};
+ if (!p) return out;
+ for (const [k, v] of Object.entries(p)) {
+ if (!AGENT_FIELDS.includes(k as keyof AgentSettings)) {
+ if (strict) throw new PeppaError(`Неизвестная настройка агента: ${k}`);
+ continue;
+ }
+ const val = parseField(k as keyof AgentSettings, v, strict);
+ if (val !== undefined) out[k] = val;
+ }
+ return out as AgentSettingsPatch;
+}
+
+export async function getSystemAgentSettings(db: Db): Promise {
+ return clean(await getSetting(db, SYSTEM_KEY));
+}
+export async function getProjectAgentSettings(db: Db, projectId: number): Promise {
+ return clean(await getSetting(db, projectKey(projectId)));
+}
+export async function getTaskAgentSettings(db: Db, taskId: number): Promise {
+ return clean(await getSetting(db, taskKey(taskId)));
+}
+
+/** Effective settings: defaults ← platform ← project ← story. */
+export async function resolveAgentSettings(db: Db, projectId: number, taskId?: number | null): Promise {
+ return {
+ ...DEFAULT_AGENT_SETTINGS,
+ ...(await getSystemAgentSettings(db)),
+ ...(await getProjectAgentSettings(db, projectId)),
+ ...(taskId ? await getTaskAgentSettings(db, taskId) : {}),
+ };
+}
+
+/**
+ * Replaces the overrides at one level (a full form: fields left out or empty inherit).
+ * With `merge`, the patch is applied over the stored overrides; null/"" there removes a field.
+ */
+async function store(db: Db, key: string, patch: Record, merge: boolean): Promise {
+ clean(patch, true); // validation
+ let base: Record = merge ? { ...((await getSetting>(db, key)) ?? {}) } : {};
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === undefined) continue;
+ if (v === "" || (v === null && k !== "escalateAfter")) delete base[k];
+ else base[k] = v;
+ }
+ const value = clean(base);
+ if (Object.keys(value).length) await setSetting(db, key, value);
+ else await deleteSetting(db, key);
+ return value;
+}
+export const setSystemAgentSettings = (db: Db, patch: Record, merge = false) => store(db, SYSTEM_KEY, patch, merge);
+export const setProjectAgentSettings = (db: Db, projectId: number, patch: Record, merge = false) => store(db, projectKey(projectId), patch, merge);
+export const setTaskAgentSettings = (db: Db, taskId: number, patch: Record, merge = false) => store(db, taskKey(taskId), patch, merge);
+
+/** "key=value" pairs (CLI) → a patch; "-" or empty value = inherit. */
+export function parseAgentPairs(pairs: string[]): Record {
+ const out: Record = {};
+ for (const p of pairs) {
+ const i = p.indexOf("=");
+ if (i < 1) throw new PeppaError(`Ожидается ключ=значение: ${p}`);
+ const k = p.slice(0, i).trim();
+ const v = p.slice(i + 1).trim();
+ out[k] = v === "-" ? "" : v;
+ }
+ return out;
+}
+
+// ── escalation ───────────────────────────────────────────────────────────────
+
+export interface Escalation {
+ at: string;
+ failures: number;
+ model: string;
+}
+
+/** Failures of a story so far: red CI attempts (distinct commits) + reviewer returns. */
+export async function storyFailures(db: Db, taskId: number): Promise {
+ const [t] = await db.select({ ci: tasks.ciAttempts }).from(tasks).where(eq(tasks.id, taskId));
+ return (t?.ci ?? 0) + (await reviewRejections(db, taskId));
+}
+
+export async function getEscalation(db: Db, taskId: number): Promise {
+ return getSetting(db, escalatedKey(taskId));
+}
+
+/**
+ * Sticky escalation: once the story reached `escalateAfter` failures (and an escalation model
+ * is set), it is recorded and stays even when a green run resets `ci_attempts`.
+ * Returns the escalation and whether it happened just now.
+ */
+export async function checkEscalation(db: Db, projectId: number, taskId: number): Promise<{ escalation: Escalation | null; fresh: boolean }> {
+ const cur = await getEscalation(db, taskId);
+ if (cur) return { escalation: cur, fresh: false };
+ const s = await resolveAgentSettings(db, projectId, taskId);
+ if (!s.escalateModel || s.escalateAfter == null) return { escalation: null, fresh: false };
+ const failures = await storyFailures(db, taskId);
+ if (failures < s.escalateAfter) return { escalation: null, fresh: false };
+ const escalation: Escalation = { at: new Date().toISOString(), failures, model: s.escalateModel };
+ await setSetting(db, escalatedKey(taskId), escalation);
+ return { escalation, fresh: true };
+}
+
+export interface LaunchModel {
+ model: string | null;
+ effort: AgentEffort | null;
+ escalated: boolean;
+}
+
+/**
+ * Model and effort for one launch on `provider`: the escalation model once the story is
+ * escalated; the fallback model on the fallback provider; the model only on its own provider.
+ */
+export function launchModelFor(s: AgentSettings, provider: AgentProvider, escalated: boolean): LaunchModel {
+ const own = s.provider == null || s.provider === provider;
+ if (own && escalated && s.escalateModel) return { model: s.escalateModel, effort: s.escalateEffort ?? s.effort, escalated: true };
+ if (own) return { model: s.model, effort: s.effort, escalated: false };
+ if (s.fallbackProvider === provider) return { model: s.fallbackModel, effort: null, escalated: false };
+ return { model: null, effort: null, escalated: false };
+}
+
+/** The model of a session's current launch (from its last started/resumed event). */
+export async function sessionLaunchModel(db: Db, sessionId: number): Promise {
+ const [row] = await db
+ .select({ payload: events.payload })
+ .from(events)
+ .where(and(eq(events.sessionId, sessionId), inArray(events.type, ["started", "resumed"])))
+ .orderBy(desc(events.id))
+ .limit(1);
+ return ((row?.payload as { model?: string | null } | null)?.model ?? null) || null;
+}
+
+/** One line for a card: "opus · усилия высокие" / "как у подписки". */
+export function agentSettingsLabel(s: Pick): string {
+ const parts = [s.provider, s.model, s.effort ? `усилия ${AGENT_EFFORT_RU[s.effort]}` : null].filter(Boolean);
+ return parts.length ? parts.join(" · ") : "по умолчанию";
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 736ee5c1..fa318d55 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -39,3 +39,6 @@ export * from "./analytics.ts";
export * from "./audit.ts";
export * from "./secrets.ts";
export * from "./secrets-audit.ts";
+export * from "./memory.ts";
+export * from "./agent-model.ts";
+export * from "./onboarding.ts";
diff --git a/packages/core/src/memory.ts b/packages/core/src/memory.ts
new file mode 100644
index 00000000..156236a2
--- /dev/null
+++ b/packages/core/src/memory.ts
@@ -0,0 +1,148 @@
+// PEP-30: project memory — `.peppa/memory.md` in the project repo, written by agents.
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { projects, tasks, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, desc, eq, isNull } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+
+export const MEMORY_FILE = ".peppa/memory.md";
+export const MEMORY_SECTIONS = ["Команды", "Соглашения", "Грабли", "Решения"] as const;
+export type MemorySection = (typeof MEMORY_SECTIONS)[number];
+const MAX_FACT = 500;
+
+export const memoryMaxChars = () => Number(process.env.PEPPA_MEMORY_MAX_CHARS ?? 12_000);
+const HEADER = "# Память проекта\n\nПишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.\n";
+
+export interface MemoryStats {
+ chars: number;
+ max: number;
+ /** More than 80% of the limit. */
+ nearLimit: boolean;
+}
+
+export const memoryPath = (dir: string) => join(dir, MEMORY_FILE);
+
+export function readMemory(dir: string): string {
+ const p = memoryPath(dir);
+ return existsSync(p) ? readFileSync(p, "utf8") : "";
+}
+
+export function memoryStats(text: string): MemoryStats {
+ const max = memoryMaxChars();
+ return { chars: text.length, max, nearLimit: text.length > max * 0.8 };
+}
+
+const norm = (s: string) => s.toLowerCase().replace(/[\s`*_.,;:—–-]+/g, " ").trim();
+
+/** Section aliases accepted from agents (English names, lower case). */
+const SECTION_ALIASES: Record = {
+ команды: "Команды",
+ commands: "Команды",
+ соглашения: "Соглашения",
+ conventions: "Соглашения",
+ грабли: "Грабли",
+ pitfalls: "Грабли",
+ gotchas: "Грабли",
+ решения: "Решения",
+ decisions: "Решения",
+};
+export function parseSection(s: string | undefined): MemorySection {
+ const v = SECTION_ALIASES[(s ?? "").trim().toLowerCase()];
+ if (!v) throw new PeppaError(`Раздел памяти: ${MEMORY_SECTIONS.join(", ")}`);
+ return v;
+}
+
+function write(dir: string, text: string) {
+ const p = memoryPath(dir);
+ mkdirSync(dirname(p), { recursive: true });
+ writeFileSync(p, text.endsWith("\n") ? text : `${text}\n`);
+}
+
+function tooBig(chars: number): PeppaError {
+ return new PeppaError(
+ `Память проекта вышла бы за предел ${memoryMaxChars()} символов (было бы ${chars}). Ужми её: get_memory, затем remember с replace: true и сокращённым текстом (объедини похожие пункты, убери устаревшее).`,
+ );
+}
+
+/** Adds one bullet to a section; returns "exists" for a duplicate (nothing written). */
+export function rememberFact(dir: string, sectionInput: string, fact: string): { result: "added" | "exists"; stats: MemoryStats } {
+ const section = parseSection(sectionInput);
+ const line = fact.replace(/\s+/g, " ").trim().replace(/^[-*]\s+/, "");
+ if (!line) throw new PeppaError("Пустой пункт памяти");
+ if (line.length > MAX_FACT) throw new PeppaError(`Пункт памяти длиннее ${MAX_FACT} символов — сформулируй короче`);
+ const cur = readMemory(dir) || HEADER;
+ const lines = cur.replace(/\n+$/, "").split("\n");
+ const key = norm(line);
+ if (lines.some((l) => /^\s*[-*]\s+/.test(l) && norm(l.replace(/^\s*[-*]\s+/, "")) === key)) return { result: "exists", stats: memoryStats(cur) };
+
+ const head = lines.findIndex((l) => l.trim().toLowerCase() === `## ${section.toLowerCase()}`);
+ if (head < 0) {
+ lines.push("", `## ${section}`, `- ${line}`);
+ } else {
+ let end = head + 1;
+ while (end < lines.length && !/^##\s/.test(lines[end]!)) end++;
+ // After the section's last non-empty line.
+ let at = end;
+ while (at > head + 1 && !lines[at - 1]!.trim()) at--;
+ lines.splice(at, 0, `- ${line}`);
+ }
+ const next = `${lines.join("\n")}\n`;
+ if (next.length > memoryMaxChars()) throw tooBig(next.length);
+ write(dir, next);
+ return { result: "added", stats: memoryStats(next) };
+}
+
+/** Rewrites the whole memory (compaction); still within the limit. */
+export function replaceMemory(dir: string, text: string): MemoryStats {
+ const body = text.trim();
+ if (!body) throw new PeppaError("Пустая память — чтобы ужать, передай сокращённый текст");
+ const next = `${body}\n`;
+ if (next.length > memoryMaxChars()) throw tooBig(next.length);
+ write(dir, next);
+ return memoryStats(next);
+}
+
+export interface DoneStory {
+ key: string;
+ title: string;
+ change: string | null;
+ updatedAt: Date;
+}
+
+/** The project's last finished stories (newest first, archived ones excluded). */
+export async function recentDoneStories(db: Db, projectId: number, limit = 5): Promise {
+ const rows = await db
+ .select({ key: projects.key, number: tasks.number, title: tasks.title, change: tasks.openspecChange, updatedAt: tasks.updatedAt })
+ .from(tasks)
+ .innerJoin(projects, eq(tasks.projectId, projects.id))
+ .where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)))
+ .orderBy(desc(tasks.updatedAt), desc(tasks.id))
+ .limit(limit);
+ return rows.map((r) => ({ key: formatTaskKey(r.key, r.number), title: r.title, change: r.change, updatedAt: r.updatedAt }));
+}
+
+const day = (d: Date) => d.toISOString().slice(0, 10);
+
+/**
+ * The "Память проекта" block appended to the agent's launch rules: the memory file of the
+ * runner's working copy (capped) and a digest of the last finished stories.
+ */
+export async function memoryContext(db: Db, projectId: number, dir: string): Promise {
+ const mem = readMemory(dir).trim();
+ const stories = await recentDoneStories(db, projectId);
+ const max = memoryMaxChars();
+ const parts = ["# Память проекта (PEP-30)", ""];
+ if (mem) {
+ const st = memoryStats(mem);
+ parts.push(`Из \`${MEMORY_FILE}\` (${st.chars} из ${max} символов${st.nearLimit ? " — почти предел, ужми через remember с replace" : ""}):`, "");
+ parts.push(mem.length > max ? `${mem.slice(0, max)}\n…(обрезано по пределу)` : mem);
+ } else {
+ parts.push(`\`${MEMORY_FILE}\` пока пуст — записывай знания через MCP \`remember\`.`);
+ }
+ if (stories.length) {
+ parts.push("", "Последние завершённые стори:");
+ for (const s of stories) parts.push(`- ${s.key} «${s.title}»${s.change ? ` — change ${s.change}` : ""} (${day(s.updatedAt)})`);
+ }
+ return parts.join("\n");
+}
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
new file mode 100644
index 00000000..02c9c759
--- /dev/null
+++ b/packages/core/src/onboarding.ts
@@ -0,0 +1,87 @@
+// PEP-31: first-run checklist on the home page and the "agents won't start" project warning.
+import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
+import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
+import { isSuperadmin } from "./monitor.ts";
+import { getSetting, setSetting } from "./settings.ts";
+import { isUsable, poolSubscriptions } from "./subscriptions.ts";
+import { userProjectIds, type User } from "./users.ts";
+
+export type OnboardingStepId = "subscription" | "telegram" | "egov" | "project" | "story" | "started";
+
+export interface OnboardingStep {
+ id: OnboardingStepId;
+ title: string;
+ hint: string;
+ href: string;
+ done: boolean;
+ optional: boolean;
+}
+
+export interface Onboarding {
+ steps: OnboardingStep[];
+ /** Required steps done / total. */
+ done: number;
+ total: number;
+ /** All required steps done. */
+ complete: boolean;
+ dismissed: boolean;
+ /** Shown on the home page. */
+ visible: boolean;
+}
+
+const dismissedKey = (userId: number) => `onboarding.dismissed:${userId}`;
+
+export async function dismissOnboarding(db: Db, userId: number): Promise {
+ await setSetting(db, dismissedKey(userId), { at: new Date().toISOString() });
+}
+
+export async function onboardingChecklist(db: Db, user: Pick): Promise {
+ const [me] = await db.select({ chat: users.telegramChatId, iin: users.egovIin }).from(users).where(eq(users.id, user.id));
+ const admin = await isSuperadmin(db, user);
+ const ids = await userProjectIds(db, user.id);
+ const n = async (q: Promise>) => (await q)[0]?.n ?? 0;
+ const storyCount = ids.length ? await n(db.select({ n: count() }).from(tasks).where(inArray(tasks.projectId, ids))) : 0;
+ const started = ids.length ? await n(db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), isNotNull(sessions.taskId)))) : 0;
+ const firstKey = ids.length ? (await db.select({ key: projects.key }).from(projects).where(inArray(projects.id, ids)).limit(1))[0]?.key : undefined;
+
+ const steps: OnboardingStep[] = [];
+ if (admin) {
+ const subs = await db.select({ status: subscriptions.status, limitedUntil: subscriptions.limitedUntil }).from(subscriptions);
+ steps.push({
+ id: "subscription",
+ title: "Подключить подписку агента",
+ hint: "Claude, Codex или OpenCode — на ней работают агенты; добавь её в пул проекта.",
+ href: "/subscriptions",
+ done: subs.some((s) => s.status === "active" || s.status === "limited"),
+ optional: false,
+ });
+ }
+ steps.push(
+ { id: "telegram", title: "Привязать Telegram", hint: "Вопросы агентов и «готово к ревью» придут в бот, отвечать можно кнопками.", href: "/settings#telegram", done: me?.chat != null, optional: false },
+ { id: "egov", title: "Привязать eGov", hint: "Вход по QR из eGov Mobile без пароля.", href: "/settings#egov", done: !!me?.iin, optional: true },
+ { id: "project", title: "Создать проект", hint: "Пеппа заведёт репозиторий в Gitea с шаблоном и CI.", href: "/projects/new", done: ids.length > 0, optional: false },
+ { id: "story", title: "Завести стори", hint: "Опиши, что нужно сделать, — одна стори = одно изменение.", href: firstKey ? `/p/${firstKey}` : "/projects", done: storyCount > 0, optional: false },
+ { id: "started", title: "Двинуть стори в работу", hint: "Перетащи карточку в «В работе» — агент запустится сам.", href: firstKey ? `/p/${firstKey}` : "/projects", done: started > 0, optional: false },
+ );
+ const required = steps.filter((s) => !s.optional);
+ const done = required.filter((s) => s.done).length;
+ const complete = done === required.length;
+ const dismissed = !!(await getSetting(db, dismissedKey(user.id)));
+ return { steps, done, total: required.length, complete, dismissed, visible: !complete && !dismissed };
+}
+
+const STATUS_RU: Record = { pending: "не подключена", limited: "в лимите", auth_error: "ошибка входа", active: "активна" };
+
+/**
+ * Why agents of the project won't start, or null: the project's pool has no working
+ * subscription. Without a pool the runner uses this machine's login (not checked here).
+ */
+export async function projectAgentWarning(db: Db, projectId: number, now = new Date()): Promise {
+ const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
+ if (p?.poolId == null) return null;
+ const subs = await poolSubscriptions(db, p.poolId);
+ if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
+ if (subs.some((s) => isUsable(s, now))) return null;
+ const why = subs.map((s) => `«${s.name}» — ${STATUS_RU[s.status] ?? s.status}${s.status === "limited" && s.limitedUntil ? ` до ${s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}` : ""}`);
+ return `нет рабочей подписки в пуле проекта: ${why.join(", ")}`;
+}
diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts
index a545d113..00da7e5c 100644
--- a/packages/core/src/subscriptions.ts
+++ b/packages/core/src/subscriptions.ts
@@ -226,7 +226,7 @@ export async function setProjectPool(db: Db, projectId: number, poolId: number |
await db.update(projects).set({ subscriptionPoolId: poolId }).where(eq(projects.id, projectId));
}
-async function poolSubscriptions(db: Db, poolId: number): Promise {
+export async function poolSubscriptions(db: Db, poolId: number): Promise {
const rows = await db
.select({ s: subscriptions })
.from(subscriptionPoolMembers)
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index a23fc202..d2e9e628 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -28,7 +28,13 @@ import {
setDefaultActor,
getSession,
listProjectSecrets,
+ MEMORY_FILE,
+ MEMORY_SECTIONS,
+ memoryContext,
+ rememberFact,
+ replaceMemory,
} from "@peppa/core";
+import { dirname } from "node:path";
import { createDb } from "@peppa/db";
import { requestReview, reviewGate } from "@peppa/runner";
import { z } from "zod";
@@ -249,4 +255,42 @@ tool(
},
);
+// ── PEP-30: project memory (.peppa/memory.md in the repo) ─────────────────────
+// The repo root: where .peppa/project.json lives (the runner's working copy or worktree).
+const memoryDir = () => {
+ if (!projectFile) throw new PeppaError("No .peppa/project.json found — project memory lives next to it");
+ return dirname(dirname(projectFile.path));
+};
+
+tool(
+ "get_memory",
+ `Read the project memory (${MEMORY_FILE}: commands, conventions, pitfalls, decisions written by earlier agents) and a digest of the last finished stories. Runner sessions already get it in the system prompt.`,
+ {},
+ async () => {
+ const dir = memoryDir();
+ const project = await projectOrDefault();
+ return memoryContext(db, project.id, dir);
+ },
+);
+
+tool(
+ "remember",
+ `Add one durable fact to the project memory (${MEMORY_FILE}) for the next agents: a build/test command, a convention, a pitfall you hit, a decision. One short line; duplicates are skipped. With replace: true, \`text\` becomes the whole memory (use it to compact when the size limit is near). Commit the file in your story branch.`,
+ {
+ section: z.string().optional().describe(`One of: ${MEMORY_SECTIONS.join(", ")} (or commands, conventions, pitfalls, decisions). Not needed with replace.`),
+ text: z.string().describe("The fact (one line), or the whole memory with replace: true"),
+ replace: z.boolean().optional(),
+ },
+ async ({ section, text, replace }) => {
+ const dir = memoryDir();
+ if (replace) {
+ const st = replaceMemory(dir, text);
+ return `Память переписана: ${st.chars} из ${st.max} символов. Закоммить ${MEMORY_FILE} в ветке стори.`;
+ }
+ const r = rememberFact(dir, section ?? "", text);
+ if (r.result === "exists") return "Такой пункт уже есть — ничего не изменил.";
+ return `Запомнил. Память: ${r.stats.chars} из ${r.stats.max} символов${r.stats.nearLimit ? " — почти предел, ужми (remember с replace: true)" : ""}. Закоммить ${MEMORY_FILE} в ветке стори.`;
+ },
+);
+
await server.connect(new StdioServerTransport());
diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts
index 2447fa81..b844eb7b 100644
--- a/packages/mcp/src/manager.ts
+++ b/packages/mcp/src/manager.ts
@@ -40,6 +40,12 @@ import {
accountUsageForUser,
describeAccount,
projectMetrics,
+ getProjectAgentSettings,
+ resolveAgentSettings,
+ setProjectAgentSettings,
+ setTaskAgentSettings,
+ type AgentSettings,
+ type AgentSettingsPatch,
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
@@ -72,6 +78,43 @@ Good habits:
- Autonomy (get_project_settings / update_project_settings): manual by default; "auto" lets Peppa take stories from the backlog, merge green PRs and close stories itself; "assisted" only pushes the user when agents idle. Change it only when the user asks.
- Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`;
+const agentSchema = z
+ .object({
+ provider: z.enum(["claude", "codex", "opencode"]).nullable().optional().describe("Agent CLI; null = inherit (the subscription decides)"),
+ model: z.string().nullable().optional().describe("--model value (sonnet, opus, gpt-5-codex…); null = inherit"),
+ effort: z.enum(["low", "medium", "high", "xhigh", "max"]).nullable().optional(),
+ escalate_model: z.string().nullable().optional().describe("Stronger model after escalate_after failures (red CI attempts + reviewer returns)"),
+ escalate_effort: z.enum(["low", "medium", "high", "xhigh", "max"]).nullable().optional(),
+ escalate_after: z.number().int().min(0).max(20).nullable().optional().describe("0 = never escalate"),
+ fallback_provider: z.enum(["claude", "codex", "opencode"]).nullable().optional().describe("Used when the main provider has no working subscription"),
+ fallback_model: z.string().nullable().optional(),
+ })
+ .optional()
+ .describe("PEP-41 agent model settings; fields left out stay, null resets to inherited");
+
+/** MCP snake_case agent patch → stored camelCase patch (null → inherit, escalate_after 0 → off). */
+function agentPatch(a: NonNullable>): Record {
+ const map: Record = { provider: "provider", model: "model", effort: "effort", escalate_model: "escalateModel", escalate_effort: "escalateEffort", escalate_after: "escalateAfter", fallback_provider: "fallbackProvider", fallback_model: "fallbackModel" };
+ const out: Record = {};
+ for (const [k, v] of Object.entries(a)) {
+ if (v === undefined) continue;
+ const key = map[k]!;
+ out[key] = key === "escalateAfter" ? (v === 0 ? null : v === null ? "" : v) : v === null ? "" : v;
+ }
+ return out;
+}
+
+function describeAgent(s: AgentSettings, own: AgentSettingsPatch): string {
+ const mark = (k: keyof AgentSettings) => (k in own ? "" : " (inherited)");
+ return [
+ "Agent model (PEP-41):",
+ `- provider: ${s.provider ?? "subscription decides"}${mark("provider")}`,
+ `- model: ${s.model ?? "CLI default"}${mark("model")}, effort: ${s.effort ?? "default"}${mark("effort")}`,
+ `- escalation: ${s.escalateModel && s.escalateAfter != null ? `${s.escalateModel}${s.escalateEffort ? ` (${s.escalateEffort})` : ""} after ${s.escalateAfter} failures` : "off"}`,
+ `- fallback provider: ${s.fallbackProvider ? `${s.fallbackProvider}${s.fallbackModel ? ` / ${s.fallbackModel}` : ""}` : "none"}`,
+ ].join("\n");
+}
+
export function createManagerServer(db: Db, user: User, webUrl: string): McpServer {
const server = new McpServer({ name: "peppa", version: "0.3.0" }, { instructions: MANAGER_INSTRUCTIONS });
@@ -220,9 +263,9 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
);
// PEP-23: autonomy of a project — levels and individual settings (owner or member).
- tool("get_project_settings", "A project's autonomy settings: who takes stories from the backlog, PM approval of proposals, merge and closing mode, idle pushes.", { project: projectArg }, true, async ({ project }) => {
+ tool("get_project_settings", "A project's autonomy settings (who takes stories from the backlog, PM approval of proposals, merge and closing mode, idle pushes) and the agent model (provider, model, effort, escalation, fallback provider).", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
- return describeAutonomy(await getAutonomy(db, p.id));
+ return `${describeAutonomy(await getAutonomy(db, p.id))}\n\n${describeAgent(await resolveAgentSettings(db, p.id), await getProjectAgentSettings(db, p.id))}`;
});
tool(
@@ -241,10 +284,12 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
idle_push_hours: z.number().int().min(1).max(168).optional(),
quiet_from: z.number().int().min(0).max(23).nullable().optional(),
quiet_to: z.number().int().min(0).max(23).nullable().optional(),
+ agent: agentSchema,
},
false,
async (a) => {
const p = await ownedProject(a.project);
+ if (a.agent) await setProjectAgentSettings(db, p.id, agentPatch(a.agent), true);
const s = await setAutonomy(db, p.id, {
level: a.level,
pick: a.pick,
@@ -258,7 +303,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
quietFrom: a.quiet_from,
quietTo: a.quiet_to,
});
- return `${p.key}:\n${describeAutonomy(s)}`;
+ return `${p.key}:\n${describeAutonomy(s)}\n\n${describeAgent(await resolveAgentSettings(db, p.id), await getProjectAgentSettings(db, p.id))}`;
},
);
@@ -327,7 +372,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"update_task",
- "Edit a story: title, description, epic and/or dependencies (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
+ "Edit a story: title, description, epic, dependencies and/or agent model for this story (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
{
task: taskArg,
title: z.string().trim().min(3).optional().describe("New title"),
@@ -335,12 +380,14 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
epic_id: z.number().int().nullable().optional().describe("Label with this epic of the same project; null removes the epic"),
goal_id: z.number().int().nullable().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Replaces the stories this one waits for (keys like PEP-3); [] removes all dependencies"),
+ agent: agentSchema,
},
false,
- async ({ task, title, description, epic_id, goal_id, blocked_by }) => {
+ async ({ task, title, description, epic_id, goal_id, blocked_by, agent }) => {
const epic = epic_id !== undefined ? epic_id : goal_id;
- if (title === undefined && description === undefined && epic === undefined && blocked_by === undefined) throw new PeppaError("Nothing to update: pass title, description, epic_id and/or blocked_by");
+ if (title === undefined && description === undefined && epic === undefined && blocked_by === undefined && agent === undefined) throw new PeppaError("Nothing to update: pass title, description, epic_id, blocked_by and/or agent");
const ref = await ownedTask(task);
+ if (agent) await setTaskAgentSettings(db, ref.task.id, agentPatch(agent), true);
if (blocked_by !== undefined) await setDependencies(db, ref, blocked_by);
if (title !== undefined || description !== undefined || epic !== undefined) await updateTask(db, ref, { title, description, goalId: epic });
const updated = await resolveTask(db, ref.key);
diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts
index 0c61d5fb..1a02cb45 100644
--- a/packages/runner/src/ci-feedback.ts
+++ b/packages/runner/src/ci-feedback.ts
@@ -22,6 +22,7 @@ import {
import { checkRuns, projects, tasks, type Db } from "@peppa/db";
import { and, eq, sql } from "drizzle-orm";
import { sendToSession } from "./sessions.ts";
+import { sendWithEscalation } from "./escalation.ts";
import { moveTask } from "./flow.ts";
import { recordRelease, recordScreenshots } from "./deploy.ts";
import { offerPlatformRelease } from "./platform-release.ts";
@@ -89,7 +90,8 @@ export async function recordCheck(db: Db, project: Project, r: CheckReport): Pro
`Почини (локально: bash .gitea/peppa-check.sh ${r.check}) и запушь в ту же ветку; не ослабляй проверки.`,
].join("\n\n");
if (sessionId) {
- await sendToSession(db, sessionId, text);
+ // PEP-41: at the failure threshold the runner is relaunched on the stronger model.
+ await sendWithEscalation(db, sessionId, text);
// The work is not done: a task that already went to review goes back.
if (ref.task.status === "review") await moveTask(db, ref, "in_progress");
return { task: ref.key, action: "agent" };
diff --git a/packages/runner/src/escalation.ts b/packages/runner/src/escalation.ts
new file mode 100644
index 00000000..9db6f2d4
--- /dev/null
+++ b/packages/runner/src/escalation.ts
@@ -0,0 +1,27 @@
+// PEP-41: feedback to a live agent with escalation — once a story reaches its failure
+// threshold, the runner is relaunched (same conversation) on the stronger model instead of
+// getting the message typed into the weaker one.
+import { checkEscalation, getSession, launchModelFor, logSessionEvent, resolveAgentSettings, sessionLaunchModel } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { resumeSession, sendToSession } from "./sessions.ts";
+import * as tmux from "./tmux.ts";
+
+export async function sendWithEscalation(db: Db, sessionId: number, text: string): Promise<"sent" | "escalated"> {
+ const s = await getSession(db, sessionId);
+ if (s.taskId) {
+ const { escalation } = await checkEscalation(db, s.projectId, s.taskId);
+ if (escalation) {
+ const want = launchModelFor(await resolveAgentSettings(db, s.projectId, s.taskId), s.provider, true).model;
+ const cur = await sessionLaunchModel(db, s.id);
+ if (want && want !== cur) {
+ if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
+ await logSessionEvent(db, s, "model_escalated", { from: cur, to: want, failures: escalation.failures });
+ const prompt = `У стори уже ${escalation.failures} неудач(и) (красные проверки и возвраты ревьюера) — Пеппа перезапустила тебя на более сильной модели (${want}).\n\n${text}`;
+ await resumeSession(db, s.id, { prompt });
+ return "escalated";
+ }
+ }
+ }
+ await sendToSession(db, sessionId, text);
+ return "sent";
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index fe2f7cb7..42f98810 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -33,3 +33,4 @@ export * from "./budgets.ts";
export * from "./runner-client.ts";
export * from "./runner-service.ts";
export * from "./recovery.ts";
+export * from "./escalation.ts";
diff --git a/packages/runner/src/providers.ts b/packages/runner/src/providers.ts
index 1219278c..118a68e5 100644
--- a/packages/runner/src/providers.ts
+++ b/packages/runner/src/providers.ts
@@ -22,6 +22,8 @@ export interface LaunchContext {
resume?: string;
permissionMode?: string;
model?: string;
+ /** PEP-41: Claude --effort, Codex model_reasoning_effort (OpenCode has none). */
+ effort?: string;
}
/** argv for one run of the agent CLI (executable first). */
@@ -44,6 +46,7 @@ function claudeCommand(c: LaunchContext): string[] {
"--permission-mode",
c.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits",
...(c.model ? ["--model", c.model] : []),
+ ...(c.effort ? ["--effort", c.effort] : []),
...(c.resume ? ["--resume", c.resume] : []),
"--",
c.prompt,
@@ -64,6 +67,8 @@ function codexCommand(c: LaunchContext): string[] {
c.cwd,
...(c.permissionMode ?? process.env.PEPPA_CODEX_MODE ?? "--full-auto").split(" ").filter(Boolean),
...(c.model ? ["--model", c.model] : []),
+ // Codex knows low/medium/high (xhigh/max → high).
+ ...(c.effort ? ["-c", `model_reasoning_effort=${toml(["xhigh", "max"].includes(c.effort) ? "high" : c.effort)}`] : []),
"-c",
`notify=${toml([HOOK_BIN(), "codex-notify"])}`,
"-c",
diff --git a/packages/runner/src/reviewer.ts b/packages/runner/src/reviewer.ts
index c12cc2f4..365b47f2 100644
--- a/packages/runner/src/reviewer.ts
+++ b/packages/runner/src/reviewer.ts
@@ -32,6 +32,7 @@ import { formatTaskKey } from "@peppa/shared";
import { eq } from "drizzle-orm";
import { claudePrint } from "./claude-print.ts";
import { sendToSession } from "./sessions.ts";
+import { sendWithEscalation } from "./escalation.ts";
import { moveTask } from "./flow.ts";
export interface ReviewVerdict {
@@ -201,7 +202,7 @@ export async function processReview(db: Db, id: number, gitea: GiteaClient = git
].join("\n\n");
if (sessionId) {
try {
- await sendToSession(db, sessionId, text);
+ await sendWithEscalation(db, sessionId, text);
return review;
} catch {}
}
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index ff25f745..e91061ba 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -14,6 +14,10 @@ import {
getQuestion,
listSessions,
loadSharedRules,
+ memoryContext,
+ checkEscalation,
+ launchModelFor,
+ resolveAgentSettings,
PeppaError,
resolveTask,
updateSession,
@@ -45,7 +49,9 @@ export interface StartOptions {
/** Extra instructions appended to the default "work on " prompt. */
prompt?: string;
permissionMode?: string;
+ /** PEP-41: explicit model/effort win over the agent settings. */
model?: string;
+ effort?: string;
/** Project for a bare task number ("42"). */
defaultProjectKey?: string;
provider?: Provider;
@@ -103,9 +109,25 @@ export async function startRunner(
await assertRunnerSlot(db, project.id, rs.maxRunners);
// PEP-67: the first free active subscription of the chosen set decides the provider.
- const sub = await pickSubscription(db, { projectId: project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider: opts.provider });
- const provider = sub?.provider ?? opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
+ // PEP-41: the agent settings may ask for a provider; with none usable — the fallback one.
+ const agent = await resolveAgentSettings(db, project.id, task?.id);
+ const wanted = opts.provider ?? (opts.subscriptionIds?.length ? undefined : (agent.provider ?? undefined));
+ const pick = (provider: Provider | undefined) => pickSubscription(db, { projectId: project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider });
+ let sub: Awaited>;
+ let fallback: { from: Provider | null; reason: string } | null = null;
+ try {
+ sub = await pick(wanted);
+ } catch (e) {
+ const fb = agent.fallbackProvider;
+ if (!fb || opts.provider || opts.subscriptionIds?.length || fb === wanted) throw e;
+ sub = await pick(fb).catch(() => {
+ throw e;
+ });
+ fallback = { from: wanted ?? null, reason: (e as Error).message };
+ }
+ const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
const session = await createSession(db, { projectId: project.id, taskId: task?.id ?? null, provider, subscriptionId: sub?.id ?? null, name: opts.name?.trim() || null });
+ if (fallback) await logSessionEvent(db, await getSession(db, session.id), "provider_fallback", { from: fallback.from, to: provider, subscriptionId: sub?.id ?? null, reason: fallback.reason });
const tmuxName = `peppa-${(task?.key ?? project.key).toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
if (task) await activateRunnerTask(db, session.id, task.id);
@@ -187,17 +209,33 @@ async function launch(
): Promise {
const generation = s.generation + 1;
const rules = await loadSharedRules();
+ // PEP-30: the project's memory and recent stories go with the shared rules.
+ const memory = await memoryContext(db, s.projectId, cwd).catch(() => "");
// The session's subscription (rotation changes it beforehand, PEP-39); none = this machine's login.
const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
+ // PEP-41: model and effort from the agent settings (escalated after failures of the story).
+ let model = opts.model;
+ let effort = opts.effort;
+ let escalated = false;
+ if (!model && !effort) {
+ const agent = await resolveAgentSettings(db, s.projectId, s.taskId);
+ const esc = s.taskId ? await checkEscalation(db, s.projectId, s.taskId) : null;
+ const lm = launchModelFor(agent, s.provider, !!esc?.escalation);
+ model = lm.model ?? undefined;
+ effort = lm.effort ?? undefined;
+ escalated = lm.escalated;
+ if (esc?.fresh && lm.escalated) await logSessionEvent(db, s, "model_escalated", { to: lm.model, failures: esc.escalation!.failures });
+ }
const argv = buildCommand(s.provider, {
sessionId: s.id,
generation,
cwd,
prompt: opts.prompt,
- rules: rules.text,
+ rules: memory ? `${rules.text}\n\n${memory}` : rules.text,
resume: opts.resume,
permissionMode: opts.permissionMode,
- model: opts.model,
+ model,
+ effort,
});
// tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux
// command line, and leaves a record of exactly what was started.
@@ -250,6 +288,9 @@ async function launch(
prompt: opts.prompt,
provider: s.provider,
subscriptionId: sub?.id ?? null,
+ model: model ?? null,
+ effort: effort ?? null,
+ ...(escalated ? { escalated: true } : {}),
rulesSource: rules.source,
});
return getSession(db, s.id);
diff --git a/packages/testkit/test/agent-smarts.test.ts b/packages/testkit/test/agent-smarts.test.ts
new file mode 100644
index 00000000..ea05d1db
--- /dev/null
+++ b/packages/testkit/test/agent-smarts.test.ts
@@ -0,0 +1,202 @@
+// PEP-30 project memory, PEP-41 model/provider per story with escalation and a fallback
+// provider, PEP-31 first-run checklist — against mock CLIs and a temporary SQLite file.
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { events, tasks } from "@peppa/db";
+import { eq } from "drizzle-orm";
+import { core, db, project, runner, setDefaultOwner, teardown, waitFor } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+
+type User = Awaited>;
+let pm: User;
+before(async () => {
+ pm = await core.upsertUserFromGitea(db, { id: 3041, login: "mock-pm-3041" }, { access_token: "x" });
+ setDefaultOwner(pm.id);
+});
+after(teardown);
+
+const argvOf = (e: { argv?: unknown }) => (e.argv as string[]) ?? [];
+const flag = (argv: string[], name: string) => {
+ const i = argv.indexOf(name);
+ return i >= 0 ? argv[i + 1] : undefined;
+};
+const sessionEvents = async (sid: number, type: string) => (await db.select().from(events)).filter((e) => e.sessionId === sid && e.type === type).map((e) => e.payload as Record);
+
+describe("PEP-30: память проекта", () => {
+ test("remember: создаёт файл и раздел, дубль не добавляется, предел и replace", () => {
+ const dir = mkdtempSync(join(tmpdir(), "peppa-mem-"));
+ const r1 = core.rememberFact(dir, "commands", "тесты: pnpm test");
+ assert.equal(r1.result, "added");
+ const text = core.readMemory(dir);
+ assert.match(text, /## Команды\n- тесты: pnpm test/);
+ assert.equal(core.rememberFact(dir, "Команды", " Тесты: pnpm test ").result, "exists");
+ core.rememberFact(dir, "грабли", "миграции — только drizzle-kit generate");
+ core.rememberFact(dir, "Команды", "сборка: pnpm build");
+ const t2 = core.readMemory(dir);
+ assert.ok(t2.indexOf("сборка: pnpm build") < t2.indexOf("## Грабли"), "a new bullet lands in its own section");
+ assert.throws(() => core.rememberFact(dir, "разное", "x"), /Раздел памяти/);
+
+ process.env.PEPPA_MEMORY_MAX_CHARS = String(t2.length + 20);
+ try {
+ assert.throws(() => core.rememberFact(dir, "Решения", "очень длинное решение, которое не влезет в предел памяти"), /предел.*replace: true/s);
+ assert.equal(core.readMemory(dir), t2, "rejected remember leaves the file as it was");
+ core.replaceMemory(dir, "# Память проекта\n\n## Команды\n- pnpm test");
+ assert.equal(core.readMemory(dir), "# Память проекта\n\n## Команды\n- pnpm test\n");
+ assert.ok(core.memoryStats(core.readMemory(dir)).chars < t2.length);
+ } finally {
+ delete process.env.PEPPA_MEMORY_MAX_CHARS;
+ }
+ });
+
+ test("Раннер кладёт память и последние стори в правила запуска", async () => {
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ core.rememberFact(p.dir, "Команды", "тесты: pnpm test");
+ const proj = await core.getProject(db, p.key);
+ const done = await core.createTask(db, { projectId: proj.id, title: "Готовая стори", description: "" });
+ await core.updateTask(db, done, { status: "done", openspecChange: "pep-x-done" });
+ const sid = await p.start();
+ const start = await p.waitLog("started", (e) => e.ev === "start");
+ const rules = readFileSync(flag(argvOf(start), "--append-system-prompt-file")!, "utf8");
+ assert.match(rules, /# Память проекта \(PEP-30\)/);
+ assert.match(rules, /тесты: pnpm test/);
+ assert.match(rules, new RegExp(`${done.key} «Готовая стори» — change pep-x-done`));
+ await runner.stopSession(db, sid);
+ });
+});
+
+describe("PEP-41: модель и провайдер стори", () => {
+ test("Модель и усилия наследуются платформа → проект → стори; чужому провайдеру модель не уходит", async () => {
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ const proj = await core.getProject(db, p.key);
+ const ref = await core.resolveTask(db, p.taskKey);
+ await core.setProjectAgentSettings(db, proj.id, { model: "sonnet", effort: "medium" });
+ await core.setTaskAgentSettings(db, ref.task.id, { model: "opus", effort: "high" });
+ assert.deepEqual(
+ { model: (await core.resolveAgentSettings(db, proj.id, ref.task.id)).model, projectModel: (await core.resolveAgentSettings(db, proj.id)).model },
+ { model: "opus", projectModel: "sonnet" },
+ );
+ await assert.rejects(core.setProjectAgentSettings(db, proj.id, { effort: "turbo" }), /Недопустимое значение effort/);
+ const sid = await p.start();
+ const argv = argvOf(await p.waitLog("started", (e) => e.ev === "start"));
+ assert.equal(flag(argv, "--model"), "opus");
+ assert.equal(flag(argv, "--effort"), "high");
+ const [ev] = await sessionEvents(sid, "started");
+ assert.equal(ev!.model, "opus");
+ await runner.stopSession(db, sid);
+
+ const s = { ...core.DEFAULT_AGENT_SETTINGS, provider: "claude" as const, model: "opus", fallbackProvider: "codex" as const };
+ assert.deepEqual(core.launchModelFor(s, "codex", false), { model: null, effort: null, escalated: false });
+ assert.equal(core.launchModelFor({ ...s, fallbackModel: "gpt-5-codex" }, "codex", false).model, "gpt-5-codex");
+ });
+
+ test("Codex получает model_reasoning_effort", async () => {
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ const proj = await core.getProject(db, p.key);
+ await core.setProjectAgentSettings(db, proj.id, { model: "gpt-5-codex", effort: "xhigh" });
+ const sid = await p.start({ provider: "codex" });
+ const argv = argvOf(await p.waitLog("started", (e) => e.ev === "start"));
+ assert.equal(flag(argv, "--model"), "gpt-5-codex");
+ assert.ok(argv.includes(`model_reasoning_effort="high"`), argv.join(" "));
+ await runner.stopSession(db, sid);
+ });
+
+ test("После N неудач живой раннер перезапускается на сильной модели с тем же разговором; эскалация липкая", async () => {
+ const p = await project({ turns: [[{ say: "ok" }]], resumeTurns: [[{ say: "Чиню на opus." }]] });
+ const proj = await core.getProject(db, p.key);
+ await core.setProjectAgentSettings(db, proj.id, { model: "sonnet", escalateModel: "opus", escalateEffort: "high", escalateAfter: 2 });
+ const sid = await p.start();
+ const first = await p.waitLog("started", (e) => e.ev === "start");
+ assert.equal(flag(argvOf(first), "--model"), "sonnet");
+ await waitFor("conversation id", async () => (await core.getSession(db, sid)).conversationId);
+ const ref = await core.resolveTask(db, p.taskKey);
+
+ // One failure: below the threshold — the message is typed into the same run.
+ await db.update(tasks).set({ ciAttempts: 1 }).where(eq(tasks.id, ref.task.id));
+ assert.equal(await runner.sendWithEscalation(db, sid, "CI красный #1"), "sent");
+ assert.equal(await core.getEscalation(db, ref.task.id), null);
+
+ await db.update(tasks).set({ ciAttempts: 2 }).where(eq(tasks.id, ref.task.id));
+ assert.equal(await runner.sendWithEscalation(db, sid, "CI красный #2: упал test"), "escalated");
+ const relaunch = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
+ const argv = argvOf(relaunch);
+ assert.equal(flag(argv, "--model"), "opus");
+ assert.equal(flag(argv, "--effort"), "high");
+ assert.equal(relaunch.resume, first.conversationId, "same conversation");
+ assert.match(argv.join(" "), /CI красный #2: упал test/);
+ const [esc] = await sessionEvents(sid, "model_escalated");
+ assert.deepEqual({ from: esc!.from, to: esc!.to, failures: esc!.failures }, { from: "sonnet", to: "opus", failures: 2 });
+
+ // Green CI resets ci_attempts — the story stays on the strong model.
+ await db.update(tasks).set({ ciAttempts: 0 }).where(eq(tasks.id, ref.task.id));
+ assert.equal((await core.getEscalation(db, ref.task.id))!.model, "opus");
+ assert.equal(await runner.sendWithEscalation(db, sid, "ещё замечание"), "sent", "already on opus — no second relaunch");
+ await runner.stopSession(db, sid);
+ });
+
+ test("Все подписки Claude в лимите → раннер стартует на запасном провайдере", async () => {
+ const claude = await runner.addSubscription(db, { provider: "claude", name: "FB Claude", method: "token", secret: `sk-ant-oat01-mock${"x".repeat(24)}fb41`, createdBy: pm.id });
+ await core.updateSubscription(db, claude.id, { status: "limited", limitedUntil: new Date(Date.now() + 3600_000) });
+ const codex = await runner.addSubscription(db, { provider: "codex", name: "FB Codex", method: "api_key", secret: "mock-key-fb41", createdBy: pm.id });
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ const proj = await core.getProject(db, p.key);
+ const pool = await core.createPool(db, { name: "Пул FB41", subscriptionIds: [claude.id, codex.id] });
+ await core.setProjectPool(db, proj.id, pool.id);
+ await core.setProjectAgentSettings(db, proj.id, { provider: "claude", model: "opus", fallbackProvider: "codex", fallbackModel: "gpt-5-codex" });
+
+ // PEP-31: the project page warns only when nothing in the pool works.
+ assert.equal(await core.projectAgentWarning(db, proj.id), null);
+
+ const sid = await p.start();
+ const s = await core.getSession(db, sid);
+ assert.equal(s.provider, "codex");
+ assert.equal(s.subscriptionId, codex.id);
+ const argv = argvOf(await p.waitLog("started", (e) => e.ev === "start"));
+ assert.equal(flag(argv, "--model"), "gpt-5-codex");
+ const [fb] = await sessionEvents(sid, "provider_fallback");
+ assert.deepEqual({ from: fb!.from, to: fb!.to }, { from: "claude", to: "codex" });
+ await runner.stopSession(db, sid);
+
+ // Without a fallback the start fails as before.
+ await core.setProjectAgentSettings(db, proj.id, { provider: "claude" });
+ await assert.rejects(p.start(), /Нет активных подписок/);
+
+ await core.updateSubscription(db, codex.id, { status: "auth_error" });
+ assert.match((await core.projectAgentWarning(db, proj.id))!, /нет рабочей подписки.*«FB Claude» — в лимите.*«FB Codex» — ошибка входа/);
+ });
+});
+
+describe("PEP-31: чек-лист первого запуска", () => {
+ test("Шаги отмечаются по данным, чек-лист скрывается после выполнения или по кнопке", async () => {
+ const u = await core.upsertUserFromGitea(db, { id: 3131, login: "mock-new-3131" }, { access_token: "x" });
+ let ob = await core.onboardingChecklist(db, u);
+ assert.deepEqual(ob.steps.map((s) => s.id), ["telegram", "egov", "project", "story", "started"], "no subscription step for a non-admin");
+ assert.deepEqual({ done: ob.done, total: ob.total, visible: ob.visible }, { done: 0, total: 4, visible: true });
+
+ db.$client.prepare("UPDATE users SET telegram_chat_id = ? WHERE id = ?").run(3131, u.id);
+ setDefaultOwner(u.id);
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ setDefaultOwner(pm.id);
+ ob = await core.onboardingChecklist(db, u);
+ assert.deepEqual(ob.steps.filter((s) => s.done).map((s) => s.id), ["telegram", "project", "story"]);
+ assert.equal(ob.steps.find((s) => s.id === "started")!.href, `/p/${p.key}`);
+
+ const sid = await p.start();
+ ob = await core.onboardingChecklist(db, u);
+ assert.deepEqual({ done: ob.done, complete: ob.complete, visible: ob.visible }, { done: 4, complete: true, visible: false });
+ await runner.stopSession(db, sid);
+
+ const admin = await core.upsertUserFromGitea(db, { id: 3132, login: "mock-admin-3132" }, { access_token: "x" });
+ await core.setPlatformAdmins(db, ["mock-admin-3132"]);
+ ob = await core.onboardingChecklist(db, admin);
+ assert.equal(ob.steps[0]!.id, "subscription");
+ assert.equal(ob.total, 5);
+ await core.dismissOnboarding(db, admin.id);
+ ob = await core.onboardingChecklist(db, admin);
+ assert.deepEqual({ dismissed: ob.dismissed, visible: ob.visible }, { dismissed: true, visible: false });
+ await core.setPlatformAdmins(db, null);
+ });
+});
diff --git a/template/RULES.md b/template/RULES.md
index 965c4a01..0d680905 100644
--- a/template/RULES.md
+++ b/template/RULES.md
@@ -15,6 +15,7 @@
| Что система должна делать (требования) | `openspec/specs/` |
| Что меняем сейчас (proposal, design, tasks) | `openspec/changes//` |
| Метаданные проекта (slug, ключ стори) | `.peppa/project.json` |
+| Память проекта: команды, соглашения, грабли, решения прошлых агентов | `.peppa/memory.md` (MCP `get_memory` / `remember`) |
## Автономный цикл
@@ -60,6 +61,12 @@ PM отвечает только на **архитектурные стоппе
- Тесты и линтеры проекта должны проходить до PR.
### Завершение
+- **Память проекта** (`.peppa/memory.md`): перед PR запиши через `peppa.remember` то, что
+ сэкономит время следующему агенту, — команду сборки/тестов, найденные грабли, соглашение,
+ решение, которого нет в спеках. Один короткий пункт на факт, без пересказа стори. Если
+ `remember` сообщает о пределе — ужми память (`get_memory`, затем `remember` с
+ `replace: true`: объедини похожее, убери устаревшее). Закоммить файл в ветке стори.
+ В сессиях Пеппы память уже в системном промпте (раздел «Память проекта»).
- `openspec archive <имя>` — delta-специфики вливаются в `openspec/specs/`.
- Запушь ветку и открой PR в Gitea (ссылка на стори и резюме change).
- `peppa.update_task` → `status: review`, `pr_url: …` и закончи ход. PM получит «готово
--
2.45.2
From 12d8fea4c22613f7b3ef2d3dca2e94ca779607b3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 07:23:52 +0500
Subject: [PATCH 003/444] PEP-30/41/31: typecheck the e2e test's mock log
access
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/agent-smarts.test.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/testkit/test/agent-smarts.test.ts b/packages/testkit/test/agent-smarts.test.ts
index ea05d1db..51bedc13 100644
--- a/packages/testkit/test/agent-smarts.test.ts
+++ b/packages/testkit/test/agent-smarts.test.ts
@@ -19,7 +19,7 @@ before(async () => {
});
after(teardown);
-const argvOf = (e: { argv?: unknown }) => (e.argv as string[]) ?? [];
+const argvOf = (e: object) => ((e as { argv?: string[] }).argv ?? []);
const flag = (argv: string[], name: string) => {
const i = argv.indexOf(name);
return i >= 0 ? argv[i + 1] : undefined;
--
2.45.2
From 621aa0b5b3e476ddca8379b56303eaaee27d4291 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 07:46:10 +0500
Subject: [PATCH 004/444] PEP-41: escalation goes through the runner service in
client processes (PEP-21)
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 2 +-
packages/runner/src/escalation.ts | 3 +++
packages/runner/src/runner-service.ts | 3 +++
3 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/AGENTS.md b/AGENTS.md
index a30f38fc..893058e8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -48,7 +48,7 @@
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
- **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` терпим к вариантам полей — формат live-CLI не сверен, `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:` / `budget.task:` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой
- **Память проекта (PEP-30)**: `.peppa/memory.md` в репо проекта (разделы Команды/Соглашения/Грабли/Решения), `core/memory.ts` (`rememberFact` — дубли пропускаются, предел `PEPPA_MEMORY_MAX_CHARS` 12 000 → отказ с просьбой ужать; `replaceMemory`; `memoryContext` = файл рабочей копии + 5 последних `done` стори). MCP агента `get_memory`/`remember` (файл рядом с `.peppa/project.json`, коммитит агент в ветке стори). Раннер (`launch` в runner/sessions.ts) дописывает `memoryContext` к общим правилам при каждом запуске/resume. Правило — «Завершение» в `template/RULES.md`; веб — вкладка «Спеки» (`MemorySection`)
-- **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:` → `task.agent:` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent k=v…`
+- **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:` → `task.agent:` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer; у клиентов PEP-21 — команда сервиса `sendEscalated`): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent k=v…`
- **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
diff --git a/packages/runner/src/escalation.ts b/packages/runner/src/escalation.ts
index 9db6f2d4..ae505b70 100644
--- a/packages/runner/src/escalation.ts
+++ b/packages/runner/src/escalation.ts
@@ -5,8 +5,11 @@ import { checkEscalation, getSession, launchModelFor, logSessionEvent, resolveAg
import type { Db } from "@peppa/db";
import { resumeSession, sendToSession } from "./sessions.ts";
import * as tmux from "./tmux.ts";
+import { isRunnerClient, runnerCall } from "./runner-client.ts";
export async function sendWithEscalation(db: Db, sessionId: number, text: string): Promise<"sent" | "escalated"> {
+ // PEP-21: clients (web, bot) hand it to the runner service as one command.
+ if (isRunnerClient()) return (await runnerCall<{ result: "sent" | "escalated" }>(db, "sendEscalated", { sessionId, text }, { key: `session:${sessionId}` })).result;
const s = await getSession(db, sessionId);
if (s.taskId) {
const { escalation } = await checkEscalation(db, s.projectId, s.taskId);
diff --git a/packages/runner/src/runner-service.ts b/packages/runner/src/runner-service.ts
index c5b93b5b..dab21ac9 100644
--- a/packages/runner/src/runner-service.ts
+++ b/packages/runner/src/runner-service.ts
@@ -11,6 +11,7 @@ import { resumeSession, sendToSession, startSession, stopSession, answerAndDeliv
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";
+import { sendWithEscalation } from "./escalation.ts";
type P = Record;
type Handler = (db: Db, p: P) => Promise;
@@ -24,6 +25,8 @@ export const RUNNER_COMMANDS: Record = {
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), {}),
+ // PEP-41: feedback that may relaunch the runner on the escalation model (one atomic step).
+ sendEscalated: async (db, p) => ({ result: await sendWithEscalation(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 }),
--
2.45.2
From ca57f9543b0556ccafab0b882fe5dd3abb1fa905 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 07:48:02 +0500
Subject: [PATCH 005/444] PEP-17/40: agent sandbox per runner (docker + agent
relay) and runner hosts over SSH
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 3 +
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/hosts/actions.ts | 73 +
apps/web/app/(app)/hosts/page.tsx | 133 +
apps/web/app/(app)/p/[key]/page.tsx | 6 +-
apps/web/app/(app)/settings/page.tsx | 3 +
apps/web/app/api/agent/[...path]/route.ts | 18 +
apps/web/components/RunnerConsole.tsx | 5 +
apps/web/components/Runners.tsx | 37 +-
apps/web/components/Sidebar.tsx | 3 +-
apps/web/components/cards.tsx | 2 +
infra/runner/Dockerfile | 34 +
infra/runner/bin/peppa-agent.mjs | 1 +
infra/runner/bin/peppa-hook | 3 +
infra/runner/bin/peppa-mcp | 3 +
infra/runner/peppa-agent.mjs | 122 +
.../design.md | 90 +
.../proposal.md | 44 +
.../specs/agent-sandbox/spec.md | 55 +
.../specs/runner-hosts/spec.md | 39 +
.../tasks.md | 26 +
openspec/specs/agent-sandbox/spec.md | 60 +
openspec/specs/runner-hosts/spec.md | 44 +
packages/cli/src/index.ts | 64 +-
packages/core/src/crypto.ts | 18 +
packages/core/src/hosts.ts | 115 +
packages/core/src/index.ts | 1 +
packages/core/src/runners.ts | 18 +-
packages/core/src/sessions.ts | 23 +-
packages/db/migrations/0013_runner_hosts.sql | 18 +
.../db/migrations/meta/0013_snapshot.json | 3652 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 35 +
packages/mcp/package.json | 4 +-
packages/mcp/src/agent.ts | 332 ++
packages/mcp/src/index.ts | 299 +-
packages/mcp/src/relay.ts | 18 +
packages/runner/src/agent-relay.ts | 204 +
packages/runner/src/budgets.ts | 4 +-
packages/runner/src/exec.ts | 128 +
packages/runner/src/hosts.ts | 153 +
packages/runner/src/index.ts | 4 +
packages/runner/src/providers.ts | 37 +-
packages/runner/src/recovery.ts | 4 +-
packages/runner/src/rotation.ts | 2 +-
packages/runner/src/run-settings.ts | 7 +-
packages/runner/src/runners.ts | 4 +-
packages/runner/src/sandbox.ts | 147 +
packages/runner/src/sessions.ts | 150 +-
packages/runner/src/terminal.ts | 30 +-
packages/runner/src/tmux.ts | 114 +-
packages/runner/src/watchdog.ts | 19 +-
packages/testkit/bin/mock-docker | 67 +-
packages/testkit/bin/mock-ssh | 43 +
packages/testkit/test/runners.test.ts | 2 +-
packages/testkit/test/sandbox-hosts.test.ts | 370 ++
scripts/runner-image.sh | 17 +
template/RULES.md | 9 +
59 files changed, 6482 insertions(+), 443 deletions(-)
create mode 100644 apps/web/app/(app)/hosts/actions.ts
create mode 100644 apps/web/app/(app)/hosts/page.tsx
create mode 100644 apps/web/app/api/agent/[...path]/route.ts
create mode 100644 infra/runner/Dockerfile
create mode 120000 infra/runner/bin/peppa-agent.mjs
create mode 100755 infra/runner/bin/peppa-hook
create mode 100755 infra/runner/bin/peppa-mcp
create mode 100644 infra/runner/peppa-agent.mjs
create mode 100644 openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/agent-sandbox/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/runner-hosts/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/tasks.md
create mode 100644 openspec/specs/agent-sandbox/spec.md
create mode 100644 openspec/specs/runner-hosts/spec.md
create mode 100644 packages/core/src/hosts.ts
create mode 100644 packages/db/migrations/0013_runner_hosts.sql
create mode 100644 packages/db/migrations/meta/0013_snapshot.json
create mode 100644 packages/mcp/src/agent.ts
create mode 100644 packages/mcp/src/relay.ts
create mode 100644 packages/runner/src/agent-relay.ts
create mode 100644 packages/runner/src/exec.ts
create mode 100644 packages/runner/src/hosts.ts
create mode 100644 packages/runner/src/sandbox.ts
create mode 100755 packages/testkit/bin/mock-ssh
create mode 100644 packages/testkit/test/sandbox-hosts.test.ts
create mode 100755 scripts/runner-image.sh
diff --git a/AGENTS.md b/AGENTS.md
index 893058e8..1ddee46e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,6 +21,7 @@
- **Раннеры (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`, переживает рестарт
+ - **Песочница и хосты (PEP-17/40)**: настройки раннеров `isolation` none (по умолчанию, как раньше) / container и `hosts` (id хостов; пусто — Mac Пеппы; хост → всегда контейнер). Все вызовы tmux — по адресу pane `{name, host}` (`tmux.sessionPane(s)`, `runner/exec.ts`: локально или `ssh` ключом `$PEPPA_HOME/ssh/id_ed25519`, ControlMaster; код 255 → `HostUnreachable`, `hasSession` его не глотает — вачдог не объявит раннер пропавшим). Контейнер (`runner/sandbox.ts`): tmux снаружи, `docker run --rm -it --init --name peppa-s` образа `PEPPA_RUNNER_IMAGE` (`infra/runner/Dockerfile`, `scripts/runner-image.sh`), монтируются только рабочая копия (+ `.git` проекта для worktree, `CODEX_HOME` подписки), каталог запуска → `/peppa/run:ro`, свой HOME → `/peppa/home`; env — только сессии/релея/подписки (значения в tmux, в launch.sh только имена); без подписки не стартует; остановка — `killRunner` (tmux + `docker rm -f`). Релей агента (`runner/agent-relay.ts`, веб `/api/agent/[...path]`, токен `agentRelayToken` = HMAC сессии+поколения): `hook` (настоящий `peppa-hook` в Пеппе; ответ ≤25 с, дальше `{wait, rid}`; транскрипт прикладывает шим), `mcp` (`@peppa/mcp/relay`: сервер агента с `lockProject`), `git/…` (прокси в Gitea с токеном бота, только `owner/repo` проекта; в контейнере `GIT_CONFIG_*` insteadOf). Шимы в образе — `infra/runner/peppa-agent.mjs` (`peppa-hook`, `peppa-mcp`). Хосты: таблица `runner_hosts`, `sessions.host_id`/`container` (миграция 0013), `runner/hosts.ts` (`checkHost`, `hostTick` в вачдоге раз в минуту, клон `/ws//s` одноразовым контейнером через релей, каталог запуска tar по SSH), выбор — `pickHost` (наименее занятый онлайн). Веб `/hosts` (суперадмин), «⋯ Настройки проекта → Раннеры»; CLI `peppa host list|key|add|set|check|disable|enable|rm|push-image`. Моки: `mock-docker run` (исполняет команду образа локально, env только из `-e`, `runs.jsonl`), `mock-ssh` (`MOCK_SSH_ROOT/`, свой tmux, `MOCK_SSH_DOWN`)
- хуки не в репо проекта, а в генерируемом `~/.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/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index e571ab09..250e91f2 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -261,7 +261,10 @@ export async function setRunnerSettingsAction(f: FormData) {
mode: pick("mode"),
context: pick("context"),
workspace: pick("workspace"),
+ isolation: pick("isolation"),
...(max === "" ? {} : { maxRunners: max === "0" ? null : Number(max) }),
+ // PEP-40: "" inherit, local — Peppa's machine, list — the ticked hosts.
+ ...(str(f, "hostsMode") === "local" ? { hosts: [] } : str(f, "hostsMode") === "list" ? { hosts: f.getAll("hosts").map(Number).filter((n) => n > 0) } : {}),
});
});
}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 833c0ec6..7c7e4331 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -74,6 +74,7 @@ export default async function Help() {
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.
Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.
+
Изоляция и хосты — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Пеппы и чужих проектов; хуки, MCP и git идут в Пеппу через релей и только к репозиторию проекта (PR агент открывает инструментом open_pull_request). «Где запускать раннеры» — Mac Пеппы или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Пеппы на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими.
Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
+
+ Хосты>}>
+ Серверы, на которых работают раннеры. Пеппа заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Пеппу только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.
+
+
+
+ {hosts.length === 0 ? Хостов нет — раннеры работают на Mac Пеппы. : hosts.map((h) => )}
+ Подключить хост}>
+
+
+
+
+
+
+
+ Добавьте ключ Пеппы в ~/.ssh/authorized_keys пользователя на хосте:
+
{pub}
+
+
Установите tmux и docker; пользователь должен иметь доступ к docker.
+
+ Загрузите образ раннера {runnerImage()}: scripts/runner-image.sh --push <имя хоста> (или peppa host push-image <имя>).
+
+
Адрес Пеппы для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.
+
+
+
+
+ );
+}
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 37611a6d..12d11fea 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
-import { DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -101,7 +101,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const superadmin = await isSuperadmin(db, user);
const [pool, pools, autonomy] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id)]);
// PEP-10/27: runner settings of the project over the system ones.
- const [runnerOwn, runnerSystem, secrets] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id)]);
+ const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
// PEP-41: agent provider/model of the project over the platform's.
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
// PEP-31: the project's pool has no working subscription — agents won't start.
@@ -180,7 +180,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
-
+
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 2105adc6..54e35797 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -89,6 +89,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
+
diff --git a/apps/web/app/api/agent/[...path]/route.ts b/apps/web/app/api/agent/[...path]/route.ts
new file mode 100644
index 00000000..540739cd
--- /dev/null
+++ b/apps/web/app/api/agent/[...path]/route.ts
@@ -0,0 +1,18 @@
+import { agentRelayMcp } from "@peppa/mcp/relay";
+import { handleAgentRelay } from "@peppa/runner";
+import { db } from "@/lib/db";
+
+export const dynamic = "force-dynamic";
+// A blocking hook (question to the PM) is answered in ≤25 s chunks (`wait` + `rid`).
+export const maxDuration = 60;
+
+/**
+ * PEP-17: the agent relay — hooks, MCP and git of agents in runner containers (here or on
+ * runner hosts, PEP-40). No web login: Bearer = the run's own token.
+ */
+async function handle(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
+ const { path } = await params;
+ return handleAgentRelay(db, req, `/${path.join("/")}`, { mcp: agentRelayMcp });
+}
+export const GET = handle;
+export const POST = handle;
diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx
index 72cf4537..68c46d9c 100644
--- a/apps/web/components/RunnerConsole.tsx
+++ b/apps/web/components/RunnerConsole.tsx
@@ -146,6 +146,11 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
{s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
{s.subscriptionSwitches > 0 && · переключений {s.subscriptionSwitches}}
+