From 1e8d9e03277e3ccee847240bbca765303d25b280 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 12:34:40 +0500
Subject: [PATCH 001/439] PEP-3: hooks, statusLine and the permission dialog
checked against live Claude Code 2.1.323
- permission dialog menus vary (3-4 items, "2" may be "switch to auto mode"): the late PM answer
reads the key off the screen (permissionKey); after "No" Claude interrupts the turn without a
Stop hook, so Peppa types PERMISSION_DENIED_NOTE
- statusLine total_*_tokens are the last request, not session totals: tokens only from transcript
- mcp__peppa allowed in run settings (connected repos have no template .claude/settings.json)
- peppa-hook: PEPPA_HOOK_CAPTURE_DIR saves raw payloads; live fixtures in testkit/fixtures/claude-live
- mock-claude follows the live contract (menu, interrupt on No, statusLine, transcript blocks, suggestions)
- peppa-dev: watchdog (runner service) on the stand, mock PEPPA_SECRET without .env
- e2e claude-live.test.ts: fixtures parsing, real peppa-hook on live payloads, terminal fallback keys
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 7 +-
apps/web/next-env.d.ts | 4 +-
.../2026-11-14-pep-3-live-claude/design.md | 74 +++++++
.../2026-11-14-pep-3-live-claude/proposal.md | 27 +++
.../specs/agent-hooks/spec.md | 18 ++
.../specs/runner-sessions/spec.md | 38 ++++
.../2026-11-14-pep-3-live-claude/tasks.md | 15 ++
openspec/specs/agent-hooks/spec.md | 17 ++
openspec/specs/runner-sessions/spec.md | 14 +-
packages/core/src/usage.ts | 10 +-
packages/runner/src/hook.ts | 11 +-
packages/runner/src/run-settings.ts | 3 +
packages/runner/src/sessions.ts | 40 +++-
packages/testkit/bin/peppa-dev | 5 +
.../notification-permission-prompt.json | 10 +
.../claude-live/permission-request-mcp.json | 32 +++
.../claude-live/permission-request.json | 26 +++
.../claude-live/post-tool-use-failure.json | 21 ++
.../fixtures/claude-live/post-tool-use.json | 26 +++
.../pre-tool-use-ask-user-question.json | 33 +++
.../fixtures/claude-live/session-end.json | 9 +
.../fixtures/claude-live/session-start.json | 9 +
.../claude-live/statusline-first.json | 42 ++++
.../fixtures/claude-live/statusline.json | 74 +++++++
.../claude-live/stop-after-block.json | 16 ++
.../testkit/fixtures/claude-live/stop.json | 16 ++
.../fixtures/claude-live/transcript.jsonl | 27 +++
.../claude-live/user-prompt-submit.json | 10 +
packages/testkit/src/mock-agent.ts | 49 +++--
packages/testkit/test/claude-live.test.ts | 196 ++++++++++++++++++
30 files changed, 846 insertions(+), 33 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-3-live-claude/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-3-live-claude/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/agent-hooks/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/runner-sessions/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-3-live-claude/tasks.md
create mode 100644 packages/testkit/fixtures/claude-live/notification-permission-prompt.json
create mode 100644 packages/testkit/fixtures/claude-live/permission-request-mcp.json
create mode 100644 packages/testkit/fixtures/claude-live/permission-request.json
create mode 100644 packages/testkit/fixtures/claude-live/post-tool-use-failure.json
create mode 100644 packages/testkit/fixtures/claude-live/post-tool-use.json
create mode 100644 packages/testkit/fixtures/claude-live/pre-tool-use-ask-user-question.json
create mode 100644 packages/testkit/fixtures/claude-live/session-end.json
create mode 100644 packages/testkit/fixtures/claude-live/session-start.json
create mode 100644 packages/testkit/fixtures/claude-live/statusline-first.json
create mode 100644 packages/testkit/fixtures/claude-live/statusline.json
create mode 100644 packages/testkit/fixtures/claude-live/stop-after-block.json
create mode 100644 packages/testkit/fixtures/claude-live/stop.json
create mode 100644 packages/testkit/fixtures/claude-live/transcript.jsonl
create mode 100644 packages/testkit/fixtures/claude-live/user-prompt-submit.json
create mode 100644 packages/testkit/test/claude-live.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 1ddee46e..626777af 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -24,9 +24,10 @@
- **Песочница и хосты (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) игнорируется
+ - Диалог разрешений Claude меняется (3–4 пункта, «2» бывает «switch to auto mode»): поздний ответ PM — `permissionKey` читает номер с экрана; после «No» Claude прерывает ход без Stop — Пеппа печатает `PERMISSION_DENIED_NOTE` (PEP-3). `mcp__peppa` разрешён в run-settings
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
- - Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3)
+ - Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3 сверил остальное: хуки, statusLine, transcript, диалог разрешений — `packages/testkit/fixtures/claude-live/`, `claude-live.test.ts`; снять лимит — `PEPPA_HOOK_CAPTURE_DIR=<каталог>` в env раннера, хук кладёт туда сырые payload'ы)
- `peppa session resume ` → `claude --resume`
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные пользователи (PEP-68), кроме отключённых; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
@@ -47,7 +48,7 @@
- **Доска, зависимости, планировщик, палитра (PEP-34/42/52)**: порядок стори = приоритет — `tasks.position` (REAL, общий для проекта; `reorderTask` в core, `reorderBoardTask` в runner/flow.ts с колонкой; `listTasks` идёт по позиции и без архивных); архив `tasks.archived_at` (`archiveTask` останавливает агента; удаления нет); `epicProgress` — «готово/всего». Зависимости — таблица `task_deps` (core/deps.ts: блокирует, пока предшественник не в review/done и не в архиве; циклы и чужие проекты отклоняются); диспетчер PEP-24 и пуш простоя берут `readyBacklog` (runner/autonomy.ts). Планировщик — runner/planner.ts: `planEpic` (`$PEPPA_PLANNER_BIN -p`, `${PEPPA_PLANNER_MODEL:-sonnet}`, через `claudePrint`) → черновик в `settings` `planner.draft:` → `applyPlan`; веб `/p//plan/`, мок `mock-planner` (`MOCK_PLANNER_SCENARIO`). Веб-экшены — `app/(app)/board-actions.ts`. MCP PM: `reorder_task`, `archive_task`, `set_dependencies`, `plan_epic`, `apply_plan`, `blocked_by` в create/update_task. Палитра ⌘K — `components/CommandPalette.tsx` (данные `GET /api/palette` → `paletteItems` в core, ранжирование `@peppa/shared/palette` — чистый модуль для браузера), горячие клавиши через `data-hotkey-search|item|answer`, список — `lib/shortcuts.ts` и `/help/shortcuts`
- **Агент-ревьюер (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-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` сверен с 2.1.323 (PEP-3: `context_window.total_*_tokens` — последний запрос, не сумма; токены только из transcript), `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; у клиентов 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` на Главной, плашка «Агенты не запустятся» на странице проекта
@@ -83,7 +84,7 @@
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite; без него тест пропускается); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`)
- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (у каждого файла свой временный SQLite-файл, свой tmux `-L`, свой `PEPPA_HOME` — параллельные worktree не мешают друг другу)
-- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
+- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (mock-telegram, бот, вачдог = раннер-сервис; привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`.
diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts
index a419cbe4..ce4e94a6 100644
--- a/apps/web/next-env.d.ts
+++ b/apps/web/next-env.d.ts
@@ -1,7 +1,7 @@
///
///
-import "./.next/dev/types/routes.d.ts";
-import "./.next/dev/types/root-params.d.ts";
+import "./.next/types/routes.d.ts";
+import "./.next/types/root-params.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/openspec/changes/archive/2026-11-14-pep-3-live-claude/design.md b/openspec/changes/archive/2026-11-14-pep-3-live-claude/design.md
new file mode 100644
index 00000000..7b75cf7b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-3-live-claude/design.md
@@ -0,0 +1,74 @@
+## Как проверяли
+
+Dev-стенд (`PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`), Claude Code **2.1.323**, вход Claude Max,
+модель haiku, `--permission-mode default`, проект `LIVE` с рабочей копией в `~/.peppa-dev/workspaces/live`,
+сценарий за PM — `peppa-dev tg messages|click|reply`. Три сессии, расход около $0.03.
+Сырые payload'ы снимались через `PEPPA_HOOK_CAPTURE_DIR` и лежат в `packages/testkit/fixtures/claude-live/`
+(пути `/Users/` заменены на `/Users/mock`, текст ответов в transcript заменён на «…»).
+
+По пути найдены две поломки самого стенда (PEP-21 и worktree): нет вачдога, значит нет раннер-сервиса,
+и бот не может доставить ответ («Раннер-сервис не запущен»); в worktree нет `.env`, поэтому нет `PEPPA_SECRET`.
+`peppa-dev up` теперь поднимает `dev-watchdog`, а без `.env` ставит mock-ключ.
+
+## Что сверено вживую
+
+| Что | Итог |
+|---|---|
+| AskUserQuestion → хук → кнопка в Telegram → `updatedInput.answers` | ✅ совпадает; TUI показывает «User answered Claude's questions: · Какой цвет? → синий» |
+| AskUserQuestion без ответа → `permissionDecision: deny` с причиной | ✅ агент заканчивает ход и ждёт; ответ PM печатается как «Ответ PM на вопрос #N: Go» |
+| PermissionRequest → хук allow/always/deny | ✅ allow («Allowed by PermissionRequest hook»), always (`updatedPermissions` = `permission_suggestions`), deny |
+| Откат в терминал: клавиша «1» | ✅ |
+| Откат в терминал: «Всегда» / «Запретить» | ❌ **было сломано** (см. ниже), исправлено и проверено вживую |
+| Bracketed paste (`paste-buffer -p`) | ✅ три строки ушли одним промптом, `/exit` вставкой тоже сработал |
+| Stop с `decision: block`, `MAX_AUTO_NUDGES` = 2, потом «Сессия ждёт тебя» | ✅ (TUI называет это «Stop hook error: », работает как надо) |
+| SessionEnd | ✅ `reason: "prompt_input_exit"` после `/exit` |
+| `--append-system-prompt-file` | ✅ агент процитировал первую строку правил «# Правила Пеппы для агентов» |
+| statusLine | ✅ формат совпал с `parseStatusLine`, кроме `total_*_tokens` (см. ниже) |
+| transcript | ✅ одно сообщение API = несколько записей (по блоку `thinking`/`text`/`tool_use`) с тем же `message.id` и одинаковым `usage`; дедуп по id нужен и работает |
+| PostToolUse / PostToolUseFailure (шаги PEP-33) | ✅ у Failure поле `error`, `is_interrupt` |
+| Notification | ✅ `notification_type: "permission_prompt"`, текст короче, чем в моке: «Claude needs your permission» |
+
+## Расхождения и решения
+
+1. **Меню диалога разрешений не фиксировано.** В одной сессии встретились три меню:
+ «1. Yes / 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode / 4. No»,
+ «1. Yes / 2. Yes, and switch to auto mode / 3. No» и «1. Yes / 2. Yes, and don't ask again for … / 3. No».
+ Старые ключи `allow→1, always→2, deny→3` в первом меню «Запретить» превращали в «Yes + auto mode», а во втором
+ «Всегда» превращали в auto mode (вживую: сессия ушла в «⏵⏵ auto mode on» и перестала спрашивать вообще).
+ Решение: `permissionKey(screen, answer)` читает номер с экрана (последний «Do you want to…»), «Всегда» без
+ пункта always = «Yes», «Запретить» без «No» = Escape. Никогда не жмём угаданный номер.
+2. **«No» прерывает ход** («Interrupted · What should Claude do instead?»), Stop-хук не срабатывает, агент молча ждёт.
+ Решение: после «Запретить» в терминале Пеппа печатает `PERMISSION_DENIED_NOTE` («PM запретил это действие. Продолжай
+ без него…»), проверено вживую: агент ответил и продолжил.
+3. **statusLine `context_window.total_input_tokens/total_output_tokens` — последний запрос**, не сумма за сессию
+ (48835 = input+cache текущего запроса; так и в документации /statusline). Пеппа клала их в `tokensByGen` и до
+ первого Stop показывала «45 тыс. токенов» — размер контекста. Решение: `parseStatusLine` их больше не читает,
+ токены — только из transcript.
+4. **MCP `peppa` спрашивает разрешение**, если в репо нет `.claude/settings.json` шаблона (подключённый существующий
+ репо). Решение: `permissions.allow: ["mcp__peppa"]` в сгенерированных `--settings`.
+5. Мок: меню из 4 пунктов как у живого CLI, «No»/Escape прерывает ход без Stop, статуслайн без `hook_event_name` и с
+ `total_*_tokens` последнего запроса, transcript по записи на блок, `permission_suggestions` = `addDirectories`
+ (`destination: session`), у AskUserQuestion `tool_use_id` и `description` вариантов, StopFailure
+ `last_assistant_message` = текст ошибки API.
+
+Новые поля payload'ов, которые Пеппа пока не использует: `prompt_id`, `permission_mode`, `effort.level`,
+`scratchpad_dir`, `model` в SessionStart, `background_tasks`/`session_crons` в Stop, `mcp_server` в PermissionRequest
+для MCP, `prompt_cache`/`exceeds_200k_tokens` в statusLine.
+
+## Что не проверено вживую
+
+- **StopFailure / лимит.** Вызвать нельзя. По документации хуков: срабатывает вместо Stop, когда ход оборвался
+ ошибкой API; поля `error` (обязательное: `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`,
+ `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`,
+ `cloud_credential_error`, `unknown`), `error_details` (необязательное), `last_assistant_message` (текст ошибки API,
+ например «API Error: Rate limit reached»); вывод и код выхода игнорируются. Наш хук совместим: `rate_limit` →
+ `recordLimit(error_details ?? last_assistant_message)`. **Точный текст `error_details` при лимите подписки и
+ реальный баннер лимита в TUI не сняты** — без времени сброса `recordLimit` переходит на пробу 30→60→120 мин.
+ Снять при первом настоящем лимите: `PEPPA_HOOK_CAPTURE_DIR` на живой системе.
+- Баннер порога «N% of your … limit» (PEP-39) живьём не видели; окна `rate_limits` в statusLine (`used_percentage`,
+ `resets_at` в секундах) есть и разбираются, их можно использовать как надёжный источник порога.
+- `/clear` и `/resume` внутри живого процесса (SessionStart с `source: clear|resume`) — не прогоняли.
+- Codex/OpenCode — вне этой стори.
+
+Замечено, но не наше: zsh пользователя на машине спрашивает «compinit: insecure directories…» в снимке шелла Claude,
+и строка попадает в поле ввода TUI; на ход не повлияло.
diff --git a/openspec/changes/archive/2026-11-14-pep-3-live-claude/proposal.md b/openspec/changes/archive/2026-11-14-pep-3-live-claude/proposal.md
new file mode 100644
index 00000000..5cf71feb
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-3-live-claude/proposal.md
@@ -0,0 +1,27 @@
+## Why
+
+Хуки, statusLine и терминальный откат Пеппы написаны и проверены только против `mock-claude`.
+Контракт настоящего Claude Code (2.1.x) — поля payload'ов хуков, формат statusLine, клавиши
+диалога разрешений, bracketed paste — ни разу не сверялся. Ошибка здесь ломает всю фабрику
+молча: вопросы не доходят PM, автопродолжение не срабатывает, расход не считается.
+
+## What Changes
+
+- Прогон настоящей сессии `claude` через раннер Пеппы на dev-стенде (`PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`):
+ PermissionRequest и AskUserQuestion через Telegram-мок, откат на диалог в терминале,
+ Stop с `decision: block`, SessionEnd, правила из `--append-system-prompt-file`, statusLine.
+- `peppa-hook` умеет сохранять сырые payload'ы (`PEPPA_HOOK_CAPTURE_DIR`) — так их и сняли.
+- Реальные payload'ы — фикстуры `packages/testkit/fixtures/claude-live/*.json`.
+- Расхождения кода и `mock-claude` с настоящим контрактом исправлены; e2e на моках там, где
+ нашлось расхождение.
+- Что вживую проверить не удалось (StopFailure/лимиты) — описано в design.md.
+
+## Capabilities
+
+### Modified Capabilities
+- `agent-hooks`: запись сырых payload'ов хуков для сверки с живым CLI.
+
+## Impact
+
+`packages/runner/src/hook.ts`, `packages/testkit/src/mock-agent.ts`, `packages/core/src/usage.ts`,
+фикстуры и e2e в `packages/testkit`.
diff --git a/openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/agent-hooks/spec.md b/openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/agent-hooks/spec.md
new file mode 100644
index 00000000..65fb4435
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/agent-hooks/spec.md
@@ -0,0 +1,18 @@
+## ADDED Requirements
+
+### Requirement: Запись сырых payload'ов хуков
+Если задан `PEPPA_HOOK_CAPTURE_DIR`, `peppa-hook` SHALL сохранять каждый полученный payload (хуки и statusLine) как есть в файл `<каталог>/<время>-<событие>.json` до обработки; ошибка записи MUST NOT ломать хук.
+
+#### Scenario: Сверка с живым Claude Code
+- **GIVEN** раннер запущен с `PEPPA_HOOK_CAPTURE_DIR=/tmp/cap`
+- **WHEN** Claude вызывает хук `Stop`
+- **THEN** в `/tmp/cap` появляется файл `…-stop.json` с payload'ом Claude без изменений
+- **AND** хук отрабатывает как обычно
+
+### Requirement: Peppa MCP без разрешений
+Сгенерированный файл настроек запуска Claude SHALL разрешать инструменты MCP-сервера `peppa` (`permissions.allow: ["mcp__peppa"]`), чтобы вызовы Пеппы не превращались в вопросы PM и в репозиториях без `.claude/settings.json` шаблона.
+
+#### Scenario: Подключённый существующий репозиторий
+- **GIVEN** в репозитории проекта нет `.claude/settings.json`
+- **WHEN** агент вызывает `peppa.get_task`
+- **THEN** Claude не спрашивает разрешения и PM не получает вопрос `permission`
diff --git a/openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/runner-sessions/spec.md b/openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/runner-sessions/spec.md
new file mode 100644
index 00000000..c11ddcba
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-3-live-claude/specs/runner-sessions/spec.md
@@ -0,0 +1,38 @@
+## MODIFIED Requirements
+
+### Requirement: Доставка ответа PM в сессию
+Ответ PM SHALL сохраняться, сбрасывать счётчик автопродолжений и доставляться агенту по виду вопроса: `permission` — пункт меню Claude, номер которого читается с экрана (allow → «Yes», always → «Yes, and always allow… / don't ask again…», а без такого пункта — «Yes», deny → последний «No», без него — Escape), после deny агенту печатается «PM запретил это действие…» (живой Claude прерывает ход на «No» без Stop-хука); `approval` — смена статуса стори и сообщение; `question` — «Ответ PM на вопрос #N: …»; иначе — текст. Вопрос, который держит хук, отдаёт агенту хук. Ответ на вопрос стори без сессии уходит в живую сессию стори. Особые ответы (релиз, простой) MUST NOT попадать в терминал.
+
+#### Scenario Outline: Одобрение proposal
+- **GIVEN** стори `PEP-42` в `awaiting_approval`, агент ждёт в сессии #7
+- **WHEN** PM отвечает «<ответ>»
+- **THEN** стори получает статус «<статус>»
+- **AND** агент получает сообщение «<сообщение>»
+
+| ответ | статус | сообщение |
+|---|---|---|
+| ок | in_progress | PM одобрил proposal PEP-42. Статус in_progress — переходи к Apply. |
+| да, но без кэша | in_progress | PM одобрил proposal PEP-42 … Комментарий PM: да, но без кэша |
+| нет, разбей на две стори | proposing | PM не одобрил proposal PEP-42. Доработай proposal по комментарию … |
+
+#### Scenario: Разрешение из Telegram
+- **GIVEN** Claude показывает диалог разрешения, хук уже отпустил вопрос в терминал
+- **AND** меню «1. Yes / 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode / 4. No»
+- **WHEN** PM нажимает «♾ Всегда»
+- **THEN** в pane нажата клавиша `2`
+
+#### Scenario: Запрет из Telegram в меню без пункта auto mode
+- **GIVEN** хук отпустил вопрос в терминал, меню «1. Yes / 2. Yes, and don't ask again… / 3. No»
+- **WHEN** PM нажимает «⛔ Запретить»
+- **THEN** в pane нажата клавиша `3`
+- **AND** агенту напечатано «PM запретил это действие. Продолжай без него…»
+
+#### Scenario: «Всегда» без пункта «always»
+- **GIVEN** меню «1. Yes / 2. Yes, and switch to auto mode / 3. No»
+- **WHEN** PM нажимает «♾ Всегда»
+- **THEN** в pane нажата клавиша `1`, сессия не переходит в auto mode
+
+#### Scenario: Сессия не запущена
+- **GIVEN** вопрос #12 сессии #7, tmux-сессии нет
+- **WHEN** PM отвечает
+- **THEN** ответ сохранён, PM видит «Ответ сохранён, но сессия сейчас не запущена»
diff --git a/openspec/changes/archive/2026-11-14-pep-3-live-claude/tasks.md b/openspec/changes/archive/2026-11-14-pep-3-live-claude/tasks.md
new file mode 100644
index 00000000..d0d6237b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-3-live-claude/tasks.md
@@ -0,0 +1,15 @@
+## 1. Снять контракт
+- [x] 1.1 `PEPPA_HOOK_CAPTURE_DIR` в peppa-hook: сырые payload'ы событий и statusLine
+- [x] 1.2 Живой прогон на dev-стенде: PermissionRequest, AskUserQuestion, откат в терминал, Stop/nudge, SessionEnd, правила, statusLine
+- [x] 1.3 Фикстуры `packages/testkit/fixtures/claude-live/`
+
+## 2. Сверить и исправить
+- [x] 2.1 Сверить payload'ы хуков с `HookInput` и mock-claude
+- [x] 2.2 Сверить statusLine с `parseStatusLine`, transcript с `transcriptUsage`
+- [x] 2.3 Сверить клавиши диалога разрешений и bracketed paste
+- [x] 2.4 StopFailure — по документации, описать непроверенное
+- [x] 2.5 Исправить расхождения в коде и моке
+
+## 3. Тесты
+- [x] 3.1 e2e на моках по найденным расхождениям (и разбор фикстур)
+- [x] 3.2 `pnpm run ci`
diff --git a/openspec/specs/agent-hooks/spec.md b/openspec/specs/agent-hooks/spec.md
index 2b376336..87ee01ff 100644
--- a/openspec/specs/agent-hooks/spec.md
+++ b/openspec/specs/agent-hooks/spec.md
@@ -142,3 +142,20 @@
- **GIVEN** сессия #7 `running`
- **WHEN** человек делает `/resume` и срабатывает `SessionEnd`
- **THEN** сессия остаётся `running`
+
+### Requirement: Запись сырых payload'ов хуков
+Если задан `PEPPA_HOOK_CAPTURE_DIR`, `peppa-hook` SHALL сохранять каждый полученный payload (хуки и statusLine) как есть в файл `<каталог>/<время>-<событие>.json` до обработки; ошибка записи MUST NOT ломать хук.
+
+#### Scenario: Сверка с живым Claude Code
+- **GIVEN** раннер запущен с `PEPPA_HOOK_CAPTURE_DIR=/tmp/cap`
+- **WHEN** Claude вызывает хук `Stop`
+- **THEN** в `/tmp/cap` появляется файл `…-stop.json` с payload'ом Claude без изменений
+- **AND** хук отрабатывает как обычно
+
+### Requirement: Peppa MCP без разрешений
+Сгенерированный файл настроек запуска Claude SHALL разрешать инструменты MCP-сервера `peppa` (`permissions.allow: ["mcp__peppa"]`), чтобы вызовы Пеппы не превращались в вопросы PM и в репозиториях без `.claude/settings.json` шаблона.
+
+#### Scenario: Подключённый существующий репозиторий
+- **GIVEN** в репозитории проекта нет `.claude/settings.json`
+- **WHEN** агент вызывает `peppa.get_task`
+- **THEN** Claude не спрашивает разрешения и PM не получает вопрос `permission`
diff --git a/openspec/specs/runner-sessions/spec.md b/openspec/specs/runner-sessions/spec.md
index 972fbf14..31d9ab33 100644
--- a/openspec/specs/runner-sessions/spec.md
+++ b/openspec/specs/runner-sessions/spec.md
@@ -85,7 +85,7 @@
- **THEN** ошибка «is not running»
### Requirement: Доставка ответа PM в сессию
-Ответ PM SHALL сохраняться, сбрасывать счётчик автопродолжений и доставляться агенту по виду вопроса: `permission` — пункт меню Claude (allow → 1, always → 2, deny → 3); `approval` — смена статуса стори и сообщение; `question` — «Ответ PM на вопрос #N: …»; иначе — текст. Вопрос, который держит хук, отдаёт агенту хук. Ответ на вопрос стори без сессии уходит в живую сессию стори. Особые ответы (релиз, простой) MUST NOT попадать в терминал.
+Ответ PM SHALL сохраняться, сбрасывать счётчик автопродолжений и доставляться агенту по виду вопроса: `permission` — пункт меню Claude, номер которого читается с экрана (allow → «Yes», always → «Yes, and always allow… / don't ask again…», а без такого пункта — «Yes», deny → последний «No», без него — Escape), после deny агенту печатается «PM запретил это действие…» (живой Claude прерывает ход на «No» без Stop-хука); `approval` — смена статуса стори и сообщение; `question` — «Ответ PM на вопрос #N: …»; иначе — текст. Вопрос, который держит хук, отдаёт агенту хук. Ответ на вопрос стори без сессии уходит в живую сессию стори. Особые ответы (релиз, простой) MUST NOT попадать в терминал.
#### Scenario Outline: Одобрение proposal
- **GIVEN** стори `PEP-42` в `awaiting_approval`, агент ждёт в сессии #7
@@ -101,9 +101,21 @@
#### Scenario: Разрешение из Telegram
- **GIVEN** Claude показывает диалог разрешения, хук уже отпустил вопрос в терминал
+- **AND** меню «1. Yes / 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode / 4. No»
- **WHEN** PM нажимает «♾ Всегда»
- **THEN** в pane нажата клавиша `2`
+#### Scenario: Запрет из Telegram в меню без пункта auto mode
+- **GIVEN** хук отпустил вопрос в терминал, меню «1. Yes / 2. Yes, and don't ask again… / 3. No»
+- **WHEN** PM нажимает «⛔ Запретить»
+- **THEN** в pane нажата клавиша `3`
+- **AND** агенту напечатано «PM запретил это действие. Продолжай без него…»
+
+#### Scenario: «Всегда» без пункта «always»
+- **GIVEN** меню «1. Yes / 2. Yes, and switch to auto mode / 3. No»
+- **WHEN** PM нажимает «♾ Всегда»
+- **THEN** в pane нажата клавиша `1`, сессия не переходит в auto mode
+
#### Scenario: Сессия не запущена
- **GIVEN** вопрос #12 сессии #7, tmux-сессии нет
- **WHEN** PM отвечает
diff --git a/packages/core/src/usage.ts b/packages/core/src/usage.ts
index dccb692a..ace11d2a 100644
--- a/packages/core/src/usage.ts
+++ b/packages/core/src/usage.ts
@@ -57,7 +57,10 @@ function parseWindow(v: unknown): UsageWindow | undefined {
return { pct: Math.max(0, Math.min(100, Math.round(pct * 10) / 10)), resetsAt: toMs(o.resets_at ?? o.resetsAt ?? o.reset_at ?? o.resets) };
}
-/** Claude Code statusLine JSON → what Peppa keeps. Tolerant to field name variants (not verified on a live CLI). */
+/**
+ * Claude Code statusLine JSON → what Peppa keeps. Checked against live 2.1.323 (PEP-3, fixture
+ * `packages/testkit/fixtures/claude-live/statusline.json`); still tolerant to field name variants.
+ */
export function parseStatusLine(input: unknown): StatusLineData {
const j = obj(input) ?? {};
const cost = obj(j.cost);
@@ -72,9 +75,8 @@ export function parseStatusLine(input: unknown): StatusLineData {
const used = cur ? (num(cur.input_tokens) ?? 0) + (num(cur.cache_read_input_tokens) ?? 0) + (num(cur.cache_creation_input_tokens) ?? 0) : num(cw.used_tokens);
const pct = num(cw.used_percentage) ?? (used != null && size ? (used / size) * 100 : undefined);
if (size && (used != null || pct != null)) out.context = { used: used ?? Math.round(((pct ?? 0) / 100) * size), size, pct: Math.round((pct ?? 0) * 10) / 10 };
- const ti = num(cw.total_input_tokens);
- const to = num(cw.total_output_tokens);
- if (ti != null || to != null) out.tokens = { input: ti ?? 0, output: to ?? 0 };
+ // PEP-3 (live 2.1.323): `total_input_tokens` / `total_output_tokens` are the LAST request
+ // (= current_usage input+cache / output), not session totals — tokens come from the transcript.
}
if (rl) {
const five = parseWindow(rl.five_hour ?? rl.fiveHour ?? rl["5h"] ?? rl.session);
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index dcedb647..49b30682 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -3,7 +3,7 @@
// PEPPA_SESSION_ID / PEPPA_GENERATION point to. Must never break the Claude session:
// always exits 0, errors go to ~/.peppa/hook.log, and blocking hooks fall back to
// Claude's own terminal dialog when the PM doesn't answer in time.
-import { appendFileSync, readFileSync } from "node:fs";
+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
answerQuestion,
@@ -395,6 +395,15 @@ if (event !== "codex-notify") {
raw = readFileSync(0, "utf8");
} catch {}
}
+// PEP-3: raw payloads as the CLI sent them, for checking the contract against a live Claude Code.
+if (process.env.PEPPA_HOOK_CAPTURE_DIR && raw) {
+ try {
+ mkdirSync(process.env.PEPPA_HOOK_CAPTURE_DIR, { recursive: true });
+ writeFileSync(join(process.env.PEPPA_HOOK_CAPTURE_DIR, `${Date.now()}-${process.pid}-${event}.json`), raw);
+ } catch (e) {
+ log(`capture ${event}: ${(e as Error).message}`);
+ }
+}
// PEP-48: hooks act as the session's agent (answers typed into the terminal are a person's).
setDefaultActor({ kind: "agent", channel: "hook" });
try {
diff --git a/packages/runner/src/run-settings.ts b/packages/runner/src/run-settings.ts
index 89ee8fe6..3830e2e7 100644
--- a/packages/runner/src/run-settings.ts
+++ b/packages/runner/src/run-settings.ts
@@ -38,6 +38,9 @@ export function writeRunSettings(sessionId: number, generation: number, bin: str
const settings = {
// PEP-5: Claude reports cost, context and the 5h/7d limit windows to the status line command.
statusLine: { type: "command", command: `${bin} statusline`, padding: 0 },
+ // PEP-3: Peppa's own MCP tools never need the PM (the template allows them too, but a
+ // connected existing repo has no .claude/settings.json); status guards live in the server.
+ permissions: { allow: ["mcp__peppa"] },
hooks: {
SessionStart: [{ hooks: [hook("session-start")] }],
UserPromptSubmit: [{ hooks: [hook("prompt")] }],
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 9731788b..69457cc3 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -330,6 +330,7 @@ async function launch(
// The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
...(sub ? subscriptionEnv(sub) : {}),
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
+ ...(process.env.PEPPA_HOOK_CAPTURE_DIR ? { PEPPA_HOOK_CAPTURE_DIR: process.env.PEPPA_HOOK_CAPTURE_DIR } : {}),
};
script = `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`;
}
@@ -396,8 +397,30 @@ export function onAnswer(h: AnswerHandler) {
}
const APPROVE_RE = /^\s*(ok|ок|да|yes|approve|approved|одобр|lgtm|go|погнали|делай)/i;
-// Claude Code permission prompt: 1 = yes, 2 = yes and don't ask again, 3 = no.
-const PERMISSION_KEYS: Record = { allow: "1", always: "2", deny: "3" };
+/**
+ * The key for the PM's answer in Claude Code's permission dialog. The menu differs by tool,
+ * by what is already allowed and by version — seen live on 2.1.323 (PEP-3): «1. Yes /
+ * 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode … / 4. No», but also
+ * «1. Yes / 2. Yes, and switch to auto mode / 3. No» and «1. Yes / 2. Yes, and always allow … /
+ * 3. No». So the number is read off the screen; a fixed "2" could switch the session to auto
+ * mode and a fixed "3" could allow instead of deny. "always" without such a line = "Yes";
+ * "deny" without a "No" line = Escape (cancels the call).
+ */
+export function permissionKey(screen: string, answer: string): string | null {
+ const a = answer.trim().toLowerCase();
+ if (!["allow", "always", "deny"].includes(a)) return null;
+ // The dialog is the last menu on the screen: only look below its question.
+ const at = screen.lastIndexOf("Do you want to");
+ const lines = (at >= 0 ? screen.slice(at) : "").split("\n");
+ const opts = lines.map((l) => /^\s*(?:❯\s*)?(\d)\.\s+(.*)$/.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ key: m[1]!, text: m[2]!.trim() }));
+ const yes = opts.find((o) => /^Yes\s*$/i.test(o.text))?.key ?? "1";
+ if (a === "allow") return yes;
+ if (a === "always") return opts.find((o) => /^Yes, and (always|don't ask|do not ask)/i.test(o.text))?.key ?? yes;
+ return [...opts].reverse().find((o) => /^No\b/i.test(o.text))?.key ?? "Escape";
+}
+
+/** Typed after "No" in the dialog: Claude interrupts the turn there and waits silently (PEP-3). */
+export const PERMISSION_DENIED_NOTE = "PM запретил это действие. Продолжай без него, а если без него никак — ask_pm и закончи ход.";
/**
* Records the PM's answer and delivers it into the session's terminal:
@@ -458,9 +481,16 @@ export async function answerAndDeliver(
if (!(await tmux.hasSession(tmux.sessionPane(s)))) return { delivered: false, question: q };
if (q.kind === "permission") {
- const key = PERMISSION_KEYS[answer.trim().toLowerCase()];
- if (key) await tmux.sendKeys(tmux.sessionPane(s), key);
- else await tmux.sendText(tmux.sessionPane(s), answer);
+ const key = permissionKey(await tmux.capturePane(tmux.sessionPane(s)).catch(() => ""), answer);
+ if (key) {
+ await tmux.sendKeys(tmux.sessionPane(s), key);
+ if (answer.trim().toLowerCase() === "deny") {
+ // The interrupted turn leaves an empty prompt; give the TUI a moment to draw it.
+ await new Promise((r) => setTimeout(r, Number(process.env.PEPPA_DENY_NOTE_DELAY_MS ?? 1500)));
+ await logSessionEvent(db, s, "input_sent", { text: PERMISSION_DENIED_NOTE });
+ await tmux.sendText(tmux.sessionPane(s), PERMISSION_DENIED_NOTE);
+ }
+ } else await tmux.sendText(tmux.sessionPane(s), answer);
} else {
await tmux.sendText(tmux.sessionPane(s), message);
}
diff --git a/packages/testkit/bin/peppa-dev b/packages/testkit/bin/peppa-dev
index 44fa9f3b..634fa31d 100755
--- a/packages/testkit/bin/peppa-dev
+++ b/packages/testkit/bin/peppa-dev
@@ -21,6 +21,8 @@ export PEPPA_CLAUDE_BIN="${PEPPA_DEV_CLAUDE_BIN:-$ROOT/packages/testkit/bin/mock
export PEPPA_CODEX_BIN="${PEPPA_DEV_CODEX_BIN:-$ROOT/packages/testkit/bin/mock-codex}"
export PEPPA_HOOK_WAIT_SEC="${PEPPA_HOOK_WAIT_SEC:-30}"
export PEPPA_WEB_URL="http://peppa-dev.local"
+# A worktree has no .env: the stand still needs a key for its own encrypted columns.
+[ -n "${PEPPA_SECRET:-}" ] || grep -q '^PEPPA_SECRET=' "$ROOT/.env" 2>/dev/null || export PEPPA_SECRET="mock-dev-stand-secret"
mkdir -p "$PEPPA_HOME" "$PEPPA_WORKSPACES"
TM=(tmux -L peppa-dev)
PEPPA="$ROOT/packages/cli/bin/peppa"
@@ -30,6 +32,9 @@ up() {
"${TM[@]}" has-session -t dev-mock-tg 2>/dev/null || "${TM[@]}" new-session -d -s dev-mock-tg "$ROOT/packages/testkit/bin/mock-telegram --port $PORT"
"${TM[@]}" set-option -s exit-empty off
for _ in $(seq 1 40); do curl -sf "$TELEGRAM_API_URL/_mock/messages" >/dev/null && break; sleep 0.25; done
+ # PEP-21: the watchdog is the runner service — the bot hands it answers and «В работу».
+ "${TM[@]}" has-session -t dev-watchdog 2>/dev/null || "${TM[@]}" new-session -d -s dev-watchdog "$PEPPA watchdog"
+ for _ in $(seq 1 40); do [ -S "$PEPPA_HOME/runner.sock" ] && break; sleep 0.25; done
"${TM[@]}" has-session -t dev-bot 2>/dev/null || "${TM[@]}" new-session -d -s dev-bot "$ROOT/apps/bot/bin/peppa-bot"
for _ in $(seq 1 40); do "$PEPPA" telegram status 2>/dev/null | grep -q '^bot: @' && break; sleep 0.25; done
"$PEPPA" user ensure mock-pm >/dev/null
diff --git a/packages/testkit/fixtures/claude-live/notification-permission-prompt.json b/packages/testkit/fixtures/claude-live/notification-permission-prompt.json
new file mode 100644
index 00000000..638256de
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/notification-permission-prompt.json
@@ -0,0 +1,10 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
+ "hook_event_name": "Notification",
+ "message": "Claude needs your permission",
+ "notification_type": "permission_prompt"
+}
diff --git a/packages/testkit/fixtures/claude-live/permission-request-mcp.json b/packages/testkit/fixtures/claude-live/permission-request-mcp.json
new file mode 100644
index 00000000..c07ac429
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/permission-request-mcp.json
@@ -0,0 +1,32 @@
+{
+ "session_id": "a8a23fed-636e-4685-963c-56dd326f5821",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821/scratchpad",
+ "prompt_id": "f4a78a56-3378-45be-ac8a-75eebfc321bd",
+ "permission_mode": "default",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "PermissionRequest",
+ "tool_name": "mcp__peppa__get_task",
+ "tool_input": {
+ "task": "LIVE-1"
+ },
+ "permission_suggestions": [
+ {
+ "type": "addRules",
+ "rules": [
+ {
+ "toolName": "mcp__peppa__get_task"
+ }
+ ],
+ "behavior": "allow",
+ "destination": "localSettings"
+ }
+ ],
+ "mcp_server": {
+ "name": "peppa",
+ "source": "project"
+ }
+}
diff --git a/packages/testkit/fixtures/claude-live/permission-request.json b/packages/testkit/fixtures/claude-live/permission-request.json
new file mode 100644
index 00000000..ad1e0c64
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/permission-request.json
@@ -0,0 +1,26 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
+ "permission_mode": "default",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "PermissionRequest",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "touch two.txt",
+ "description": "Create two.txt in the working directory"
+ },
+ "permission_suggestions": [
+ {
+ "type": "addDirectories",
+ "directories": [
+ "/Users/mock/.peppa-dev/workspaces/live"
+ ],
+ "destination": "session"
+ }
+ ]
+}
diff --git a/packages/testkit/fixtures/claude-live/post-tool-use-failure.json b/packages/testkit/fixtures/claude-live/post-tool-use-failure.json
new file mode 100644
index 00000000..3e508d60
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/post-tool-use-failure.json
@@ -0,0 +1,21 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
+ "permission_mode": "auto",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "PostToolUseFailure",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "ls /nonexistent-peppa",
+ "description": "List a nonexistent directory to check error handling"
+ },
+ "tool_use_id": "toolu_01RWJyz6BUXwPcU2j2znFmq5",
+ "error": "Exit code 1\nls: /nonexistent-peppa: No such file or directory",
+ "is_interrupt": false,
+ "duration_ms": 10081
+}
diff --git a/packages/testkit/fixtures/claude-live/post-tool-use.json b/packages/testkit/fixtures/claude-live/post-tool-use.json
new file mode 100644
index 00000000..cd5d1505
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/post-tool-use.json
@@ -0,0 +1,26 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
+ "permission_mode": "auto",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "touch two.txt",
+ "description": "Create two.txt in the working directory"
+ },
+ "tool_response": {
+ "stdout": "",
+ "stderr": "",
+ "interrupted": false,
+ "isImage": false,
+ "noOutputExpected": true
+ },
+ "tool_use_id": "toolu_015ZHJezTdAPV733czTubGD5",
+ "duration_ms": 82
+}
diff --git a/packages/testkit/fixtures/claude-live/pre-tool-use-ask-user-question.json b/packages/testkit/fixtures/claude-live/pre-tool-use-ask-user-question.json
new file mode 100644
index 00000000..710c7d22
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/pre-tool-use-ask-user-question.json
@@ -0,0 +1,33 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "2566d5ad-f4dc-489b-8aa6-8ff1730a023c",
+ "permission_mode": "default",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "PreToolUse",
+ "tool_name": "AskUserQuestion",
+ "tool_input": {
+ "questions": [
+ {
+ "question": "Какой язык?",
+ "header": "Язык",
+ "options": [
+ {
+ "label": "Go",
+ "description": "Язык Go"
+ },
+ {
+ "label": "Rust",
+ "description": "Язык Rust"
+ }
+ ],
+ "multiSelect": false
+ }
+ ]
+ },
+ "tool_use_id": "toolu_01TCVWSwtMREECGQ6o93NCnV"
+}
diff --git a/packages/testkit/fixtures/claude-live/session-end.json b/packages/testkit/fixtures/claude-live/session-end.json
new file mode 100644
index 00000000..078b97c1
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/session-end.json
@@ -0,0 +1,9 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "6c2c2439-2d58-4662-8dac-35c50dad63b6",
+ "hook_event_name": "SessionEnd",
+ "reason": "prompt_input_exit"
+}
diff --git a/packages/testkit/fixtures/claude-live/session-start.json b/packages/testkit/fixtures/claude-live/session-start.json
new file mode 100644
index 00000000..ead867fd
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/session-start.json
@@ -0,0 +1,9 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "hook_event_name": "SessionStart",
+ "source": "startup",
+ "model": "claude-haiku-5-5"
+}
diff --git a/packages/testkit/fixtures/claude-live/statusline-first.json b/packages/testkit/fixtures/claude-live/statusline-first.json
new file mode 100644
index 00000000..2e6109d3
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/statusline-first.json
@@ -0,0 +1,42 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "effort": {
+ "level": "medium"
+ },
+ "model": {
+ "id": "claude-haiku-5-5",
+ "display_name": "Haiku 5.5"
+ },
+ "workspace": {
+ "current_dir": "/Users/mock/.peppa-dev/workspaces/live",
+ "project_dir": "/Users/mock/.peppa-dev/workspaces/live",
+ "added_dirs": []
+ },
+ "version": "2.1.323",
+ "output_style": {
+ "name": "default"
+ },
+ "cost": {
+ "total_cost_usd": 0,
+ "total_duration_ms": 359,
+ "total_api_duration_ms": 0,
+ "total_lines_added": 0,
+ "total_lines_removed": 0
+ },
+ "context_window": {
+ "total_input_tokens": 0,
+ "total_output_tokens": 0,
+ "context_window_size": 1000000,
+ "current_usage": null,
+ "used_percentage": null,
+ "remaining_percentage": null
+ },
+ "exceeds_200k_tokens": false,
+ "fast_mode": false,
+ "thinking": {
+ "enabled": true
+ }
+}
diff --git a/packages/testkit/fixtures/claude-live/statusline.json b/packages/testkit/fixtures/claude-live/statusline.json
new file mode 100644
index 00000000..bb39faf5
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/statusline.json
@@ -0,0 +1,74 @@
+{
+ "session_id": "a8a23fed-636e-4685-963c-56dd326f5821",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821/scratchpad",
+ "prompt_id": "f4a78a56-3378-45be-ac8a-75eebfc321bd",
+ "effort": {
+ "level": "medium"
+ },
+ "model": {
+ "id": "claude-haiku-5-5",
+ "display_name": "Haiku 5.5"
+ },
+ "workspace": {
+ "current_dir": "/Users/mock/.peppa-dev/workspaces/live",
+ "project_dir": "/Users/mock/.peppa-dev/workspaces/live",
+ "added_dirs": []
+ },
+ "version": "2.1.323",
+ "output_style": {
+ "name": "default"
+ },
+ "cost": {
+ "total_cost_usd": 0.00725025,
+ "total_duration_ms": 111292,
+ "total_api_duration_ms": 12591,
+ "total_lines_added": 0,
+ "total_lines_removed": 0
+ },
+ "context_window": {
+ "total_input_tokens": 51302,
+ "total_output_tokens": 2,
+ "context_window_size": 1000000,
+ "current_usage": {
+ "input_tokens": 2,
+ "output_tokens": 2,
+ "cache_creation_input_tokens": 390,
+ "cache_read_input_tokens": 50910
+ },
+ "used_percentage": 5,
+ "remaining_percentage": 95
+ },
+ "exceeds_200k_tokens": false,
+ "prompt_cache": {
+ "warm": true,
+ "caching_observed": true,
+ "ttl": "1h",
+ "expires_at": 1794644343,
+ "requests": 5,
+ "misses": 0,
+ "expected_rebuilds": 0,
+ "hit_ratio": 0.9223495643259867,
+ "cache_write_tokens": 18927,
+ "miss_recache_tokens": 0,
+ "last_miss_at": null,
+ "last_miss_cause": null,
+ "miss_causes": {},
+ "recache_tokens_if_cold": 50912
+ },
+ "fast_mode": false,
+ "thinking": {
+ "enabled": true
+ },
+ "rate_limits": {
+ "five_hour": {
+ "used_percentage": 4,
+ "resets_at": 1794648000
+ },
+ "seven_day": {
+ "used_percentage": 14,
+ "resets_at": 1795107600
+ }
+ }
+}
diff --git a/packages/testkit/fixtures/claude-live/stop-after-block.json b/packages/testkit/fixtures/claude-live/stop-after-block.json
new file mode 100644
index 00000000..bfc1060d
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/stop-after-block.json
@@ -0,0 +1,16 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "c33d7529-95bd-4b45-946b-56264cfc5c1c",
+ "permission_mode": "auto",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "Stop",
+ "stop_hook_active": true,
+ "last_assistant_message": "Не буду продолжать LIVE-1 по этому хуку. В начале вы написали, что это тест хуков Пеппы, не настоящая работа, и просили не вызывать MCP `peppa` и не трогать OpenSpec. Хук требует именно этого: `ask_pm`, `update_task(status: review)`, PR. Это внешние действия, поэтому без вашего подтверждения их не делаю.\n\nЧто сделано в тесте: `touch four.txt` и `touch five.txt` выполнены последовательно, файлы созданы в рабочем каталоге.\n\nЕсли LIVE-1 нужно довести до настоящего PR, напишите, и я сделаю это по `tasks.md` и правилам Пеппы. Если тест завершён, ничего больше делать не нужно. В этом случае хук можно отключить или поправить на стороне Пеппы, так как он требует реальной работы, которую вы не заказывали.",
+ "background_tasks": [],
+ "session_crons": []
+}
diff --git a/packages/testkit/fixtures/claude-live/stop.json b/packages/testkit/fixtures/claude-live/stop.json
new file mode 100644
index 00000000..2eaf6b58
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/stop.json
@@ -0,0 +1,16 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "2566d5ad-f4dc-489b-8aa6-8ff1730a023c",
+ "permission_mode": "default",
+ "effort": {
+ "level": "medium"
+ },
+ "hook_event_name": "Stop",
+ "stop_hook_active": false,
+ "last_assistant_message": "Вопрос «Какой язык?» (Go / Rust) не прошёл: хук Пеппы переслал его PM (#5). Ход закончен, шаги 2–5 (два `ls`/`touch` и итоговая строка) выполню после ответа.",
+ "background_tasks": [],
+ "session_crons": []
+}
diff --git a/packages/testkit/fixtures/claude-live/transcript.jsonl b/packages/testkit/fixtures/claude-live/transcript.jsonl
new file mode 100644
index 00000000..8873ed06
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/transcript.jsonl
@@ -0,0 +1,27 @@
+{"type": "user", "uuid": "697335fb-029b-4998-8d2d-997bfcf1a5e1", "parentUuid": null, "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:06:46.899Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "a1de7d53-4516-4df7-a26e-970daa23999e", "parentUuid": "6c496664-b2fb-40ef-a8c0-0ea571f00fac", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:06:48.896Z", "requestId": "req_011Ch2Q24xuPkankc3LBjUNp", "message": {"id": "msg_011Ch2Q25AJRyZVA8qwBVqme", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 12770, "cache_read_input_tokens": 31983, "output_tokens": 194, "output_tokens_details": {"thinking_tokens": 63}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 12770, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 194, "cache_read_input_tokens": 31983, "cache_creation_input_tokens": 12770, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 12770}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "101937b3-9a2e-4a6e-833c-1d34310f2baa", "parentUuid": "a1de7d53-4516-4df7-a26e-970daa23999e", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:06:49.263Z", "requestId": "req_011Ch2Q24xuPkankc3LBjUNp", "message": {"id": "msg_011Ch2Q25AJRyZVA8qwBVqme", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "AskUserQuestion", "id": "toolu_01TCVWSwtMREECGQ6o93NCnV", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 12770, "cache_read_input_tokens": 31983, "output_tokens": 194, "output_tokens_details": {"thinking_tokens": 63}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 12770, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 194, "cache_read_input_tokens": 31983, "cache_creation_input_tokens": 12770, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 12770}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "9cca4968-7ef1-4636-ae53-5a484ab51863", "parentUuid": "101937b3-9a2e-4a6e-833c-1d34310f2baa", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:07:34.713Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "97cfc91e-caa9-4c8d-a500-76104c7a9f04", "parentUuid": "ec108f22-b004-4cb2-bf8a-234a1f24b7e4", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:07:36.307Z", "requestId": "req_011Ch2Q5ZVDdRtYB7FpSUg2J", "message": {"id": "msg_011Ch2Q5Zm6JTaimsdDQLQrP", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 3873, "cache_read_input_tokens": 44753, "output_tokens": 164, "output_tokens_details": {"thinking_tokens": 76}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 3873, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 164, "cache_read_input_tokens": 44753, "cache_creation_input_tokens": 3873, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 3873}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "a3724236-f427-4152-955f-bcdc82c9ced5", "parentUuid": "97cfc91e-caa9-4c8d-a500-76104c7a9f04", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:07:36.698Z", "requestId": "req_011Ch2Q5ZVDdRtYB7FpSUg2J", "message": {"id": "msg_011Ch2Q5Zm6JTaimsdDQLQrP", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 3873, "cache_read_input_tokens": 44753, "output_tokens": 164, "output_tokens_details": {"thinking_tokens": 76}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 3873, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 164, "cache_read_input_tokens": 44753, "cache_creation_input_tokens": 3873, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 3873}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "d08997e4-60c7-477a-8405-be2bf7d31c46", "parentUuid": "306b7de8-c0c6-4ba1-89d1-70bcf5217126", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:04.783Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "053219d4-5683-4e0a-adf5-91e9b5d3c104", "parentUuid": "600f4e46-49bc-4dcd-b2a5-19ea3ff4c465", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:07.829Z", "requestId": "req_011Ch2Q7ocqPJU3qfEPHbAr6", "message": {"id": "msg_011Ch2Q7oqUakBseEDos4cYs", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01RWJyz6BUXwPcU2j2znFmq5", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 43, "cache_read_input_tokens": 48790, "output_tokens": 252, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 43, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 252, "cache_read_input_tokens": 48790, "cache_creation_input_tokens": 43, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 43}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "4f77556b-3a2c-4b60-91ec-f3fb1965d8c3", "parentUuid": "053219d4-5683-4e0a-adf5-91e9b5d3c104", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:08.483Z", "requestId": "req_011Ch2Q7ocqPJU3qfEPHbAr6", "message": {"id": "msg_011Ch2Q7oqUakBseEDos4cYs", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_015ZHJezTdAPV733czTubGD5", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 43, "cache_read_input_tokens": 48790, "output_tokens": 252, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 43, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 252, "cache_read_input_tokens": 48790, "cache_creation_input_tokens": 43, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 43}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "1db240ac-330d-4d97-8aad-d2f67e168a6f", "parentUuid": "4f77556b-3a2c-4b60-91ec-f3fb1965d8c3", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:08.489Z", "requestId": "req_011Ch2Q7ocqPJU3qfEPHbAr6", "message": {"id": "msg_011Ch2Q7oqUakBseEDos4cYs", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01RCpdfRJ5Fy1gygPm8kqvrC", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 43, "cache_read_input_tokens": 48790, "output_tokens": 252, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 43, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 252, "cache_read_input_tokens": 48790, "cache_creation_input_tokens": 43, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 43}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "77973920-f1a9-46ce-ac1b-99ed02ab7ff0", "parentUuid": "053219d4-5683-4e0a-adf5-91e9b5d3c104", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:11:46.819Z", "message": {"role": "user", "content": "…"}}
+{"type": "user", "uuid": "f48f0431-868e-43ad-9de9-fd5601502873", "parentUuid": "4f77556b-3a2c-4b60-91ec-f3fb1965d8c3", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:12:00.822Z", "message": {"role": "user", "content": "…"}}
+{"type": "user", "uuid": "f2f65ffb-bd31-43d7-b434-77c683247429", "parentUuid": "1db240ac-330d-4d97-8aad-d2f67e168a6f", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:12:47.129Z", "message": {"role": "user", "content": "…"}}
+{"type": "user", "uuid": "3703fb55-0d62-4e12-b2f1-2c1d7adadeb1", "parentUuid": "f2f65ffb-bd31-43d7-b434-77c683247429", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:12:47.129Z", "message": {"role": "user", "content": "…"}}
+{"type": "user", "uuid": "2d0ac504-43a6-40de-b0f2-1d9be0829dcc", "parentUuid": "e1509482-7971-4f9c-a92b-1915611c2098", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:26.597Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "3fce53fc-e25c-4790-b9d0-b8631c6641a5", "parentUuid": "34c1df3e-3038-44dc-8852-beb9932372c4", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:28.165Z", "requestId": "req_011Ch2QbxYPKwsdMSvWASxpC", "message": {"id": "msg_011Ch2Qby39TeJ5WrPLH8FGv", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 596, "cache_read_input_tokens": 48833, "output_tokens": 124, "output_tokens_details": {"thinking_tokens": 40}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 596, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 124, "cache_read_input_tokens": 48833, "cache_creation_input_tokens": 596, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 596}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "251c79d2-42cb-4318-8bce-2d5a4f7c72d2", "parentUuid": "3fce53fc-e25c-4790-b9d0-b8631c6641a5", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:28.238Z", "requestId": "req_011Ch2QbxYPKwsdMSvWASxpC", "message": {"id": "msg_011Ch2Qby39TeJ5WrPLH8FGv", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01BKmkrAhc1MxrpUeG51ykY8", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 596, "cache_read_input_tokens": 48833, "output_tokens": 124, "output_tokens_details": {"thinking_tokens": 40}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 596, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 124, "cache_read_input_tokens": 48833, "cache_creation_input_tokens": 596, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 596}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "5412ec29-5319-489e-88a4-830bb5db1c65", "parentUuid": "251c79d2-42cb-4318-8bce-2d5a4f7c72d2", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:28.975Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "e458165b-cd63-4654-9d37-56f0efe02d20", "parentUuid": "5edbdd48-ddfa-43f2-b8d6-70f4127278b7", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:30.381Z", "requestId": "req_011Ch2Qc6f3i7Vr64kFD2tPL", "message": {"id": "msg_011Ch2Qc6tRh9C63e1G5mLx6", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01SzRBf4DkBdrSqtDqr3WN1Z", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 163, "cache_read_input_tokens": 49429, "output_tokens": 83, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 163, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 83, "cache_read_input_tokens": 49429, "cache_creation_input_tokens": 163, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 163}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "bc55f7a8-c3db-4c75-b00b-7b744a10aa8a", "parentUuid": "e458165b-cd63-4654-9d37-56f0efe02d20", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:31.078Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "5c69bbb0-c0fe-4725-bcb1-ecdca11a5056", "parentUuid": "8c42a39f-ca23-46f9-b822-c8c12b85655a", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:32.446Z", "requestId": "req_011Ch2QcFe2zcaFAKFvkHC45", "message": {"id": "msg_011Ch2QcFrBuBvcyMNvSFDJT", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 122, "cache_read_input_tokens": 49592, "output_tokens": 39, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 122, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 39, "cache_read_input_tokens": 49592, "cache_creation_input_tokens": 122, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 122}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "2409a3e9-9534-4916-b3aa-ba793052c765", "parentUuid": "5c69bbb0-c0fe-4725-bcb1-ecdca11a5056", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:32.853Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "3dad0194-f63a-4908-8aa9-5517e854e72a", "parentUuid": "eee833c6-b008-4713-8f1c-710dedf2d865", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:37.644Z", "requestId": "req_011Ch2QcPTqZSdTitPM9wRxn", "message": {"id": "msg_011Ch2QcPgihdGyGQMoTuGJm", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 293, "cache_read_input_tokens": 49714, "output_tokens": 1047, "output_tokens_details": {"thinking_tokens": 735}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 293, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 1047, "cache_read_input_tokens": 49714, "cache_creation_input_tokens": 293, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 293}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "65b51d80-0d16-445f-8abd-fcb1865a498b", "parentUuid": "3dad0194-f63a-4908-8aa9-5517e854e72a", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:38.953Z", "requestId": "req_011Ch2QcPTqZSdTitPM9wRxn", "message": {"id": "msg_011Ch2QcPgihdGyGQMoTuGJm", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 293, "cache_read_input_tokens": 49714, "output_tokens": 1047, "output_tokens_details": {"thinking_tokens": 735}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 293, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 1047, "cache_read_input_tokens": 49714, "cache_creation_input_tokens": 293, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 293}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "user", "uuid": "917e2117-854c-4219-977f-1719697c62b2", "parentUuid": "65b51d80-0d16-445f-8abd-fcb1865a498b", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:39.356Z", "message": {"role": "user", "content": "…"}}
+{"type": "assistant", "uuid": "4056d593-958d-4e44-b578-70e3a270d386", "parentUuid": "067d666a-d156-4e2c-8e1a-1941e9664843", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:41.105Z", "requestId": "req_011Ch2Qcs6VsrAExG68M2gvc", "message": {"id": "msg_011Ch2QcsK922mGXJtd6NkyM", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 1301, "cache_read_input_tokens": 50007, "output_tokens": 329, "output_tokens_details": {"thinking_tokens": 81}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 1301, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 329, "cache_read_input_tokens": 50007, "cache_creation_input_tokens": 1301, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 1301}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
+{"type": "assistant", "uuid": "240275df-0612-43db-b650-d896340388c8", "parentUuid": "4056d593-958d-4e44-b578-70e3a270d386", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:42.347Z", "requestId": "req_011Ch2Qcs6VsrAExG68M2gvc", "message": {"id": "msg_011Ch2QcsK922mGXJtd6NkyM", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 1301, "cache_read_input_tokens": 50007, "output_tokens": 329, "output_tokens_details": {"thinking_tokens": 81}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 1301, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 329, "cache_read_input_tokens": 50007, "cache_creation_input_tokens": 1301, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 1301}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
diff --git a/packages/testkit/fixtures/claude-live/user-prompt-submit.json b/packages/testkit/fixtures/claude-live/user-prompt-submit.json
new file mode 100644
index 00000000..44c606e1
--- /dev/null
+++ b/packages/testkit/fixtures/claude-live/user-prompt-submit.json
@@ -0,0 +1,10 @@
+{
+ "session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
+ "transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
+ "cwd": "/Users/mock/.peppa-dev/workspaces/live",
+ "scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
+ "prompt_id": "2566d5ad-f4dc-489b-8aa6-8ff1730a023c",
+ "permission_mode": "default",
+ "hook_event_name": "UserPromptSubmit",
+ "prompt": "Работай над стори LIVE-1 по правилам AGENTS.md.\n\nЭТО ТЕСТ ХУКОВ ПЕППЫ, не настоящая работа. Не вызывай MCP peppa и не трогай OpenSpec. Строго по шагам, каждый шаг отдельным вызовом инструмента: (1) инструмент AskUserQuestion: вопрос «Какой язык?», header «Язык», варианты «Go» и «Rust»; если вопрос не удался — закончи ход и жди ответа следующим сообщением, остальные шаги сделаешь после ответа. (2) Bash: ls /nonexistent-peppa (3) Bash: touch two.txt (4) Bash: touch three.txt (5) ответь одной строкой: язык и какие шаги удались. Если тебя попросят продолжать — ответь «жду» и закончи ход."
+}
diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts
index e1fd8827..2aa38060 100644
--- a/packages/testkit/src/mock-agent.ts
+++ b/packages/testkit/src/mock-agent.ts
@@ -134,7 +134,8 @@ function fireStatusLine(payload: Record): Promise {
} else if ("usage" in action) {
const u = action.usage;
const model = u.model ?? "claude-sonnet-4-5";
- appendFileSync(
- transcriptPath,
- `${JSON.stringify({ type: "assistant", sessionId: conversationId, message: { id: `msg_${randomUUID()}`, model, role: "assistant", content: [{ type: "text", text: "…" }], usage: { input_tokens: u.input ?? 0, output_tokens: u.output ?? 0, cache_read_input_tokens: u.cacheRead ?? 0, cache_creation_input_tokens: u.cacheWrite ?? 0 } } })}\n`,
- );
+ // Like the live CLI (fixtures/claude-live/transcript.jsonl): one entry per content block,
+ // every entry of the message repeats its id and usage.
+ const id = `msg_${randomUUID()}`;
+ const usage = { input_tokens: u.input ?? 0, output_tokens: u.output ?? 0, cache_read_input_tokens: u.cacheRead ?? 0, cache_creation_input_tokens: u.cacheWrite ?? 0 };
+ for (const block of [{ type: "thinking", thinking: "…" }, { type: "text", text: "…" }]) {
+ appendFileSync(transcriptPath, `${JSON.stringify({ type: "assistant", sessionId: conversationId, message: { id, model, role: "assistant", type: "message", content: [block], usage } })}\n`);
+ }
if (provider === "claude") {
const resets = Math.floor(Date.now() / 1000) + (u.resetInSec ?? 3600);
const rate_limits: Record = {};
@@ -269,7 +275,8 @@ async function run(action: Action): Promise {
await fireStatusLine({
model: { id: model, display_name: model },
...(u.costUsd != null ? { cost: { total_cost_usd: u.costUsd, total_duration_ms: 1000 } } : {}),
- ...(u.context ? { context_window: { context_window_size: u.context.size, current_usage: { input_tokens: u.context.used, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 } } } : {}),
+ // total_*_tokens are the last request, not session totals (live 2.1.323).
+ ...(u.context ? { context_window: { total_input_tokens: u.context.used, total_output_tokens: u.output ?? 0, context_window_size: u.context.size, current_usage: { input_tokens: u.context.used, output_tokens: u.output ?? 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }, used_percentage: Math.round((u.context.used / u.context.size) * 100) } } : {}),
...(Object.keys(rate_limits).length ? { rate_limits } : {}),
});
}
@@ -280,24 +287,30 @@ async function run(action: Action): Promise {
} else if ("permission" in action) {
if (provider !== "claude") return true;
const { tool, input } = action.permission;
- const res = await fireHook("PermissionRequest", { tool_name: tool, tool_input: input, permission_suggestions: [{ type: "addRules", rules: [{ toolName: tool }], behavior: "allow", destination: "localSettings" }] }, tool);
+ const res = await fireHook("PermissionRequest", { tool_name: tool, tool_input: input, permission_suggestions: [{ type: "addDirectories", directories: [cwd], destination: "session" }] }, tool);
const decision = res?.hookSpecificOutput?.decision;
if (decision) {
log("permission", { tool, via: "hook", behavior: decision.behavior, updatedPermissions: !!decision.updatedPermissions, message: decision.message });
out(`⏺ ${tool} ${decision.behavior === "allow" ? "allowed" : "denied"} by hook\n`);
} else {
- out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and don't ask again for ${tool}\n 3. No, and tell Claude what to do differently (esc)\n`);
- await fireHook("Notification", { message: `Claude needs your permission to use ${tool}`, notification_type: "permission_prompt" }, "permission_prompt");
+ // The menu of Claude Code 2.1.323 (PEP-3, captured live): the "No" line is the 4th.
+ out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and always allow access to ${cwd} from this project\n 3. Yes, and switch to auto mode · auto mode handles these prompts for you\n 4. No\n\n Esc to cancel · Tab to amend\n`);
+ await fireHook("Notification", { message: "Claude needs your permission", notification_type: "permission_prompt" }, "permission_prompt");
const key = await dialog();
mode = "busy";
- const behavior = key === "3" ? "deny" : "allow";
- log("permission", { tool, via: "terminal", key, behavior });
- out(`⏺ ${tool} ${behavior === "allow" ? "allowed" : "denied"} in terminal (${key})\n`);
+ const behavior = key === "4" || key === "esc" ? "deny" : "allow";
+ log("permission", { tool, via: "terminal", key, behavior, ...(key === "3" ? { mode: "auto" } : {}) });
+ if (behavior === "deny") {
+ // Live 2.1.323: "No" interrupts the turn — no Stop hook, the prompt waits for the user.
+ out(` ⎿ Interrupted · What should Claude do instead?\n`);
+ return false;
+ }
+ out(`⏺ ${tool} allowed in terminal (${key})\n`);
}
} else if ("ask" in action) {
if (provider !== "claude") return true;
- const questions = action.ask.map((q) => ({ question: q.question, header: "Q", options: (q.options ?? []).map((label) => ({ label })), multiSelect: false }));
- const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions } }, "AskUserQuestion");
+ const questions = action.ask.map((q) => ({ question: q.question, header: "Q", options: (q.options ?? []).map((label) => ({ label, description: label })), multiSelect: false }));
+ const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions }, tool_use_id: `toolu_${randomUUID()}` }, "AskUserQuestion");
const h = res?.hookSpecificOutput;
if (h?.permissionDecision === "allow" && h.updatedInput?.answers) {
log("ask", { via: "hook", answers: h.updatedInput.answers });
@@ -319,7 +332,9 @@ async function run(action: Action): Promise {
const when = spec.reset === "unknown" ? "" : at ? ` resets at ${at}` : " resets 5pm";
if (provider === "claude") {
out(`⎿ Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}\n`);
- await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: lastMessage }, "rate_limit");
+ // Per the hooks docs, last_assistant_message of StopFailure is the API error text, not
+ // Claude's output; error_details is optional and its live wording is unverified (PEP-3).
+ await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: `API Error: Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}` }, "rate_limit");
} else {
out(`■ You've hit your usage limit.${spec.reset === "unknown" ? "" : ` Try again at ${at ?? "5:00 PM"}.`}\n`);
}
diff --git a/packages/testkit/test/claude-live.test.ts b/packages/testkit/test/claude-live.test.ts
new file mode 100644
index 00000000..e30b5583
--- /dev/null
+++ b/packages/testkit/test/claude-live.test.ts
@@ -0,0 +1,196 @@
+// PEP-3: the contract of the live Claude Code CLI (2.1.323), captured on the dev stand with
+// PEPPA_HOOK_CAPTURE_DIR (fixtures/claude-live/*). The real peppa-hook is replayed on those
+// payloads, statusLine/transcript are parsed from them, and the permission dialog keys are
+// read off the menus the live TUI drew.
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, describe, test } from "node:test";
+import { events } from "@peppa/db";
+import { asc, eq } from "drizzle-orm";
+import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
+
+after(teardown);
+
+const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
+const FIX = join(ROOT, "packages/testkit/fixtures/claude-live");
+const fixture = (name: string) => JSON.parse(readFileSync(join(FIX, `${name}.json`), "utf8")) as Record;
+const PM = "telegram" as const;
+
+/** Runs the real peppa-hook like Claude Code does: payload on stdin, JSON (maybe) on stdout. */
+function hook(event: string, payload: unknown, sessionId: number, generation: number): Promise {
+ return new Promise((done) => {
+ const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], {
+ env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: String(generation) },
+ stdio: ["pipe", "pipe", "inherit"],
+ });
+ let out = "";
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", (code) => {
+ assert.equal(code, 0);
+ done(out.trim() ? JSON.parse(out) : null);
+ });
+ p.stdin.end(JSON.stringify(payload));
+ });
+}
+
+describe("Живой Claude Code: statusLine и transcript", () => {
+ test("statusLine 2.1.323: стоимость, контекст, окна; total_*_tokens — не сумма за сессию", () => {
+ const raw = fixture("statusline");
+ const d = core.parseStatusLine(raw);
+ assert.equal(d.costUsd, raw.cost.total_cost_usd);
+ const cu = raw.context_window.current_usage;
+ const used = cu.input_tokens + cu.cache_read_input_tokens + cu.cache_creation_input_tokens;
+ assert.equal(used, raw.context_window.total_input_tokens, "total_input_tokens = the last request's context");
+ assert.deepEqual(d.context, { used, size: raw.context_window.context_window_size, pct: raw.context_window.used_percentage });
+ assert.equal(d.tokens, undefined, "session tokens come from the transcript, not from the status line");
+ assert.deepEqual(d.windows.fiveHour, { pct: raw.rate_limits.five_hour.used_percentage, resetsAt: raw.rate_limits.five_hour.resets_at * 1000 });
+ assert.deepEqual(d.windows.sevenDay, { pct: raw.rate_limits.seven_day.used_percentage, resetsAt: raw.rate_limits.seven_day.resets_at * 1000 });
+ assert.equal(d.model, raw.model.id);
+ });
+
+ test("statusLine до первого ответа API: current_usage null, rate_limits нет", () => {
+ const d = core.parseStatusLine(fixture("statusline-first"));
+ assert.equal(d.context, undefined);
+ assert.deepEqual(d.windows, {});
+ assert.equal(d.costUsd, 0);
+ });
+
+ test("transcript: одно сообщение — несколько записей с тем же id и usage", () => {
+ const path = join(FIX, "transcript.jsonl");
+ const byId = new Map();
+ for (const line of readFileSync(path, "utf8").trim().split("\n")) {
+ const e = JSON.parse(line);
+ if (e.type === "assistant") byId.set(e.message.id, e.message.usage);
+ }
+ const sum = (k: string) => [...byId.values()].reduce((a, u) => a + u[k], 0);
+ const u = core.transcriptUsage(path)!;
+ assert.deepEqual(u.tokens, { input: sum("input_tokens"), output: sum("output_tokens"), cacheRead: sum("cache_read_input_tokens"), cacheWrite: sum("cache_creation_input_tokens") });
+ assert.equal(u.model, "claude-haiku-5-5");
+ });
+});
+
+describe("Живой Claude Code: диалог разрешений", () => {
+ // Menus as the live TUI drew them (tmux capture-pane), all three seen in one session.
+ const menu = (...opts: string[]) =>
+ [" Bash command", "", " touch two.txt", "", " Do you want to proceed?", ...opts.map((o, i) => `${i ? " " : " ❯ "}${i + 1}. ${o}`), "", " Esc to cancel · Tab to amend"].join("\n");
+ const full = menu("Yes", "Yes, and always allow access to /w/live from this project", "Yes, and switch to auto mode · auto mode handles these prompts for you", "No");
+ const noAlways = menu("Yes", "Yes, and switch to auto mode · auto mode handles these prompts for you", "No");
+ const noAuto = menu("Yes", "Yes, and don't ask again for peppa — Get Task commands in /w/live", "No");
+
+ test("клавиша читается с экрана: «No» не всегда 3, «2» не всегда «всегда»", () => {
+ const k = runner.permissionKey;
+ assert.deepEqual(["allow", "always", "deny"].map((a) => k(full, a)), ["1", "2", "4"]);
+ // No "always" line: "2" would switch the session to auto mode — answer plain "Yes".
+ assert.deepEqual(["allow", "always", "deny"].map((a) => k(noAlways, a)), ["1", "1", "3"]);
+ assert.deepEqual(["allow", "always", "deny"].map((a) => k(noAuto, a)), ["1", "2", "3"]);
+ // No dialog on the screen: Yes / Yes / Escape (cancel), never a guessed number for deny.
+ assert.deepEqual(["allow", "always", "deny"].map((a) => k("❯ ", a)), ["1", "1", "Escape"]);
+ assert.equal(k(full, "можно, но аккуратно"), null);
+ // The last dialog wins when an old one is still in the scrollback.
+ assert.equal(k(`${noAlways}\n\n${full}`, "deny"), "4");
+ });
+
+ for (const [answer, key] of [
+ ["allow", "1"],
+ ["always", "2"],
+ ["deny", "4"],
+ ] as const) {
+ test(`нет ответа вовремя → диалог в терминале; поздний «${answer}» жмёт «${key}»`, async () => {
+ const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "touch two.txt" } } }, { say: "Создал." }]] });
+ const sid = await p.start();
+ const q = await p.waitQuestion(sid, "permission");
+ await waitFor("hook released", async () => !(await core.getQuestion(db, q.id)).awaitingHook, 15000);
+ await p.waitLog("dialog drawn", (e) => e.ev === "dialog");
+ assert.ok((await runner.answerAndDeliver(db, q.id, answer, PM)).delivered);
+ const e = await p.waitLog("decision in terminal", (x) => x.ev === "permission");
+ assert.equal(e.via, "terminal");
+ assert.equal(e.key, key);
+ assert.equal(e.mode, undefined, "never switches the session to auto mode");
+ if (answer === "deny") {
+ // Live: "No" interrupts the turn without a Stop hook — Peppa tells the agent why.
+ const note = await p.waitLog("deny note typed", (x) => x.ev === "prompt" && String(x.prompt).startsWith("PM запретил"));
+ assert.equal(note.prompt, runner.PERMISSION_DENIED_NOTE);
+ assert.equal(p.log().some((x) => x.ev === "action" && JSON.stringify(x.action).includes("Создал")), false);
+ } else await p.waitLog("turn went on", (x) => x.ev === "action" && JSON.stringify(x.action).includes("Создал"));
+ await runner.stopSession(db, sid);
+ });
+ }
+});
+
+describe("Живой Claude Code: peppa-hook на снятых payload'ах", () => {
+ test("SessionStart, Notification, PostToolUse(Failure), SessionEnd", async () => {
+ const p = await project({ turns: [[{ sleep: 60_000 }]] });
+ const sid = await p.start();
+ await p.waitLog("mock started", (e) => e.ev === "prompt");
+ const s = await p.session(sid);
+
+ const start = fixture("session-start");
+ await hook("session-start", start, sid, s.generation);
+ assert.equal((await p.session(sid)).conversationId, start.session_id);
+
+ await hook("notification", fixture("notification-permission-prompt"), sid, s.generation);
+ await hook("tool-use", fixture("post-tool-use"), sid, s.generation);
+ await hook("tool-use", fixture("post-tool-use-failure"), sid, s.generation);
+ await hook("session-end", fixture("session-end"), sid, s.generation);
+
+ const evs = (await db.select().from(events).where(eq(events.sessionId, sid)).orderBy(asc(events.id))).map((e) => ({ type: e.type, payload: e.payload as Record }));
+ assert.deepEqual(evs.find((e) => e.type === "notification")?.payload, { type: "permission_prompt", message: "Claude needs your permission" });
+ const steps = evs.filter((e) => e.type === "step").map((e) => [e.payload.text, e.payload.ok]);
+ assert.deepEqual(steps, [
+ ["touch two.txt", true],
+ ["ls /nonexistent-peppa", false],
+ ]);
+ assert.equal(evs.find((e) => e.type === "claude_session_end")?.payload.reason, "prompt_input_exit");
+ await runner.stopSession(db, sid);
+ });
+
+ test("PermissionRequest: «Всегда» возвращает permission_suggestions живого CLI", async () => {
+ const p = await project({ turns: [[{ sleep: 60_000 }]] });
+ const sid = await p.start();
+ const s = await p.session(sid);
+ const raw = fixture("permission-request");
+ const out = hook("permission-request", raw, sid, s.generation);
+ const q = await p.waitQuestion(sid, "permission");
+ assert.match(q.text, /touch two\.txt/);
+ await runner.answerAndDeliver(db, q.id, "always", PM);
+ assert.deepEqual(await out, {
+ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow", updatedPermissions: raw.permission_suggestions } },
+ });
+ await runner.stopSession(db, sid);
+ });
+
+ test("PreToolUse AskUserQuestion: ответ PM уходит в updatedInput.answers", async () => {
+ const p = await project({ turns: [[{ sleep: 60_000 }]] });
+ const sid = await p.start();
+ const s = await p.session(sid);
+ const raw = fixture("pre-tool-use-ask-user-question");
+ const out = hook("ask-question", raw, sid, s.generation);
+ const q = await p.waitQuestion(sid, "question");
+ assert.deepEqual(q.options, ["Go", "Rust"]);
+ await runner.answerAndDeliver(db, q.id, "Go", PM);
+ const res = await out;
+ assert.equal(res.hookSpecificOutput.permissionDecision, "allow");
+ assert.deepEqual(res.hookSpecificOutput.updatedInput, { ...raw.tool_input, answers: { "Какой язык?": "Go" } });
+ await runner.stopSession(db, sid);
+ });
+
+ test("Stop: стори в работе → decision block; после двух — PM", async () => {
+ const p = await project({ turns: [[{ sleep: 60_000 }]] });
+ const sid = await p.start();
+ await p.waitLog("mock started", (e) => e.ev === "prompt");
+ await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" });
+ const s = await p.session(sid);
+ const stop = fixture("stop");
+ const first = await hook("stop", stop, sid, s.generation);
+ assert.equal(first.decision, "block");
+ assert.match(first.reason, new RegExp(p.taskKey));
+ assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block");
+ assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null);
+ const q = await p.waitQuestion(sid, "attention");
+ assert.equal(q.text, fixture("stop-after-block").last_assistant_message);
+ await runner.stopSession(db, sid);
+ });
+});
--
2.45.2
From 5f1b1b42120df5fad703031cac839b634c551786 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 16:27:14 +0500
Subject: [PATCH 002/439] PEP-70: pug mascot next to the agents' questions
Cartoon pug (inline SVG) on Home: sleeps when nothing waits, perks up with
a speech bubble and question count when agents ask. Motion only without
prefers-reduced-motion.
Co-Authored-By: Claude Opus 5.5
---
apps/web/app/(app)/page.tsx | 4 +-
apps/web/app/app.css | 10 ++++
apps/web/components/PugMascot.tsx | 89 +++++++++++++++++++++++++++++++
3 files changed, 102 insertions(+), 1 deletion(-)
create mode 100644 apps/web/components/PugMascot.tsx
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 97bb92a0..81f7fc99 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -1,5 +1,6 @@
import { listUserProjects, onboardingChecklist } from "@peppa/core";
import { OnboardingChecklist } from "@/components/Onboarding";
+import { PugBanner } from "@/components/PugMascot";
import { LiveRefresh } from "@/components/LiveRefresh";
import { ActivityAside } from "@/components/ActivityAside";
import { ProjectList, QuestionCard, SessionCard } from "@/components/cards";
@@ -20,7 +21,8 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}
{onboarding.visible && }
- {items.length === 0 ? Агентам от тебя ничего не нужно. : items.map((q) => )}
+
+ {items.map((q) => )}
все раннеры}>
{sessions.length === 0 ? Сейчас ничего не запущено. : sessions.map((s) => )}
diff --git a/apps/web/app/app.css b/apps/web/app/app.css
index f150bd47..22beefde 100644
--- a/apps/web/app/app.css
+++ b/apps/web/app/app.css
@@ -101,3 +101,13 @@
@apply bg-primary/30;
}
}
+
+/* PEP-70: pug mascot — gentle breathing while asleep, a curious head tilt when agents ask. */
+@media (prefers-reduced-motion: no-preference) {
+ .pug-sleep .pug-head { animation: pug-breathe 3.2s ease-in-out infinite; }
+ .pug-sleep .pug-zzz { animation: pug-zzz 3.2s ease-in-out infinite; }
+ .pug-alert .pug-head { animation: pug-tilt 2.4s ease-in-out infinite; }
+}
+@keyframes pug-breathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.03, 0.98); } }
+@keyframes pug-zzz { 0%, 100% { opacity: 0.25; transform: translateY(2px); } 50% { opacity: 0.6; transform: translateY(-2px); } }
+@keyframes pug-tilt { 0%, 60%, 100% { transform: rotate(0deg); } 70% { transform: rotate(-9deg); } 85% { transform: rotate(5deg); } }
diff --git a/apps/web/components/PugMascot.tsx b/apps/web/components/PugMascot.tsx
new file mode 100644
index 00000000..d009a6da
--- /dev/null
+++ b/apps/web/components/PugMascot.tsx
@@ -0,0 +1,89 @@
+// PEP-70: Peppa's mascot — a cartoon pug next to the agents' questions. Pure SVG (no external
+// images), fixed fawn/black colours that read on both themes; motion only without reduced-motion.
+import { cn } from "@/lib/utils";
+
+type Mood = "sleep" | "alert";
+
+export function PugMascot({ mood, size = 72, className }: { mood: Mood; size?: number; className?: string }) {
+ const awake = mood === "alert";
+ return (
+
+
+ {/* head */}
+
+ {/* folded "button" ears flop over the head */}
+
+
+ {/* forehead wrinkles */}
+
+
+ {/* cheeks */}
+
+
+ {/* black mask */}
+
+ {/* eyes */}
+ {awake ? (
+ <>
+
+
+
+
+
+
+ >
+ ) : (
+ <>
+
+
+ >
+ )}
+ {/* nose */}
+
+
+ {/* mouth + tongue */}
+
+ {awake && }
+
+ {!awake && (
+
+ z
+ z
+
+ )}
+
+ );
+}
+
+/** Mascot with a speech bubble: sleeps when nothing waits, perks up when agents ask. */
+export function PugBanner({ count }: { count: number }) {
+ const awake = count > 0;
+ return (
+
+
+
+ {awake ? (
+ <>
+ Гав! {count === 1 ? "Агент ждёт" : "Агенты ждут"} твоего ответа
+ — {plural(count)} ниже.
+ >
+ ) : (
+ Тихо… Агентам от тебя ничего не нужно, мопс спит.
+ )}
+
+
+ );
+}
+
+function plural(n: number) {
+ const m10 = n % 10, m100 = n % 100;
+ const w = m10 === 1 && m100 !== 11 ? "вопрос" : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? "вопроса" : "вопросов";
+ return `${n} ${w}`;
+}
--
2.45.2
From 06b3501427ad93fa5db260b52c946cc2587d8b18 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 16:29:34 +0500
Subject: [PATCH 003/439] PEP-70: clay-style chibi pug with a terminal-screen
face
Co-Authored-By: Claude Opus 5.5
---
apps/web/app/app.css | 10 ++-
apps/web/components/PugMascot.tsx | 135 ++++++++++++++++++++----------
2 files changed, 97 insertions(+), 48 deletions(-)
diff --git a/apps/web/app/app.css b/apps/web/app/app.css
index 22beefde..462b4490 100644
--- a/apps/web/app/app.css
+++ b/apps/web/app/app.css
@@ -102,12 +102,14 @@
}
}
-/* PEP-70: pug mascot — gentle breathing while asleep, a curious head tilt when agents ask. */
+/* PEP-70: pug mascot — breathing while asleep, a curious head tilt and a blinking cursor when agents ask. */
@media (prefers-reduced-motion: no-preference) {
- .pug-sleep .pug-head { animation: pug-breathe 3.2s ease-in-out infinite; }
+ .pug-sleep .pug-body { animation: pug-breathe 3.2s ease-in-out infinite; }
.pug-sleep .pug-zzz { animation: pug-zzz 3.2s ease-in-out infinite; }
.pug-alert .pug-head { animation: pug-tilt 2.4s ease-in-out infinite; }
+ .pug-alert .pug-cursor { animation: pug-blink 1s steps(1) infinite; }
}
-@keyframes pug-breathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.03, 0.98); } }
+@keyframes pug-breathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.02, 0.985); } }
@keyframes pug-zzz { 0%, 100% { opacity: 0.25; transform: translateY(2px); } 50% { opacity: 0.6; transform: translateY(-2px); } }
-@keyframes pug-tilt { 0%, 60%, 100% { transform: rotate(0deg); } 70% { transform: rotate(-9deg); } 85% { transform: rotate(5deg); } }
+@keyframes pug-tilt { 0%, 60%, 100% { transform: rotate(0deg); } 70% { transform: rotate(-7deg); } 85% { transform: rotate(4deg); } }
+@keyframes pug-blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
diff --git a/apps/web/components/PugMascot.tsx b/apps/web/components/PugMascot.tsx
index d009a6da..f8ec7e06 100644
--- a/apps/web/components/PugMascot.tsx
+++ b/apps/web/components/PugMascot.tsx
@@ -1,61 +1,108 @@
-// PEP-70: Peppa's mascot — a cartoon pug next to the agents' questions. Pure SVG (no external
-// images), fixed fawn/black colours that read on both themes; motion only without reduced-motion.
+// PEP-70: Peppa's mascot — a soft "clay" chibi pug whose face is a terminal screen (`> _`).
+// Pure SVG (no external images), fixed colours that read on both themes; motion only without
+// reduced-motion (see .pug-* in app.css).
+import { useId } from "react";
import { cn } from "@/lib/utils";
type Mood = "sleep" | "alert";
-export function PugMascot({ mood, size = 72, className }: { mood: Mood; size?: number; className?: string }) {
+export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: number; className?: string }) {
const awake = mood === "alert";
+ const id = useId().replace(/[^a-zA-Z0-9]/g, "");
+ const fur = `pf${id}`, furDark = `pd${id}`, ear = `pe${id}`, screen = `ps${id}`, glow = `pg${id}`, soft = `po${id}`;
return (
-
- {/* head */}
-
- {/* folded "button" ears flop over the head */}
-
-
- {/* forehead wrinkles */}
-
-
- {/* cheeks */}
-
-
- {/* black mask */}
-
- {/* eyes */}
- {awake ? (
- <>
-
-
-
-
-
-
- >
- ) : (
- <>
-
-
- >
- )}
- {/* nose */}
-
-
- {/* mouth + tongue */}
-
- {awake && }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* floor shadow */}
+
+
+
+ {/* curly tail */}
+
+ {/* legs */}
+
+
+ {/* body */}
+
+ {/* arms */}
+
+
+ {/* belly prompt */}
+
+
+
+
+
+
+ {/* head */}
+
+ {/* folded button ears */}
+
+
+ {/* forehead wrinkles */}
+
+
+ {/* cheeks */}
+
+
+ {/* screen face (the pug's black mask) */}
+
+
+ {awake ? (
+
+
+
+
+ ) : (
+
+
+
+
+ )}
+
+
{!awake && (
-
- z
- z
+
+ z
+ z
)}
--
2.45.2
From 7a4988ec8957074751f0e4f18fb13a5157f71860 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 16:30:46 +0500
Subject: [PATCH 004/439] PEP-70: pug face back, the terminal prompt glows on
the belly
Co-Authored-By: Claude Opus 5.5
---
apps/web/components/PugMascot.tsx | 43 +++++++++++++++++++------------
1 file changed, 27 insertions(+), 16 deletions(-)
diff --git a/apps/web/components/PugMascot.tsx b/apps/web/components/PugMascot.tsx
index f8ec7e06..f250d9e1 100644
--- a/apps/web/components/PugMascot.tsx
+++ b/apps/web/components/PugMascot.tsx
@@ -1,4 +1,4 @@
-// PEP-70: Peppa's mascot — a soft "clay" chibi pug whose face is a terminal screen (`> _`).
+// PEP-70: Peppa's mascot — a soft "clay" chibi pug with a terminal prompt (`> _`) glowing on its belly.
// Pure SVG (no external images), fixed colours that read on both themes; motion only without
// reduced-motion (see .pug-* in app.css).
import { useId } from "react";
@@ -64,10 +64,12 @@ export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: n
{/* arms */}
- {/* belly prompt */}
-
-
-
+ {/* belly screen with the glowing prompt */}
+
+
+
+
+
@@ -82,20 +84,29 @@ export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: n
{/* cheeks */}
- {/* screen face (the pug's black mask) */}
-
-
+ {/* black mask */}
+
+ {/* eyes */}
{awake ? (
-
-
-
-
+ <>
+
+
+
+
+
+
+ >
) : (
-
-
-
-
+ <>
+
+
+ >
)}
+ {/* nose, mouth, tongue */}
+
+
+
+ {awake && }
--
2.45.2
From 57d7857d9469c5bf0112981cef16ca4774968ef3 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 17:57:02 +0500
Subject: [PATCH 005/439] PEP-71: login only through eGov, unknown IIN
registers an account
Gitea and password login are gone from the web; the first eGov login creates a
Peppa account (login from the certificate name). Projects of self-registered
owners run agents only on a subscription pool, never on the machine login.
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 3 +-
apps/web/app/(app)/actions.ts | 37 --------
apps/web/app/(app)/help/page.tsx | 4 +-
apps/web/app/(app)/settings/page.tsx | 80 ++++++----------
apps/web/app/(app)/users/page.tsx | 52 ++--------
apps/web/app/auth/callback/route.ts | 37 --------
apps/web/app/auth/egov/complete/route.ts | 4 +-
apps/web/app/auth/password/route.ts | 25 -----
apps/web/app/auth/start/route.ts | 16 ----
apps/web/app/login/page.tsx | 22 +----
apps/web/components/EgovSign.tsx | 2 +-
apps/web/lib/auth.ts | 2 -
.../pep-71-egov-only-login/proposal.md | 29 ++++++
.../specs/web-auth/spec.md | 94 +++++++++++++++++++
.../changes/pep-71-egov-only-login/tasks.md | 14 +++
packages/core/src/access.ts | 16 ++++
packages/core/src/egov.ts | 71 ++++++++++++--
packages/runner/src/sessions.ts | 5 +
packages/testkit/test/egov.test.ts | 49 +++++++++-
19 files changed, 318 insertions(+), 244 deletions(-)
delete mode 100644 apps/web/app/auth/callback/route.ts
delete mode 100644 apps/web/app/auth/password/route.ts
delete mode 100644 apps/web/app/auth/start/route.ts
create mode 100644 openspec/changes/pep-71-egov-only-login/proposal.md
create mode 100644 openspec/changes/pep-71-egov-only-login/specs/web-auth/spec.md
create mode 100644 openspec/changes/pep-71-egov-only-login/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index 626777af..1ce113bf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@
Текущее состояние и порядок работ: `docs/HANDOFF.md`.
## Структура
-- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (PEP-32): шапка (статус, эпик, прогресс tasks.md, «Изменить» — название/описание/эпик, агент и живая сессия с терминалом и лентой шагов) и вкладки `?tab=` Proposal · Design (свой безопасный рендер `components/Markdown.tsx`) · Specs (дельта-спеки change) · Tasks · Comments (вопросы + комментарии PM: событие `pm_comment`, агент видит в `get_task`, флажок «Отправить агенту сейчас») · Tests · Merge request («Принять и смержить» = `acceptStory` в runner/flow.ts) · Activity (с авторами: `payload.login` / сессия / система); change читает `core/openspec.ts` (`readChange`, `parseTasks`, `taskProgress`, и архивный); новый проект. **Живые страницы (PEP-37)**: `LiveRefresh` (вместо `AutoRefresh`, он остался только у подписок) слушает SSE `GET /api/live?scope=home|runners|project:|task:|steps:` и делает `router.refresh()` (ждёт, пока пользователь печатает), индикатор связи, откат на опрос 5 с; хаб `runner/live.ts` (`globalThis`) будят `notify()` (подписчик `web`, сокет `$PEPPA_HOME/web.events.sock`) и `PRAGMA data_version` + `total_changes()` раз в секунду, отпечаток области — один SQL без `last_activity_at`/шагов; заголовки `no-cache, no-transform`, `X-Accel-Buffering: no`, пинг 15 с **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
+- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход только через eGov QR (PEP-71: первый вход создаёт учётку, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (PEP-32): шапка (статус, эпик, прогресс tasks.md, «Изменить» — название/описание/эпик, агент и живая сессия с терминалом и лентой шагов) и вкладки `?tab=` Proposal · Design (свой безопасный рендер `components/Markdown.tsx`) · Specs (дельта-спеки change) · Tasks · Comments (вопросы + комментарии PM: событие `pm_comment`, агент видит в `get_task`, флажок «Отправить агенту сейчас») · Tests · Merge request («Принять и смержить» = `acceptStory` в runner/flow.ts) · Activity (с авторами: `payload.login` / сессия / система); change читает `core/openspec.ts` (`readChange`, `parseTasks`, `taskProgress`, и архивный); новый проект. **Живые страницы (PEP-37)**: `LiveRefresh` (вместо `AutoRefresh`, он остался только у подписок) слушает SSE `GET /api/live?scope=home|runners|project:|task:|steps:` и делает `router.refresh()` (ждёт, пока пользователь печатает), индикатор связи, откат на опрос 5 с; хаб `runner/live.ts` (`globalThis`) будят `notify()` (подписчик `web`, сокет `$PEPPA_HOME/web.events.sock`) и `PRAGMA data_version` + `total_changes()` раз в секунду, отпечаток области — один SQL без `last_activity_at`/шагов; заголовки `no-cache, no-transform`, `X-Accel-Buffering: no`, пинг 15 с **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта. **Стори из сообщения (PEP-45)**: любой другой текст привязанного пользователя — черновик (`apps/bot/src/drafts.ts`, `settings` `bot.draft:`, сутки): префикс `KEY:`/`в KEY:` (только свои проекты) или кнопки проекта → кнопки эпика/«Создать» → `createTask` → «▶️ Взять в работу» (`moveTask`); кнопки `d::p|g|x`, `t::start|keep`. Голос: `getFile` → `transcribe.ts` — OpenAI-совместимый `POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions` (`PEPPA_TRANSCRIBE_KEY`, `_MODEL`=whisper-1, `_LANG`=ru); без env — просит текстом. Моки: `mock-transcribe`, голос и `/file/` в `mock-telegram`
- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36)
- `packages/shared` — env, ключи задач (`PEP-42`)
@@ -35,6 +35,7 @@
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
- **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ` `, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/`
+- **Вход только eGov (PEP-71)**: Gitea-вход и пароль убраны из веба (маршрутов `/auth/start|callback|password` нет). Неизвестный ИИН → `registerEgovUser` (core/egov.ts): учётка `gitea_id < 0` без пароля, логин `egovLoginBase` из имени сертификата («ИВАНОВА АЙГЕРИМ» → `aigerim.ivanova`, дубль `-2`, без имени `user-<4 цифры>`). Самозарегистрированный владелец (без Gitea и пароля, не админ/allowlist) без пула не получает вход машины для агентов — `mayUseMachineLogin` (core/access.ts) в `startSession`. Старым учёткам ИИН — «Настройки» (пока залогинен) или `peppa user egov`; аварийный вход — `peppa web login-link`
- **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из stdin или сгенерированный)
- **Секреты (PEP-54/19)**: секреты проекта — таблица `project_secrets` (имя env, `value_enc` = `encrypt`, кто менял, `last_used_at`), `core/secrets.ts` (`setProjectSecret`/`deleteProjectSecret` через `projectForUser`, имена `^[A-Z][A-Z0-9_]*$` без зарезервированных `PATH`/`PEPPA_*`/`CLAUDE_*`…, `projectSecretEnv`, `projectSecretMasker`); веб «⋯ Настройки проекта → Секреты» (значение только на запись). Раннер (`launch` в runner/sessions.ts) пишет `secrets.env` (0600) в каталог поколения, `launch.sh` его читает и сразу удаляет — значений нет в argv tmux; событие `secrets_issued {names}`. Маскировка `••••` — `TerminalFeed` (`mask`, из `terminalSse`) и `recordStep`. MCP `list_secrets` (агент — проект своей сессии; PM — доступный проект), только имена. Ревизия (core/secrets-audit.ts `secretsAudit`): секреты платформы `PLATFORM_SECRETS` (задан ли, возраст от `settings` `secrets.rotated:`, кто использует, шаги ротации), шифрование по колонкам, MCP-токены по клиентам, подписки, секреты проектов — `/secrets` (суперадмин) и `peppa secrets audit|new-key|reencrypt|rotated|revoke-client|check-gitea|list`. Ротация `PEPPA_SECRET` двумя ключами: `PEPPA_SECRET_PREVIOUS` принимается для `decrypt`/`verify`/хэшей OAuth (`hashTokenCandidates`)/подписей вебхуков, пишется только текущим; `reencryptAll` переводит все `*_enc`. Новые зашифрованные колонки — добавлять в `encryptedColumns` (secrets-audit.ts), иначе ротация их потеряет
- **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. **Ротация (PEP-39)**: лимит (StopFailure/баннер) помечает подписку «лимит до …» (`markSubscriptionLimited`), `recordLimit` при свободной подписке того же провайдера в пуле (`rotationCandidate`: пул проекта, иначе пулы текущей подписки; наименее занятая) ставит `sessions.rotate_reason=limit` вместо пинга PM, вачдог (runner/rotation.ts `tryRotate`/`rotateSession`) убивает tmux и `resumeSession` на новой подписке — Claude/OpenCode тот же разговор, Codex заново (`conversation_id` сбрасывается, история в `CODEX_HOME` аккаунта не переносится); событие `subscription_switched` + сообщение в Telegram (`sendProjectMessage`). Порог: баннер «N% of your … limit» (≥ `PEPPA_ROTATE_THRESHOLD_PCT`, 85) → `rotate_reason=threshold`, Stop-хук не подталкивает, после хода — на подписку без сессий. Свободных нет — ждёт сброса (PEP-56); освободилась раньше — переключит. Предел `PEPPA_ROTATE_MAX_PER_HOUR` (3), выключение `PEPPA_ROTATE=off`. Справедливость: проект с ≥ `PEPPA_POOL_PROJECT_MAX` (2) подписками пула не получает свободную, пока сессия другого проекта ждёт сброса на этом пуле (`poolRestricted`). Мок: `limit.credential` в сценарии — лимит только на входе с этой подстрокой, `{warn: N}` — баннер порога. Провайдер OpenCode (`providers.ts`): `opencode --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — » и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 250e91f2..1a752add 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -4,7 +4,6 @@ import {
setAutonomy,
type AutonomyLevel,
type AutonomySettings,
- linkEgovIin,
createEpic,
createTask,
updateEpic,
@@ -22,13 +21,9 @@ import {
updateIncidentSettings,
setReviewSettings,
type IncidentPolicy,
- changeOwnPassword,
- createLocalUser,
getUser,
- isLocalUser,
isSuperadmin,
setUserDisabled,
- setUserPassword,
NOTIFY_EVENTS,
defaultPrefs,
deletePushSubscription,
@@ -354,12 +349,6 @@ export async function revokeConnectedApp(f: FormData) {
});
}
-export async function unlinkEgov(f: FormData) {
- const user = asWebActor(await requireUser());
- await attempt(f, async () => {
- await linkEgovIin(db, user.id, null);
- });
-}
export async function addProjectMember(f: FormData) {
const user = asWebActor(await requireUser());
@@ -574,23 +563,7 @@ async function requireSuperadmin() {
return user;
}
-export async function createLocalUserAction(f: FormData) {
- await attempt(f, async () => {
- await requireSuperadmin();
- const u = await createLocalUser(db, { login: str(f, "login"), name: str(f, "name"), password: String(f.get("password") ?? "") });
- return `/users?created=${encodeURIComponent(u.login)}`;
- });
-}
-export async function resetUserPasswordAction(f: FormData) {
- await attempt(f, async () => {
- await requireSuperadmin();
- const u = await getUser(db, Number(str(f, "userId")));
- if (!u || !isLocalUser(u)) throw new PeppaError("Пароль задаётся только локальным пользователям");
- await setUserPassword(db, u.id, String(f.get("password") ?? ""));
- return `/users?reset=${encodeURIComponent(u.login)}`;
- });
-}
export async function setUserDisabledAction(f: FormData) {
await attempt(f, async () => {
@@ -602,16 +575,6 @@ export async function setUserDisabledAction(f: FormData) {
});
}
-export async function changePasswordAction(f: FormData) {
- const user = asWebActor(await requireUser());
- await attempt(f, async () => {
- if (!isLocalUser(user)) throw new PeppaError("Вы входите через Gitea — пароль меняется там");
- const next = String(f.get("newPassword") ?? "");
- if (next !== String(f.get("confirm") ?? "")) throw new PeppaError("Новый пароль и повтор не совпадают");
- await changeOwnPassword(db, user, String(f.get("current") ?? ""), next);
- return "/settings?password=changed";
- });
-}
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 7c7e4331..8845b10e 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,7 +70,7 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
- Локальные пользователи — аккаунты Пеппы без Gitea: входят по логину и паролю на странице входа, создаёт их суперадмин в разделе «Пользователи», пароль меняется в «Настройках». Их добавляют в участники по логину Пеппы; доступа к репозиторию в Gitea у них нет — код только через Пеппу, а их новые проекты создаются в пространстве peppa-bot .
+ Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.
Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.
@@ -83,7 +83,7 @@ export default async function Help() {
Адрес сервера:
{mcp}
- ChatGPT : Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите (Gitea, eGov или логин и пароль) и нажмите «Разрешить». В чате включите коннектор Peppa.
+ ChatGPT : Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa.
Codex, Claude и другие MCP-клиенты : добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.
Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в Настройках.
Модель агента — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (Claude Code, Codex, OpenCode), модель (sonnet, opus, gpt-5-codex…) и усилия. Эскалация : после N неудач стори (красные проверки по разным коммитам и возвраты ревьюера, по умолчанию 2) она до конца идёт на сильной модели — живой раннер перезапускается в том же разговоре. Запасной провайдер — если у основного нет рабочей подписки в пуле (все в лимите или с ошибкой входа), раннер стартует на нём.
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 54e35797..06389f30 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -1,4 +1,4 @@
-import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, MIN_PASSWORD, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
+import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
@@ -8,7 +8,7 @@ import { EgovSign } from "@/components/EgovSign";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { changePasswordAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unlinkEgov, unpairTelegramAction } from "../actions";
+import { pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
@@ -27,9 +27,9 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
);
}
-export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; password?: string; notify?: string }> }) {
+export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string }> }) {
const user = await requireUser();
- const { error, egov, password, notify } = await searchParams;
+ const { error, egov, notify } = await searchParams;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
const apps = await connectedApps(db, user.id);
@@ -44,37 +44,24 @@ export default async function Settings({ searchParams }: { searchParams: Promise
- {password === "changed" && Пароль изменён }
- {local ? (
-
-
- {user.login} — локальный пользователь Пеппы, нет аккаунта Gitea . Доступ к коду проектов — только через Пеппу
- (агенты, PR, проверки); соавтором репозитория в Gitea вас добавить нельзя, новые проекты создаются в пространстве{" "}
- peppa-bot .
+
+
+ Логин {user.login}
+ {user.name ? <> · {user.name}> : null}. Вход в Пеппу — только через eGov QR
+ {user.egovIin ? (
+ <>
+ , ИИН {maskIin(user.egovIin)} .
+ >
+ ) : (
+ <>. ИИН ещё не привязан — привяжите его ниже, иначе после выхода вы не сможете войти.>
+ )}
+
+ {local && (
+
+ Аккаунта Gitea нет: код проектов — через Пеппу (агенты, PR, проверки), новые проекты создаются в пространстве peppa-bot .
-
-
- ) : (
- Вы входите через Gitea{user.egovIin ? " или eGov" : ""}; пароль Пеппы не нужен.
- )}
+ )}
+
{superadmin && (
}
>
- Локальные пользователи без Gitea: создать, сбросить пароль, отключить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
+ Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
)}
@@ -107,27 +94,18 @@ export default async function Settings({ searchParams }: { searchParams: Promise
Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.
-
- {egov === "linked" && eGov привязан — теперь можно входить по QR }
- {user.egovIin ? (
+ {!user.egovIin && (
+
+ {egov === "linked" && eGov привязан — теперь можно входить по QR }
-
- Привязан ИИН {maskIin(user.egovIin)} — на странице входа можно войти через eGov QR.
-
-
-
- ) : (
-
- Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. После этого можно входить в Пеппу через eGov.
+ Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Пеппу — только через eGov.
- )}
-
+
+ )}
+ {user.egovIin && egov === "linked" && eGov привязан — теперь можно входить по QR }
{user.telegramChatId ? (
diff --git a/apps/web/app/(app)/users/page.tsx b/apps/web/app/(app)/users/page.tsx
index 45a80060..93041a8a 100644
--- a/apps/web/app/(app)/users/page.tsx
+++ b/apps/web/app/(app)/users/page.tsx
@@ -1,58 +1,33 @@
import { notFound } from "next/navigation";
-import { isLocalUser, isSuperadmin, listUsers, MIN_PASSWORD, platformAdmins } from "@peppa/core";
+import { isLocalUser, isSuperadmin, listUsers, maskIin, platformAdmins } from "@peppa/core";
import { Hidden } from "@/components/cards";
-import { ago, Flash, Notice, PageHeader, Section } from "@/components/common";
+import { ago, Flash, PageHeader, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
-import { Input, Label } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { createLocalUserAction, resetUserPasswordAction, setUserDisabledAction } from "../actions";
+import { setUserDisabledAction } from "../actions";
const back = { back: "/users" };
-/** Superadmin only (PEP-68): local users without Gitea — create, reset password, disable. */
-export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string; created?: string; reset?: string }> }) {
+/** Superadmin only (PEP-68/71): who is registered, disable / enable. */
+export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound();
- const { error, created, reset } = await searchParams;
+ const { error } = await searchParams;
const all = await listUsers(db);
const admins = new Set(await platformAdmins(db));
return (
- {created &&
Пользователь «{created}» создан — передайте ему логин и временный пароль, сменить его можно в «Настройках». }
- {reset &&
Пароль «{reset}» сброшен — передайте новый временный пароль. }
- Локальные пользователи входят по логину и паролю, без аккаунта Gitea. Отключённый пользователь сразу теряет сессии веба и MCP.
+ Вход только через eGov: первый вход по QR сам создаёт учётку по ИИН. Доступ к проектам — приглашением владельца; агенты проекта нового пользователя
+ работают только на пуле подписок. Отключённый пользователь сразу теряет сессии веба и MCP.
-
-
{all.map((u) => {
const local = isLocalUser(u);
@@ -61,20 +36,13 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
{u.login}
{u.name && {u.name} }
- {local ? "локальный" : "Gitea"}
+ {!local && Gitea }
{admins.has(u.login.toLowerCase()) && суперадмин }
{u.disabledAt && отключён }
- {local && !u.passwordHash && без пароля }
+ {u.egovIin ? eGov {maskIin(u.egovIin)} : без eGov — не войдёт }
{u.lastLoginAt ? `вход ${ago(u.lastLoginAt)}` : "ещё не входил"}
- {local && (
-
- )}
{u.id !== me.id && (
diff --git a/apps/web/components/EgovSign.tsx b/apps/web/components/EgovSign.tsx
index c984bdec..5405327d 100644
--- a/apps/web/components/EgovSign.tsx
+++ b/apps/web/components/EgovSign.tsx
@@ -68,7 +68,7 @@ export function EgovSign({ purpose, next, label }: { purpose: "login" | "link";
return (
{phase.at === "error" &&
{phase.message}
}
-
void start().catch((e: Error) => fail(e.message))}>
+ void start().catch((e: Error) => fail(e.message))}>
{phase.at === "error" ? "Новый QR" : label}
diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts
index 583303ca..0dfe4e3b 100644
--- a/apps/web/lib/auth.ts
+++ b/apps/web/lib/auth.ts
@@ -6,8 +6,6 @@ import { cache } from "react";
import { db } from "./db";
export const SESSION_COOKIE = "peppa_session";
-export const STATE_COOKIE = "peppa_oauth_state";
-export const NEXT_COOKIE = "peppa_next";
/** eGov QR flow handle (PEP-65): httpOnly, only for /auth/egov, lives as long as the QR. */
export const EGOV_COOKIE = "peppa_egov";
diff --git a/openspec/changes/pep-71-egov-only-login/proposal.md b/openspec/changes/pep-71-egov-only-login/proposal.md
new file mode 100644
index 00000000..92f2a60d
--- /dev/null
+++ b/openspec/changes/pep-71-egov-only-login/proposal.md
@@ -0,0 +1,29 @@
+# PEP-71: вход только через eGov с авторегистрацией
+
+## Why
+Способов входа три: Gitea, eGov QR, логин и пароль. Это путает. PM решил оставить один — eGov.
+Сейчас человек, подписавший QR с непривязанным ИИН, получает отказ «ИИН не привязан». Вместо отказа его
+учётка должна создаваться сама.
+
+## What Changes
+- Подписал QR с неизвестным ИИН → Пеппа создаёт пользователя. Учётка без Gitea и без пароля, ИИН привязан,
+ логин берётся из имени в сертификате (`aigerim.ivanova`, при совпадении — `-2`, без имени — `user-<4 цифры ИИН>`).
+ Имя для экрана — «Имя Фамилия».
+- Со страницы входа убраны кнопка Gitea и форма логина с паролем. Удалены маршруты `/auth/start`,
+ `/auth/callback`, `/auth/password`, server actions смены и сброса пароля, создания локального
+ пользователя и отвязки eGov.
+- «Настройки»: вместо блока пароля — учётка (логин, ИИН). Привязка eGov показывается только тем, у кого ИИН
+ ещё нет, — это старые учётки Gitea, пока они залогинены. Отвязки нет: без ИИН в Пеппу не войти.
+- «Пользователи» (суперадмин): список с ИИН и кнопками отключить/включить; создания и паролей нет.
+- **Безопасность**: зарегистрироваться может любой человек с eGov. Поэтому проект, чей владелец сам
+ зарегистрировался через eGov (без Gitea и без пароля) и не входит в админы или allowlist, без пула подписок
+ не запускает агентов на входе машины (`mayUseMachineLogin`). Пул назначает суперадмин.
+- Аварийный вход — `peppa web login-link ` (CLI на машине), как и раньше.
+
+## Impact
+- `packages/core/src/egov.ts` (`registerEgovUser`, `egovLoginBase`), `access.ts` (`mayUseMachineLogin`),
+ `runner/src/sessions.ts` (проверка перед запуском).
+- Веб: `/login`, `/settings`, `/users`, `/help`, `auth/egov/complete`, `actions.ts`.
+- Код Gitea OAuth и паролей в core остаётся: токены Gitea у старых учёток, CLI `peppa user add|passwd`.
+- Существующие учётки без ИИН (asel, admin) войдут, только если ИИН привязать заранее: в «Настройках»,
+ пока сессия жива, или командой `peppa user egov <ИИН>`.
diff --git a/openspec/changes/pep-71-egov-only-login/specs/web-auth/spec.md b/openspec/changes/pep-71-egov-only-login/specs/web-auth/spec.md
new file mode 100644
index 00000000..3b12a955
--- /dev/null
+++ b/openspec/changes/pep-71-egov-only-login/specs/web-auth/spec.md
@@ -0,0 +1,94 @@
+## MODIFIED Requirements
+
+### Requirement: Вход через eGov QR
+Страница входа SHALL предлагать единственный способ входа — «Войти через eGov»: Пеппа
+создаёт сессию подписи в relay KazEDS, показывает QR и ссылку для eGov Mobile и после
+подписи входит под пользователем, к которому привязан ИИН из сертификата подписанта, а
+если такого нет — регистрирует его. Подписанный документ SHALL содержать ровно challenge и
+nonce, созданные сервером для этого потока; поток одноразовый и живёт 5 минут.
+
+#### Scenario: Вход по QR
+- **GIVEN** у пользователя «asel» привязан ИИН 900101300126 и вход ему разрешён
+- **WHEN** он выбирает «Войти через eGov» и подписывает QR в eGov Mobile
+- **THEN** он входит в Пеппу как «asel»
+
+#### Scenario: ИИН не привязан
+- **WHEN** QR подписал человек «ИВАНОВА АЙГЕРИМ», чей ИИН не привязан ни к одному пользователю
+- **THEN** создаётся пользователь «aigerim.ivanova» без Gitea и без пароля, с этим ИИН, и человек входит под ним
+- **AND** следующий вход по тому же ИИН попадает в ту же учётку
+
+#### Scenario: Подменённый документ
+- **WHEN** в подписанном XML нет challenge или nonce этого потока
+- **THEN** вход отклонён, поток удалён
+
+#### Scenario: Отказ или истечение
+- **WHEN** пользователь отменил подпись в eGov Mobile или QR истёк
+- **THEN** страница входа показывает причину и предлагает новый QR
+
+#### Scenario: Отключённая учётка
+- **WHEN** QR подписал человек, чья учётка отключена суперадмином
+- **THEN** вход отклонён, новая учётка не создаётся
+
+### Requirement: Привязка ИИН
+Пользователь без привязанного ИИН (учётка, созданная до PEP-71) SHALL привязывать его,
+подписав QR в «Настройках → eGov». Отвязать ИИН в вебе нельзя. Один ИИН привязан не больше
+чем к одной учётке.
+
+#### Scenario: Привязка
+- **GIVEN** пользователь вошёл, ИИН у него не привязан
+- **WHEN** он нажимает «Привязать eGov» и подписывает QR
+- **THEN** в «Настройках» виден его ИИН (частично скрытый) и дальше он входит через eGov
+
+#### Scenario: ИИН уже занят
+- **WHEN** пользователь подписывает QR ИИН, привязанным к другой учётке
+- **THEN** привязка отклонена
+
+## ADDED Requirements
+
+### Requirement: Пользователи платформы
+Суперадмин (логин в `platform.admins`) SHALL видеть в разделе «Пользователи» всех
+пользователей с привязанным ИИН (частично скрытым) и отключать или включать их; остальным
+раздел недоступен. Администратор машины SHALL управлять пользователями через CLI
+`peppa user add|passwd|disable|enable|egov`.
+
+#### Scenario: Не суперадмин
+- **WHEN** пользователь не из `platform.admins` открывает «Пользователи» или отправляет действие раздела
+- **THEN** он получает «не найдено», данные не меняются
+
+#### Scenario: Отключённый пользователь
+- **GIVEN** пользователь «kate» вошла в веб и подключила MCP-клиент
+- **WHEN** суперадмин отключает её
+- **THEN** её следующий запрос к вебу ведёт на страницу входа, запрос MCP-клиента получает 401
+- **AND** войти через eGov она не может
+
+### Requirement: Агенты самозарегистрированных пользователей
+Проект, владелец которого зарегистрировался сам через eGov (учётка без Gitea и без пароля) и
+не является админом платформы или разрешённым логином, SHALL запускать агентов только на
+подписках пула проекта, а не на входе машины.
+
+#### Scenario: Нет пула
+- **GIVEN** «aigerim.ivanova» зарегистрировалась через eGov и создала проект без пула подписок
+- **WHEN** стори проекта переносят в «В работе»
+- **THEN** агент не запускается, и показывается, что нужен пул подписок от администратора
+
+## REMOVED Requirements
+
+### Requirement: Вход через Gitea
+**Reason**: PEP-71 — единственный способ входа в веб теперь eGov.
+**Migration**: учётки Gitea привязывают ИИН в «Настройках» или через `peppa user egov <ИИН>`; токены Gitea у старых учёток остаются для операций с репозиториями.
+
+### Requirement: Вход по логину и паролю
+**Reason**: PEP-71 — вход только через eGov.
+**Migration**: локальные пользователи привязывают ИИН (`peppa user egov`); аварийный вход — `peppa web login-link`.
+
+### Requirement: Управление локальными пользователями
+**Reason**: PEP-71 — учётки создаются сами при первом входе через eGov; создание и пароли в вебе убраны.
+**Migration**: см. «Пользователи платформы»; CLI `peppa user` остаётся.
+
+### Requirement: Смена своего пароля
+**Reason**: паролей для входа в веб больше нет.
+**Migration**: не требуется.
+
+### Requirement: Логины Gitea не склеиваются с локальными
+**Reason**: входа через Gitea больше нет.
+**Migration**: не требуется.
diff --git a/openspec/changes/pep-71-egov-only-login/tasks.md b/openspec/changes/pep-71-egov-only-login/tasks.md
new file mode 100644
index 00000000..d28ddc00
--- /dev/null
+++ b/openspec/changes/pep-71-egov-only-login/tasks.md
@@ -0,0 +1,14 @@
+## 1. Ядро
+- [x] 1.1 `registerEgovUser` + `egovLoginBase` (транслит кириллицы и казахских букв), `completeEgovFlow` регистрирует неизвестный ИИН, `lastLoginAt`
+- [x] 1.2 `mayUseMachineLogin` и проверка в `startSession`: без пула агенты самозарегистрированного владельца не запускаются
+
+## 2. Веб
+- [x] 2.1 `/login` — только eGov; удалить `/auth/start`, `/auth/callback`, `/auth/password`
+- [x] 2.2 «Настройки»: учётка и привязка ИИН только без ИИН; убрать смену пароля и отвязку
+- [x] 2.3 «Пользователи»: список с ИИН, отключить/включить; убрать создание и сброс пароля
+- [x] 2.4 Справка и AGENTS.md
+
+## 3. Проверка
+- [x] 3.1 Тесты `egov.test.ts`: регистрация, повторный вход, суффикс логина, логин из имени, машинный вход
+- [x] 3.2 typecheck, e2e
+- [ ] 3.3 Выкатка; привязать ИИН PM к его учётке
diff --git a/packages/core/src/access.ts b/packages/core/src/access.ts
index 3e5d0181..a9487f09 100644
--- a/packages/core/src/access.ts
+++ b/packages/core/src/access.ts
@@ -47,3 +47,19 @@ export async function giteaLoginRefusal(db: Db, login: string): Promise {
+ if (ownerId == null) return true;
+ const [owner] = await db.select().from(users).where(eq(users.id, ownerId));
+ if (!owner || owner.disabledAt) return false;
+ if (!(owner.giteaId < 0 && !owner.passwordHash)) return true;
+ const login = owner.login.toLowerCase();
+ const admins = (await getSetting(db, "platform.admins")) ?? (await allowedLogins(db));
+ return admins.includes(login) || (await allowedLogins(db)).includes(login);
+}
diff --git a/packages/core/src/egov.ts b/packages/core/src/egov.ts
index c513fda9..2f82ecd5 100644
--- a/packages/core/src/egov.ts
+++ b/packages/core/src/egov.ts
@@ -2,8 +2,8 @@
// short-lived , reads the signed XML from the relay itself and takes
// the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is
// trusted (PM decision, see openspec design); the challenge and nonce never leave the server.
-import { randomBytes, randomUUID } from "node:crypto";
-import { eq } from "drizzle-orm";
+import { randomBytes, randomInt, randomUUID } from "node:crypto";
+import { eq, sql } from "drizzle-orm";
import { users, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { hashToken } from "./crypto.ts";
@@ -98,12 +98,15 @@ export interface EgovIdentity {
name: string | null;
}
-export type EgovResult = { purpose: "login"; user: User; identity: EgovIdentity } | { purpose: "link"; user: User; identity: EgovIdentity };
+export type EgovResult =
+ | { purpose: "login"; user: User; identity: EgovIdentity; /** PEP-71: the account was registered by this login. */ created: boolean }
+ | { purpose: "link"; user: User; identity: EgovIdentity };
/**
* Finishes a signed flow (one-shot: the flow is removed whatever happens): checks that the
* signed XML carries this flow's challenge and nonce, reads the signer's IIN, then logs in the
- * account the IIN is linked to, or links it to the flow's account.
+ * account the IIN is linked to (PEP-71: registering one for an unknown IIN), or links it to the
+ * flow's account.
*/
export async function completeEgovFlow(db: Db, handle: string): Promise {
const flow = await loadFlow(db, handle);
@@ -118,8 +121,64 @@ export async function completeEgovFlow(db: Db, handle: string): Promise {
+ const base = egovLoginBase(identity);
+ for (let n = 1; n < 1000; n++) {
+ const suffix = n === 1 ? "" : `-${n}`;
+ const login = base.slice(0, 39 - suffix.length).replace(/[._-]+$/, "") + suffix;
+ const [taken] = await db.select({ id: users.id }).from(users).where(sql`lower(${users.login}) = ${login}`);
+ if (taken) continue;
+ for (let i = 0; i < 5; i++) {
+ const [row] = await db
+ .insert(users)
+ .values({ giteaId: -1 - randomInt(2 ** 47), login, name: displayName(identity.name), egovIin: identity.iin, egovLinkedAt: new Date() })
+ .onConflictDoNothing()
+ .returning();
+ if (row) return row;
+ // Lost a race: the same IIN was registered meanwhile — that account is the answer.
+ const [same] = await db.select().from(users).where(eq(users.egovIin, identity.iin));
+ if (same) return same;
+ }
+ }
+ throw new PeppaError("Не удалось создать пользователя");
+}
+
+const TRANSLIT: Record = {
+ а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "i", к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s",
+ т: "t", у: "u", ф: "f", х: "kh", ц: "ts", ч: "ch", ш: "sh", щ: "shch", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya",
+ ә: "a", ғ: "g", қ: "k", ң: "n", ө: "o", ұ: "u", ү: "u", һ: "h", і: "i",
+};
+
+/** "ИВАНОВА АСЕЛЬ" → "asel.ivanova"; no usable name → "user-". */
+export function egovLoginBase(identity: EgovIdentity): string {
+ const words = (identity.name ?? "")
+ .toLowerCase()
+ .split(/\s+/)
+ .map((w) => [...w].map((c) => TRANSLIT[c] ?? (/[a-z0-9]/.test(c) ? c : "")).join(""))
+ .filter(Boolean);
+ // NCA certificates: "SURNAME GIVEN [PATRONYMIC]" — given name first reads better as a login.
+ const parts = words.length >= 2 ? [words[1]!, words[0]!] : words;
+ const login = parts.join(".").slice(0, 39);
+ return /^[a-z0-9][a-z0-9._-]{1,38}$/.test(login) ? login : `user-${identity.iin.slice(8)}`;
+}
+
+/** "ИВАНОВА АСЕЛЬ" → "Асель Иванова" for the UI. */
+function displayName(name: string | null): string | null {
+ const words = (name ?? "").trim().split(/\s+/).filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1).toLowerCase());
+ if (!words.length) return null;
+ return (words.length >= 2 ? [words[1], words[0], ...words.slice(2)] : words).join(" ");
}
/** The trust check (relay trusted): our challenge and nonce are in the signed XML; signer from the certificate. */
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 69457cc3..20876aa6 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -6,6 +6,7 @@ import {
getAutonomy,
getBudgetState,
getSubscription,
+ mayUseMachineLogin,
pickSubscription,
createSession,
expireSessionQuestions,
@@ -141,6 +142,10 @@ export async function startRunner(
fallback = { from: wanted ?? null, reason: (e as Error).message };
}
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
+ // PEP-71: self-registered (eGov) users don't get this machine's login for free.
+ if (!sub && !sandboxed && !(await mayUseMachineLogin(db, project.ownerId))) {
+ throw new PeppaError("У проекта нет пула подписок — агенты не запустятся. Попросите администратора назначить пул в «⋯ Настройки проекта»");
+ }
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError("Для запуска агента в контейнере нужна подписка: добавьте её в пул проекта (раздел «Подписки»)");
if (host && provider === "codex") throw new PeppaError("Codex на удалённом хосте пока не поддерживается — выберите подписку Claude или OpenCode");
diff --git a/packages/testkit/test/egov.test.ts b/packages/testkit/test/egov.test.ts
index 374704e6..c1d7f598 100644
--- a/packages/testkit/test/egov.test.ts
+++ b/packages/testkit/test/egov.test.ts
@@ -1,5 +1,5 @@
-// PEP-65: eGov QR login through the KazEDS relay (mock-kazeds-relay): link an IIN, log in by it,
-// unknown IIN, tampered document, refusal, expiry, IIN taken by another account.
+// PEP-65/71: eGov QR login through the KazEDS relay (mock-kazeds-relay): link an IIN, log in by it,
+// unknown IIN registers an account, tampered document, refusal, expiry, IIN taken by another account.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { core, db, teardown } from "./helpers.ts";
@@ -35,13 +35,54 @@ describe("eGov QR", () => {
assert.ok(!core.isValidIin("900101300123"));
});
- test("unlinked IIN: signed, but no login", async () => {
+ test("unknown IIN: the first login registers the account, the next one finds it (PEP-71)", async () => {
+ relay.signer = { iin: "850505400008", name: "ИВАНОВА ӘЙГЕРІМ ҚАЙРАТҚЫЗЫ" };
const f = await core.startEgovFlow(db, "login");
assert.match(f.qrContent, /^mobileSign:/);
assert.match(f.deeplink, /^https:\/\/m\.egov\.kz\//);
await scanAndSign(f.handle);
- await assert.rejects(core.completeEgovFlow(db, f.handle), /не привязан к Пеппе/);
+ const r = await core.completeEgovFlow(db, f.handle);
+ assert.equal(r.purpose, "login");
+ assert.ok(r.purpose === "login" && r.created);
+ assert.equal(r.user.login, "aigerim.ivanova");
+ assert.equal(r.user.name, "Әйгерім Иванова Қайратқызы");
+ assert.equal(r.user.egovIin, "850505400008");
+ assert.ok(r.user.giteaId < 0 && !r.user.passwordHash, "a Peppa account without Gitea and password");
+ assert.ok(core.isLocalUser(r.user));
+ assert.ok(await core.isUserAllowed(db, r.user));
await assert.rejects(core.completeEgovFlow(db, f.handle), /истёк/, "one-shot");
+
+ const again = await core.startEgovFlow(db, "login");
+ await scanAndSign(again.handle);
+ const r2 = await core.completeEgovFlow(db, again.handle);
+ assert.ok(r2.purpose === "login" && !r2.created);
+ assert.equal(r2.user.id, r.user.id);
+ assert.ok((await core.getUser(db, r.user.id))!.lastLoginAt);
+
+ // Same name, other person → the login gets a suffix.
+ relay.signer = { iin: "850505400018", name: "ИВАНОВА АЙГЕРИМ" };
+ const other = await core.startEgovFlow(db, "login");
+ await scanAndSign(other.handle);
+ const r3 = await core.completeEgovFlow(db, other.handle);
+ assert.equal(r3.user.login, "aigerim.ivanova-2");
+ relay.signer = { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" };
+ });
+
+ test("login from the certificate name", () => {
+ assert.equal(core.egovLoginBase({ iin: "850505400028", name: "ТЕСТОВ ТЕСТ" }), "test.testov");
+ assert.equal(core.egovLoginBase({ iin: "850505400028", name: "ЖҰМАБЕК" }), "zhumabek");
+ assert.equal(core.egovLoginBase({ iin: "850505400028", name: null }), "user-0028");
+ assert.equal(core.egovLoginBase({ iin: "850505400028", name: "*** ###" }), "user-0028");
+ });
+
+ test("self-registered owner without a pool: no machine login for agents", async () => {
+ const self = await core.registerEgovUser(db, { iin: "850505400028", name: "ПУЛОВ БЕЗ" });
+ assert.equal(await core.mayUseMachineLogin(db, self.id), false);
+ assert.equal(await core.mayUseMachineLogin(db, asel.id), true, "Gitea account");
+ assert.equal(await core.mayUseMachineLogin(db, null), true, "platform project");
+ await core.setPlatformAdmins(db, ["bez.pulov"]);
+ assert.equal(await core.mayUseMachineLogin(db, self.id), true, "an admin may");
+ await core.setPlatformAdmins(db, null);
});
test("link from Settings, then log in by eGov", async () => {
--
2.45.2
From bd931c1c026f15a9affb439bf55642d036bab342 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 18:03:27 +0500
Subject: [PATCH 006/439] PEP-71: archive openspec change
Co-Authored-By: Claude Opus 5.5
---
.../proposal.md | 0
.../specs/web-auth/spec.md | 0
.../tasks.md | 2 +-
openspec/specs/web-auth/spec.md | 132 ++++++------------
4 files changed, 44 insertions(+), 90 deletions(-)
rename openspec/changes/{pep-71-egov-only-login => archive/2026-11-14-pep-71-egov-only-login}/proposal.md (100%)
rename openspec/changes/{pep-71-egov-only-login => archive/2026-11-14-pep-71-egov-only-login}/specs/web-auth/spec.md (100%)
rename openspec/changes/{pep-71-egov-only-login => archive/2026-11-14-pep-71-egov-only-login}/tasks.md (94%)
diff --git a/openspec/changes/pep-71-egov-only-login/proposal.md b/openspec/changes/archive/2026-11-14-pep-71-egov-only-login/proposal.md
similarity index 100%
rename from openspec/changes/pep-71-egov-only-login/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-71-egov-only-login/proposal.md
diff --git a/openspec/changes/pep-71-egov-only-login/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-71-egov-only-login/specs/web-auth/spec.md
similarity index 100%
rename from openspec/changes/pep-71-egov-only-login/specs/web-auth/spec.md
rename to openspec/changes/archive/2026-11-14-pep-71-egov-only-login/specs/web-auth/spec.md
diff --git a/openspec/changes/pep-71-egov-only-login/tasks.md b/openspec/changes/archive/2026-11-14-pep-71-egov-only-login/tasks.md
similarity index 94%
rename from openspec/changes/pep-71-egov-only-login/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-71-egov-only-login/tasks.md
index d28ddc00..ea258b22 100644
--- a/openspec/changes/pep-71-egov-only-login/tasks.md
+++ b/openspec/changes/archive/2026-11-14-pep-71-egov-only-login/tasks.md
@@ -11,4 +11,4 @@
## 3. Проверка
- [x] 3.1 Тесты `egov.test.ts`: регистрация, повторный вход, суффикс логина, логин из имени, машинный вход
- [x] 3.2 typecheck, e2e
-- [ ] 3.3 Выкатка; привязать ИИН PM к его учётке
+- [x] 3.3 Выкатка; привязать ИИН PM к его учётке
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index 4380dad9..1a020322 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -5,18 +5,6 @@
## Requirements
-### Requirement: Вход через Gitea
-Веб SHALL пускать пользователя только после авторизации через OAuth2 Gitea, на которой
-размещены репозитории Пеппы. Пользователь Пеппы однозначно соответствует аккаунту Gitea.
-
-#### Scenario: Первый вход
-- **WHEN** неавторизованный пользователь открывает любую страницу веба
-- **THEN** он попадает на страницу входа, а после подтверждения в Gitea возвращается в веб авторизованным, и для него создаётся пользователь Пеппы с логином, именем и аватаром из Gitea
-
-#### Scenario: Подделка или повтор колбэка
-- **WHEN** колбэк OAuth приходит без корректного `state` текущего браузера или с уже использованным кодом
-- **THEN** вход не выполняется и показывается ошибка
-
### Requirement: Закрытый веб
Все страницы и действия веба, кроме страницы входа и колбэка OAuth, SHALL требовать
действующую сессию. Сессия хранится в подписанной httpOnly cookie и истекает через 30 дней.
@@ -83,11 +71,11 @@
- **AND** запрос её MCP-клиента получает 401
### Requirement: Вход через eGov QR
-Страница входа SHALL предлагать «Войти через eGov»: Пеппа создаёт сессию подписи в relay
-KazEDS, показывает QR и ссылку для eGov Mobile и после подписи входит под пользователем,
-к которому привязан ИИН из сертификата подписанта. Подписанный документ SHALL содержать
-ровно challenge и nonce, созданные сервером для этого потока; поток одноразовый и живёт
-5 минут.
+Страница входа SHALL предлагать единственный способ входа — «Войти через eGov»: Пеппа
+создаёт сессию подписи в relay KazEDS, показывает QR и ссылку для eGov Mobile и после
+подписи входит под пользователем, к которому привязан ИИН из сертификата подписанта, а
+если такого нет — регистрирует его. Подписанный документ SHALL содержать ровно challenge и
+nonce, созданные сервером для этого потока; поток одноразовый и живёт 5 минут.
#### Scenario: Вход по QR
- **GIVEN** у пользователя «asel» привязан ИИН 900101300126 и вход ему разрешён
@@ -95,8 +83,9 @@ KazEDS, показывает QR и ссылку для eGov Mobile и после
- **THEN** он входит в Пеппу как «asel»
#### Scenario: ИИН не привязан
-- **WHEN** QR подписал человек, чей ИИН не привязан ни к одному пользователю
-- **THEN** вход отклонён с подсказкой привязать eGov в «Настройках» после входа через Gitea
+- **WHEN** QR подписал человек «ИВАНОВА АЙГЕРИМ», чей ИИН не привязан ни к одному пользователю
+- **THEN** создаётся пользователь «aigerim.ivanova» без Gitea и без пароля, с этим ИИН, и человек входит под ним
+- **AND** следующий вход по тому же ИИН попадает в ту же учётку
#### Scenario: Подменённый документ
- **WHEN** в подписанном XML нет challenge или nonce этого потока
@@ -106,85 +95,24 @@ KazEDS, показывает QR и ссылку для eGov Mobile и после
- **WHEN** пользователь отменил подпись в eGov Mobile или QR истёк
- **THEN** страница входа показывает причину и предлагает новый QR
+#### Scenario: Отключённая учётка
+- **WHEN** QR подписал человек, чья учётка отключена суперадмином
+- **THEN** вход отклонён, новая учётка не создаётся
+
### Requirement: Привязка ИИН
-Пользователь SHALL привязывать к своей учётке ИИН, подписав QR в «Настройках → eGov», и
-отвязывать его там же. Один ИИН привязан не больше чем к одной учётке.
+Пользователь без привязанного ИИН (учётка, созданная до PEP-71) SHALL привязывать его,
+подписав QR в «Настройках → eGov». Отвязать ИИН в вебе нельзя. Один ИИН привязан не больше
+чем к одной учётке.
#### Scenario: Привязка
-- **GIVEN** пользователь вошёл через Gitea
+- **GIVEN** пользователь вошёл, ИИН у него не привязан
- **WHEN** он нажимает «Привязать eGov» и подписывает QR
-- **THEN** в «Настройках» виден его ИИН (частично скрытый) и дальше он может входить через eGov
+- **THEN** в «Настройках» виден его ИИН (частично скрытый) и дальше он входит через eGov
#### Scenario: ИИН уже занят
- **WHEN** пользователь подписывает QR ИИН, привязанным к другой учётке
- **THEN** привязка отклонена
-### Requirement: Вход по логину и паролю
-Страница входа SHALL предлагать вход по логину и паролю для локальных пользователей Пеппы
-(без аккаунта Gitea). Пароль хранится только как хэш scrypt с солью. Любая причина
-отказа (нет логина, нет пароля, неверный пароль, пользователь отключён) SHALL давать одно
-и то же сообщение «Неверный логин или пароль». После 5 неудачных попыток по логину или
-20 по IP за 15 минут вход по паролю приостанавливается на 15 минут.
-
-#### Scenario: Вход по паролю
-- **GIVEN** суперадмин создал локального пользователя «admin» с паролем
-- **WHEN** admin вводит логин и пароль на странице входа
-- **THEN** он входит в Пеппу без Gitea
-
-#### Scenario: Неверный пароль
-- **GIVEN** локальный пользователь «kate»
-- **WHEN** на странице входа введён логин «kate» и неверный пароль
-- **THEN** вход отклонён с сообщением «Неверный логин или пароль»
-- **AND** для несуществующего логина сообщение такое же
-
-#### Scenario: Пауза после 5 попыток
-- **GIVEN** для логина «kate» было 5 неудачных попыток за 15 минут
-- **WHEN** вводится даже верный пароль
-- **THEN** вход отклонён с сообщением о слишком частых попытках
-
-### Requirement: Управление локальными пользователями
-Суперадмин (логин в `platform.admins`) SHALL создавать локальных пользователей (логин,
-имя, временный пароль), сбрасывать им пароль и отключать или включать пользователей в
-разделе «Пользователи»; остальным раздел недоступен. Администратор машины SHALL делать
-то же через CLI `peppa user add|passwd|disable|enable`. Логин локального пользователя
-уникален в Пеппе.
-
-#### Scenario: Создание пользователя
-- **GIVEN** суперадмин «admin»
-- **WHEN** он создаёт пользователя «kate» с временным паролем
-- **THEN** kate может войти по этому паролю
-
-#### Scenario: Не суперадмин
-- **WHEN** пользователь не из `platform.admins` открывает «Пользователи» или отправляет действие раздела
-- **THEN** он получает «не найдено», данные не меняются
-
-#### Scenario: Отключённый пользователь
-- **GIVEN** пользователь «kate» вошла в веб и подключила MCP-клиент
-- **WHEN** суперадмин отключает её
-- **THEN** её следующий запрос к вебу ведёт на страницу входа, запрос MCP-клиента получает 401
-- **AND** войти по паролю она не может
-
-### Requirement: Смена своего пароля
-Локальный пользователь SHALL менять свой пароль в «Настройках», указав текущий и новый
-(не короче 8 символов).
-
-#### Scenario: Смена пароля
-- **WHEN** kate вводит текущий пароль и новый
-- **THEN** дальше она входит только по новому паролю
-
-#### Scenario: Неверный текущий пароль
-- **WHEN** текущий пароль указан неверно
-- **THEN** пароль не меняется и показывается ошибка
-
-### Requirement: Логины Gitea не склеиваются с локальными
-Вход через Gitea SHALL отклоняться, если логин аккаунта Gitea занят локальным
-пользователем Пеппы.
-
-#### Scenario: Логин занят локальным пользователем
-- **GIVEN** локальный пользователь «kate»
-- **WHEN** аккаунт Gitea «kate» проходит вход через Gitea
-- **THEN** сессия не создаётся и показывается, что логин занят локальным пользователем Пеппы
-
### Requirement: Возможности локального пользователя
Локальный пользователь SHALL работать с досками, задачами и вопросами своих проектов и
быть участником чужих (добавляется по логину Пеппы, без доступа к репозиторию в Gitea).
@@ -195,3 +123,29 @@ KazEDS, показывает QR и ссылку для eGov Mobile и после
- **GIVEN** владелец проекта «PAY» и локальный пользователь «kate»
- **WHEN** владелец добавляет «kate» в участники
- **THEN** kate видит проект «PAY», соавтором репозитория в Gitea она не становится
+
+### Requirement: Пользователи платформы
+Суперадмин (логин в `platform.admins`) SHALL видеть в разделе «Пользователи» всех
+пользователей с привязанным ИИН (частично скрытым) и отключать или включать их; остальным
+раздел недоступен. Администратор машины SHALL управлять пользователями через CLI
+`peppa user add|passwd|disable|enable|egov`.
+
+#### Scenario: Не суперадмин
+- **WHEN** пользователь не из `platform.admins` открывает «Пользователи» или отправляет действие раздела
+- **THEN** он получает «не найдено», данные не меняются
+
+#### Scenario: Отключённый пользователь
+- **GIVEN** пользователь «kate» вошла в веб и подключила MCP-клиент
+- **WHEN** суперадмин отключает её
+- **THEN** её следующий запрос к вебу ведёт на страницу входа, запрос MCP-клиента получает 401
+- **AND** войти через eGov она не может
+
+### Requirement: Агенты самозарегистрированных пользователей
+Проект, владелец которого зарегистрировался сам через eGov (учётка без Gitea и без пароля) и
+не является админом платформы или разрешённым логином, SHALL запускать агентов только на
+подписках пула проекта, а не на входе машины.
+
+#### Scenario: Нет пула
+- **GIVEN** «aigerim.ivanova» зарегистрировалась через eGov и создала проект без пула подписок
+- **WHEN** стори проекта переносят в «В работе»
+- **THEN** агент не запускается, и показывается, что нужен пул подписок от администратора
--
2.45.2
From a1b3760afd8fbe6d776eaae8d2b2223aaf1ca06d 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 18:15:34 +0500
Subject: [PATCH 007/439] PEP-72: eGov sign-in on the phone itself through the
deep link
Co-Authored-By: Claude Opus 5.5
---
apps/web/app/login/page.tsx | 2 +-
apps/web/components/EgovSign.tsx | 159 ++++++++++++++----
.../proposal.md | 16 ++
.../specs/web-auth/spec.md | 16 ++
.../tasks.md | 3 +
openspec/specs/web-auth/spec.md | 15 ++
6 files changed, 181 insertions(+), 30 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/specs/web-auth/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/tasks.md
diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index e649de5e..58bccf1f 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -18,7 +18,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
Софтвейр-фабрика: проекты в Gitea, стори по OpenSpec, агенты Claude Code и Codex.
- Первый вход сразу создаёт учётку по вашему ИИН. С телефона — кнопка «Открыть в eGov Mobile».
+ Первый вход сразу создаёт учётку по вашему ИИН. На телефоне вход открывает eGov Mobile, QR не нужен.
diff --git a/apps/web/components/EgovSign.tsx b/apps/web/components/EgovSign.tsx
index 5405327d..d0055e39 100644
--- a/apps/web/components/EgovSign.tsx
+++ b/apps/web/components/EgovSign.tsx
@@ -1,9 +1,10 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { QrCode, Smartphone } from "lucide-react";
+import { ChevronDown, QrCode, Smartphone } from "lucide-react";
import { Button } from "@/components/ui/button";
+type Purpose = "login" | "link";
type Phase = { at: "idle" } | { at: "qr"; qr: string; deeplink: string; status: string } | { at: "done" } | { at: "error"; message: string };
const STATUS: Record = {
@@ -11,50 +12,150 @@ const STATUS: Record = {
scanned: "QR отсканирован — подпишите в eGov Mobile",
completed: "Подписано, входим…",
};
+const PHONE_STATUS: Record = {
+ pending: "Откройте eGov Mobile и подпишите вход, потом вернитесь сюда",
+ scanned: "Подпишите в eGov Mobile и вернитесь сюда",
+ completed: "Подписано, входим…",
+};
+
+/** Saved per tab so a phone that reloads the page on return from eGov Mobile picks the flow up again. */
+const SAVED = "peppa.egov.flow";
+interface Saved {
+ purpose: Purpose;
+ qr: string;
+ deeplink: string;
+ expiresAt: number;
+}
+
+function readSaved(purpose: Purpose): Saved | null {
+ try {
+ const s = JSON.parse(sessionStorage.getItem(SAVED) ?? "null") as Saved | null;
+ return s && s.purpose === purpose && s.expiresAt > Date.now() ? s : null;
+ } catch {
+ return null;
+ }
+}
+function writeSaved(s: Saved | null) {
+ try {
+ if (s) sessionStorage.setItem(SAVED, JSON.stringify(s));
+ else sessionStorage.removeItem(SAVED);
+ } catch {
+ /* private mode: no resume, the flow still works */
+ }
+}
+
+const isPhone = () => typeof window !== "undefined" && (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) || (navigator.maxTouchPoints > 1 && /Macintosh/.test(navigator.userAgent)));
/**
- * eGov QR (PEP-65): shows the relay's QR and a deep link for the same phone, polls the flow and
- * finishes it. `login` signs in; `link` binds the IIN to the current account (Settings).
+ * eGov sign-in (PEP-65/72): on a computer — the relay's QR for eGov Mobile; on the phone itself —
+ * a deep link that opens eGov Mobile, with the QR folded away. Polls the flow and finishes it;
+ * `login` signs in (PEP-71: registers on first login), `link` binds the IIN (Settings).
*/
-export function EgovSign({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) {
+export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: string; label: string }) {
const [phase, setPhase] = useState({ at: "idle" });
+ const [phone, setPhone] = useState(false);
+ const [showQr, setShowQr] = useState(false);
const alive = useRef(true);
+ const gen = useRef(0);
+ const wake = useRef<(() => void) | null>(null);
+
+ const fail = (message: string) => {
+ writeSaved(null);
+ if (alive.current) setPhase({ at: "error", message });
+ };
+
+ async function poll() {
+ // One loop at a time: a newer poll (or unmount) bumps the generation and the old one stops.
+ const my = ++gen.current;
+ const stale = () => !alive.current || gen.current !== my;
+ {
+ for (;;) {
+ // Wait 2 s, or less when the tab comes back from eGov Mobile.
+ await new Promise((res) => {
+ const t = setTimeout(res, 2000);
+ wake.current = () => {
+ clearTimeout(t);
+ res();
+ };
+ });
+ wake.current = null;
+ if (stale()) return;
+ const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string };
+ if (stale()) return;
+ if (s.error) return fail(s.error);
+ if (s.status === "expired") return fail("Вход истёк — начните заново");
+ if (s.status === "rejected") return fail("Подписание отменено в eGov Mobile");
+ setPhase((p) => (p.at === "qr" ? { ...p, status: s.status ?? p.status } : p));
+ if (s.status === "completed") break;
+ }
+ const c = await fetch("/auth/egov/complete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ next }) });
+ const done = (await c.json().catch(() => ({}))) as { redirect?: string; error?: string };
+ if (!c.ok || !done.redirect) return fail(done.error ?? "Не удалось войти через eGov");
+ writeSaved(null);
+ setPhase({ at: "done" });
+ window.location.assign(done.redirect);
+ }
+ }
+
// Set on mount too: StrictMode (dev) mounts, unmounts and mounts again.
useEffect(() => {
alive.current = true;
- return () => void (alive.current = false);
+ setPhone(isPhone());
+ const saved = readSaved(purpose);
+ if (saved) {
+ setPhase({ at: "qr", qr: saved.qr, deeplink: saved.deeplink, status: "pending" });
+ void poll().catch((e: Error) => fail(e.message));
+ }
+ const onVisible = () => document.visibilityState === "visible" && wake.current?.();
+ document.addEventListener("visibilitychange", onVisible);
+ window.addEventListener("pageshow", onVisible);
+ return () => {
+ alive.current = false;
+ gen.current++;
+ wake.current?.();
+ document.removeEventListener("visibilitychange", onVisible);
+ window.removeEventListener("pageshow", onVisible);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- once per mount
}, []);
- const fail = (message: string) => alive.current && setPhase({ at: "error", message });
-
async function start() {
const r = await fetch("/auth/egov/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ purpose }) });
- const body = (await r.json()) as { qr?: string; deeplink?: string; error?: string };
- if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось создать QR");
- setPhase({ at: "qr", qr: body.qr, deeplink: body.deeplink ?? "", status: "pending" });
- for (;;) {
- await new Promise((res) => setTimeout(res, 2000));
- const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string };
- if (!alive.current) return;
- if (s.error) return fail(s.error);
- if (s.status === "expired") return fail("QR-код истёк — начните заново");
- if (s.status === "rejected") return fail("Подписание отменено в eGov Mobile");
- setPhase((p) => (p.at === "qr" ? { ...p, status: s.status ?? p.status } : p));
- if (s.status === "completed") break;
- }
- const c = await fetch("/auth/egov/complete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ next }) });
- const done = (await c.json().catch(() => ({}))) as { redirect?: string; error?: string };
- if (!c.ok || !done.redirect) return fail(done.error ?? "Не удалось войти через eGov");
- setPhase({ at: "done" });
- window.location.assign(done.redirect);
+ const body = (await r.json()) as { qr?: string; deeplink?: string; expiresAt?: number; error?: string };
+ if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось начать вход через eGov");
+ const deeplink = body.deeplink ?? "";
+ writeSaved({ purpose, qr: body.qr, deeplink, expiresAt: body.expiresAt ?? Date.now() + 5 * 60_000 });
+ setShowQr(false);
+ setPhase({ at: "qr", qr: body.qr, deeplink, status: "pending" });
+ await poll();
}
if (phase.at === "qr") {
+ const qrBlock = (
+ // eslint-disable-next-line @next/next/no-img-element -- data URL from the server
+
+ );
+ const status = (phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status;
+ if (phone && phase.deeplink) {
+ return (
+
+
+
+ Открыть eGov Mobile
+
+
+
{status}
+
setShowQr((v) => !v)}>
+ {showQr ? "Скрыть QR" : "Войти с другого телефона по QR"}
+
+ {showQr && qrBlock}
+
+ );
+ }
return (
- {/* eslint-disable-next-line @next/next/no-img-element -- data URL from the server */}
-
-
{STATUS[phase.status] ?? phase.status}
+ {qrBlock}
+
{status}
{phase.deeplink && (
@@ -69,7 +170,7 @@ export function EgovSign({ purpose, next, label }: { purpose: "login" | "link";
{phase.at === "error" &&
{phase.message}
}
void start().catch((e: Error) => fail(e.message))}>
- {phase.at === "error" ? "Новый QR" : label}
+ {phone ? : } {phase.at === "error" ? (phone ? "Начать заново" : "Новый QR") : phone ? `${label} Mobile` : label}
);
diff --git a/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/proposal.md b/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/proposal.md
new file mode 100644
index 00000000..28d3b053
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/proposal.md
@@ -0,0 +1,16 @@
+# PEP-72: вход eGov с телефона по диплинку
+
+## Why
+Когда входишь с того же телефона, где стоит eGov Mobile, QR бесполезен: отсканировать свой же экран нельзя.
+Кнопка «Открыть в eGov Mobile» пряталась под QR. А мобильный браузер, пока подписываешь в eGov, может выгрузить вкладку,
+и после возврата вход приходится начинать заново.
+
+## What Changes
+- `EgovSign` на телефоне (UA Android/iOS/iPadOS): главная кнопка «Войти через eGov Mobile», затем крупная ссылка «Открыть eGov Mobile»
+ (диплинк relay). QR свёрнут под «Войти с другого телефона по QR». На компьютере всё как раньше.
+- Поток сохраняется в `sessionStorage` вкладки (QR, диплинк, срок; handle остаётся в httpOnly cookie). После перезагрузки
+ страница продолжает опрос; при возврате на вкладку (`visibilitychange`/`pageshow`) статус проверяется сразу.
+- Опрос — один цикл на компонент (счётчик поколений), без дублей при двойном монтировании StrictMode.
+
+## Impact
+`apps/web/components/EgovSign.tsx`, текст на `/login`. Сервер и relay не меняются.
diff --git a/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/specs/web-auth/spec.md
new file mode 100644
index 00000000..9feef373
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/specs/web-auth/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Вход eGov с телефона
+На телефоне страница входа SHALL вести вход через ссылку, открывающую eGov Mobile, а QR
+показывать только по запросу. Начатый вход SHALL продолжаться после возврата из eGov Mobile,
+даже если браузер перезагрузил страницу, пока поток не истёк.
+
+#### Scenario: Вход на том же телефоне
+- **GIVEN** человек открыл страницу входа в браузере телефона
+- **WHEN** он нажимает «Войти через eGov Mobile», затем «Открыть eGov Mobile» и подписывает
+- **THEN** после возврата в браузер он входит без QR
+
+#### Scenario: Браузер перезагрузил страницу
+- **GIVEN** вход начат, человек ушёл в eGov Mobile, браузер выгрузил вкладку
+- **WHEN** он возвращается, и страница загружается заново
+- **THEN** страница продолжает тот же вход и после подписи впускает его
diff --git a/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/tasks.md b/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/tasks.md
new file mode 100644
index 00000000..9141ecb0
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-72-egov-phone-deeplink/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 Телефонный вид `EgovSign`: диплинк главный, QR свёрнут
+- [x] 2 Продолжение потока после перезагрузки и при возврате на вкладку
+- [x] 3 Проверка в браузере (мобильный и десктопный вид, перезагрузка, один опрос раз в 2 с)
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index 1a020322..552b8730 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -149,3 +149,18 @@ nonce, созданные сервером для этого потока; по
- **GIVEN** «aigerim.ivanova» зарегистрировалась через eGov и создала проект без пула подписок
- **WHEN** стори проекта переносят в «В работе»
- **THEN** агент не запускается, и показывается, что нужен пул подписок от администратора
+
+### Requirement: Вход eGov с телефона
+На телефоне страница входа SHALL вести вход через ссылку, открывающую eGov Mobile, а QR
+показывать только по запросу. Начатый вход SHALL продолжаться после возврата из eGov Mobile,
+даже если браузер перезагрузил страницу, пока поток не истёк.
+
+#### Scenario: Вход на том же телефоне
+- **GIVEN** человек открыл страницу входа в браузере телефона
+- **WHEN** он нажимает «Войти через eGov Mobile», затем «Открыть eGov Mobile» и подписывает
+- **THEN** после возврата в браузер он входит без QR
+
+#### Scenario: Браузер перезагрузил страницу
+- **GIVEN** вход начат, человек ушёл в eGov Mobile, браузер выгрузил вкладку
+- **WHEN** он возвращается, и страница загружается заново
+- **THEN** страница продолжает тот же вход и после подписи впускает его
--
2.45.2
From cdc7e62bfcfc7f1eec6391dc4610cbaee57a4771 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 18:25:40 +0500
Subject: [PATCH 008/439] =?UTF-8?q?PEP-73:=20project=20tab=20AGENTS.md=20?=
=?UTF-8?q?=E2=80=94=20read=20and=20edit=20the=20agents'=20prompt?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/web/app/(app)/actions.ts | 12 ++-
apps/web/app/(app)/p/[key]/page.tsx | 12 ++-
apps/web/app/(app)/p/[key]/tabs.tsx | 89 ++++++++++++++++++-
.../proposal.md | 20 +++++
.../specs/web-workspace/spec.md | 16 ++++
.../2026-11-14-pep-73-agents-md-tab/tasks.md | 4 +
openspec/specs/web-workspace/spec.md | 15 ++++
packages/core/src/gitea.ts | 17 ++++
packages/db/scripts/export-epics.ts | 47 ++++++++++
packages/runner/src/agents-md.ts | 85 ++++++++++++++++++
packages/runner/src/index.ts | 1 +
packages/testkit/src/mock-gitea.ts | 35 +++++++-
packages/testkit/test/project-tabs.test.ts | 32 +++++++
13 files changed, 373 insertions(+), 12 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md
create mode 100644 packages/db/scripts/export-epics.ts
create mode 100644 packages/runner/src/agents-md.ts
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 1a752add..96ae9a2a 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -650,3 +650,13 @@ export async function checkGiteaTokenAction(f: FormData) {
return `/secrets?gitea=${encodeURIComponent(r.ok ? `ok:${r.login}` : r.problems.join("; "))}`;
});
}
+
+// ── PEP-73: the project's AGENTS.md ──────────────────────────────────────────────
+export async function saveAgentsMdAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await saveAgentsMd(db, user, p, String(f.get("text") ?? ""), str(f, "sha") || null);
+ return `/p/${p.key}?tab=agents&saved=1`;
+ });
+}
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 12d11fea..f5588070 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,6 +1,6 @@
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 { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
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";
@@ -22,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, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
+import { AgentsMdTab, 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";
@@ -39,6 +39,7 @@ const TABS = [
{ id: "board", label: "Доска" },
{ id: "code", label: "Код" },
{ id: "specs", label: "Спеки" },
+ { id: "agents", label: "AGENTS.md" },
{ id: "pulls", label: "PR" },
{ id: "releases", label: "Релизы" },
{ id: "bugs", label: "Баги" },
@@ -67,10 +68,10 @@ function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
);
}
-export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string }> }) {
+export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string }> }) {
const user = await requireUser();
const { key } = await params;
- const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel } = await searchParams;
+ const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams;
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
@@ -129,6 +130,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 agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
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;
@@ -423,6 +425,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
>
)}
+ {tab === "agents" && agentsMd && }
+
{tab === "pulls" && pulls && }
{tab === "releases" && (
diff --git a/apps/web/app/(app)/p/[key]/tabs.tsx b/apps/web/app/(app)/p/[key]/tabs.tsx
index 02c89b07..24bcc62b 100644
--- a/apps/web/app/(app)/p/[key]/tabs.tsx
+++ b/apps/web/app/(app)/p/[key]/tabs.tsx
@@ -1,11 +1,11 @@
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
-import { Archive, ExternalLink, GitBranch, GitPullRequest } from "lucide-react";
+import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
import type { Epic, SpecSummary } from "@peppa/core";
import { Markdown } from "@/components/Markdown";
-import type { OpenPull, RepoOverview } from "@peppa/runner";
-import { addEpic, editEpic } from "../../actions";
+import type { AgentsMd, OpenPull, RepoOverview } from "@peppa/runner";
+import { addEpic, editEpic, saveAgentsMdAction } from "../../actions";
import { Hidden } from "@/components/cards";
-import { Disclosure, Empty, Key, Section, StatusBadge } from "@/components/common";
+import { Disclosure, Empty, Key, Notice, Section, StatusBadge } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
@@ -231,3 +231,84 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
);
}
+
+/** PEP-73: the project's AGENTS.md — prompt and standards every agent follows; read and edit. */
+export function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projectId: number; projectKey: string; md: AgentsMd; edit: boolean; saved: boolean }) {
+ const tabHref = `/p/${projectKey}?tab=agents`;
+ const gitea = (
+
+
+ В Gitea
+
+
+ );
+ if (md.error) {
+ return (
+
+ );
+ }
+ if (edit) {
+ return (
+
+
+
+
+
+
Сохранить в {md.branch}
+
+ Отмена
+
+
Коммит в ветку {md.branch} от вашего имени. Новые и перезапущенные агенты прочитают его сразу.
+
+
+
+ );
+ }
+ return (
+
+
+
+ Изменить
+
+
+ {gitea}
+ >
+ }
+ >
+ {saved && AGENTS.md сохранён в {md.branch} }
+
+ Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила
+ Пеппы добавляются сами.
+
+ {md.text.trim() ? (
+
+
+
+ ) : (
+ В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.
+ )}
+
+ );
+}
+
+const AGENTS_MD_STARTER = `# AGENTS.md
+
+Проект ведётся софтвейр-фабрикой **Пеппа**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы;
+здесь — только стандарты этого проекта.
+
+## Стек и команды
+
+
+## Соглашения
+
+
+## Перед PR
+- Тесты и линтеры проходят.
+- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
+ новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
+`;
diff --git a/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md
new file mode 100644
index 00000000..d5261b29
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md
@@ -0,0 +1,20 @@
+# PEP-73: вкладка AGENTS.md в проекте
+
+## Why
+PM хочет задавать проекту стандарты, которым следуют все агенты, — по сути промпт проекта (стек, соглашения, этапы
+вроде проверки ИБ перед PR). Такой файл уже есть: `AGENTS.md`. Claude читает его через `CLAUDE.md`, Codex и OpenCode — сами.
+Но правка доступна только через git.
+
+## What Changes
+- Вкладка «AGENTS.md» рядом с Доской/Кодом/Спеками: файл из ветки по умолчанию в Gitea (не рабочей копии), Markdown,
+ «Изменить» → редактор → «Сохранить в main». Это один коммит через contents API Gitea от имени пользователя (клиент владельца,
+ затем peppa-bot), событие `agents_md_updated` в журнале.
+- Защита от перезаписи: сохранение идёт против blob sha, с которого начали; файл изменился — отказ «изменили, пока вы редактировали».
+ Предел — 64 КБ. Нет файла — редактор открывается с заготовкой (стек, соглашения, «Перед PR» с чек-листом ИБ).
+- После сохранения рабочая копия проекта делает fast-forward, если она свободна, чистая и на main.
+
+Вне scope: CI-сканер ИБ (gitleaks/semgrep) — отдельная стори.
+
+## Impact
+`core/gitea.ts` (`fileWithSha`, `writeFile`), `runner/agents-md.ts`, вкладка на странице проекта, `saveAgentsMdAction`,
+`mock-gitea` (POST/PUT contents, sha в GET). Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md
new file mode 100644
index 00000000..cfe4f211
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Вкладка AGENTS.md
+Страница проекта SHALL иметь вкладку «AGENTS.md», которая показывает `AGENTS.md` из ветки
+по умолчанию репозитория проекта и даёт владельцу и участникам изменить его. Сохранение —
+один коммит в ветку по умолчанию от имени пользователя.
+
+#### Scenario: Создать и изменить
+- **GIVEN** в репозитории проекта нет `AGENTS.md`
+- **WHEN** участник открывает вкладку, нажимает «Изменить» и сохраняет текст с разделом «ИБ»
+- **THEN** в main появляется коммит с `AGENTS.md`, вкладка показывает этот текст, в журнале — событие правки
+
+#### Scenario: Файл изменили параллельно
+- **GIVEN** участник открыл редактор, а коллега тем временем закоммитил другой `AGENTS.md`
+- **WHEN** участник сохраняет свою версию
+- **THEN** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
diff --git a/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md
new file mode 100644
index 00000000..5d2ad8a8
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md
@@ -0,0 +1,4 @@
+- [x] 1 `fileWithSha`/`writeFile` в GiteaClient, contents API в mock-gitea
+- [x] 2 `readAgentsMd`/`saveAgentsMd` (sha-guard, предел, событие, ff рабочей копии)
+- [x] 3 Вкладка «AGENTS.md»: просмотр, редактор, заготовка
+- [x] 4 Тесты `project-tabs.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 40449d50..476bfab6 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -366,3 +366,18 @@ PM SHALL уметь убрать стори в архив и вернуть её
#### Scenario: Список сочетаний
- **WHEN** PM нажимает `?` вне поля ввода
- **THEN** открывается окно со списком сочетаний, тот же список — на `/help/shortcuts`
+
+### Requirement: Вкладка AGENTS.md
+Страница проекта SHALL иметь вкладку «AGENTS.md», которая показывает `AGENTS.md` из ветки
+по умолчанию репозитория проекта и даёт владельцу и участникам изменить его. Сохранение —
+один коммит в ветку по умолчанию от имени пользователя.
+
+#### Scenario: Создать и изменить
+- **GIVEN** в репозитории проекта нет `AGENTS.md`
+- **WHEN** участник открывает вкладку, нажимает «Изменить» и сохраняет текст с разделом «ИБ»
+- **THEN** в main появляется коммит с `AGENTS.md`, вкладка показывает этот текст, в журнале — событие правки
+
+#### Scenario: Файл изменили параллельно
+- **GIVEN** участник открыл редактор, а коллега тем временем закоммитил другой `AGENTS.md`
+- **WHEN** участник сохраняет свою версию
+- **THEN** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index 01361bb8..b599903e 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -259,6 +259,23 @@ export class GiteaClient {
}
}
+ /** A file at `ref` with its blob sha (for an update), or null if absent. */
+ async fileWithSha(owner: string, repo: string, path: string, ref: string): Promise<{ text: string; sha: string } | null> {
+ try {
+ const f = await this.request<{ content: string; sha: string }>("GET", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`);
+ return { text: Buffer.from(f.content, "base64").toString("utf8"), sha: f.sha };
+ } catch (e) {
+ if (e instanceof GiteaError && e.status === 404) return null;
+ throw e;
+ }
+ }
+
+ /** Creates (no `sha`) or updates (with the current blob `sha`) a file with one commit on `branch`. */
+ writeFile(owner: string, repo: string, path: string, o: { text: string; branch: string; message: string; sha?: string; author?: { name: string; email: string } }) {
+ const body = { content: Buffer.from(o.text, "utf8").toString("base64"), branch: o.branch, message: o.message, ...(o.sha ? { sha: o.sha } : {}), ...(o.author ? { author: o.author, committer: o.author } : {}) };
+ return this.request<{ commit: { sha: string; html_url: string } }>(o.sha ? "PUT" : "POST", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, body);
+ }
+
setActionsSecret(owner: string, repo: string, name: string, data: string) {
return this.request("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data });
}
diff --git a/packages/db/scripts/export-epics.ts b/packages/db/scripts/export-epics.ts
new file mode 100644
index 00000000..603caae4
--- /dev/null
+++ b/packages/db/scripts/export-epics.ts
@@ -0,0 +1,47 @@
+// Dumps a project's goals (epics) and their tasks with descriptions into Markdown.
+// Usage: tsx packages/db/scripts/export-epics.ts [KEY=PEP] [out=PEPPE_EPICS.md]
+import { writeFileSync } from "node:fs";
+import { asc, eq } from "drizzle-orm";
+import { createDb, goals, projects, tasks } from "../src/index.ts";
+
+const [key = "PEP", out = "PEPPE_EPICS.md"] = process.argv.slice(2);
+const db = createDb();
+
+const [project] = await db.select().from(projects).where(eq(projects.key, key));
+if (!project) throw new Error(`no project ${key}`);
+const gs = await db.select().from(goals).where(eq(goals.projectId, project.id)).orderBy(asc(goals.id));
+const ts = await db.select().from(tasks).where(eq(tasks.projectId, project.id)).orderBy(asc(tasks.number));
+
+const STATUS: Record = {
+ backlog: "Бэклог", proposing: "Proposal", awaiting_approval: "Ждёт одобрения",
+ in_progress: "В работе", review: "Ревью", done: "Готово", blocked: "Заблокирована",
+};
+
+function section(title: string, desc: string | null, items: typeof ts) {
+ const done = items.filter((t) => t.status === "done").length;
+ const lines = [`## ${title}`, "", `Задач: ${items.length}, готово: ${done}`, ""];
+ if (desc?.trim()) lines.push(desc.trim(), "");
+ for (const t of items) {
+ lines.push(`### ${key}-${t.number}: ${t.title}`, "");
+ const meta = [`Статус: ${STATUS[t.status] ?? t.status}`];
+ if (t.openspecChange) meta.push(`OpenSpec: \`${t.openspecChange}\``);
+ if (t.prUrl) meta.push(`PR: ${t.prUrl}`);
+ lines.push(meta.join(" · "), "");
+ if (t.description?.trim()) lines.push(t.description.trim(), "");
+ }
+ return lines.join("\n");
+}
+
+const parts = [
+ `# ${project.name} (${key}) — эпики и задачи`,
+ "",
+ `Выгружено ${new Date().toISOString().slice(0, 16).replace("T", " ")}: целей ${gs.length}, задач ${ts.length}.`,
+ "",
+ ...gs.map((g) => section(`${g.title}${g.status === "open" ? "" : ` (${g.status})`}`, g.description, ts.filter((t) => t.goalId === g.id))),
+];
+const orphans = ts.filter((t) => !t.goalId || !gs.some((g) => g.id === t.goalId));
+if (orphans.length) parts.push(section("Без цели", null, orphans));
+
+writeFileSync(out, parts.join("\n").trimEnd() + "\n");
+console.log(`${out}: ${gs.length} goals, ${ts.length} tasks`);
+process.exit(0);
diff --git a/packages/runner/src/agents-md.ts b/packages/runner/src/agents-md.ts
new file mode 100644
index 00000000..1a6e1616
--- /dev/null
+++ b/packages/runner/src/agents-md.ts
@@ -0,0 +1,85 @@
+// PEP-73: the project's AGENTS.md — its prompt and standards for every agent (Claude reads it
+// through CLAUDE.md, Codex and OpenCode natively) — shown and edited on the project tab
+// «AGENTS.md». The source of truth is the default branch in Gitea, not the working copy (which
+// may sit on a story branch); a save is one commit there, guarded by the blob sha it was based on.
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import { GiteaError, listSessions, logEvent, PeppaError, type Project, type User } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { loadEnv } from "@peppa/shared";
+import { git } from "./git.ts";
+import { repoAdmins } from "./share.ts";
+
+export const AGENTS_MD = "AGENTS.md";
+export const AGENTS_MD_MAX = 64 * 1024;
+
+export interface AgentsMd {
+ /** File text; "" when the repo has no AGENTS.md yet. */
+ text: string;
+ /** Blob sha the editor saves against; null when the file does not exist. */
+ sha: string | null;
+ branch: string;
+ url: string;
+ /** Set when Gitea could not be asked. */
+ error: string | null;
+}
+
+export async function readAgentsMd(db: Db, project: Project): Promise {
+ const branch = project.defaultBranch;
+ const url = `${loadEnv().GITEA_URL}/${project.giteaOwner}/${project.giteaRepo}/src/branch/${encodeURIComponent(branch)}/${AGENTS_MD}`;
+ let last: unknown = null;
+ for (const c of await repoAdmins(db, project)) {
+ try {
+ const f = await c.fileWithSha(project.giteaOwner, project.giteaRepo, AGENTS_MD, branch);
+ return { text: f?.text ?? "", sha: f?.sha ?? null, branch, url, error: null };
+ } catch (e) {
+ last = e;
+ }
+ }
+ return { text: "", sha: null, branch, url, error: `Gitea не ответила: ${(last as Error | null)?.message ?? "нет клиента"}` };
+}
+
+/**
+ * Commits a new AGENTS.md to the default branch. `baseSha` is the blob the editor started from
+ * (null for a new file): if someone changed the file meanwhile, the save is refused instead of
+ * overwriting their edit. The caller has already checked access to the project.
+ */
+export async function saveAgentsMd(db: Db, user: User, project: Project, text: string, baseSha: string | null): Promise<{ sha: string }> {
+ const body = text.replace(/\r\n/g, "\n");
+ if (Buffer.byteLength(body, "utf8") > AGENTS_MD_MAX) throw new PeppaError(`AGENTS.md больше ${AGENTS_MD_MAX / 1024} КБ — сократите`);
+ const branch = project.defaultBranch;
+ const author = { name: user.name || user.login, email: user.email || `${user.login}@users.peppa` };
+ let last: unknown = null;
+ for (const c of await repoAdmins(db, project)) {
+ try {
+ const cur = await c.fileWithSha(project.giteaOwner, project.giteaRepo, AGENTS_MD, branch);
+ if ((cur?.sha ?? null) !== baseSha) throw new PeppaError("AGENTS.md изменили, пока вы редактировали — обновите страницу и повторите правку");
+ if (cur && cur.text === body) return { sha: cur.sha };
+ const r = await c.writeFile(project.giteaOwner, project.giteaRepo, AGENTS_MD, {
+ text: body,
+ branch,
+ sha: cur?.sha,
+ message: `AGENTS.md: правка из Пеппы (${user.login})`,
+ author,
+ });
+ await logEvent(db, { projectId: project.id, type: "agents_md_updated", payload: { login: user.login, commit: r.commit.sha } });
+ await pullWorkspace(db, project).catch(() => {});
+ return { sha: r.commit.sha };
+ } catch (e) {
+ if (e instanceof PeppaError && !(e instanceof GiteaError)) throw e;
+ last = e;
+ }
+ }
+ throw new PeppaError(`Не удалось сохранить AGENTS.md в Gitea: ${(last as Error | null)?.message ?? "нет клиента"}`);
+}
+
+/** Fast-forwards the project's working copy when it is idle, clean and on the default branch. */
+async function pullWorkspace(db: Db, project: Project): Promise {
+ const dir = project.workspacePath;
+ if (!dir || !existsSync(join(dir, ".git"))) return;
+ if ((await listSessions(db, { active: true, projectId: project.id })).some((s) => !s.workspacePath)) return;
+ if ((await git(dir, "rev-parse", "--abbrev-ref", "HEAD")).stdout.trim() !== project.defaultBranch) return;
+ if ((await git(dir, "status", "--porcelain")).stdout.trim()) return;
+ await git(dir, "fetch", "origin", project.defaultBranch);
+ await git(dir, "merge", "--ff-only", `origin/${project.defaultBranch}`);
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d70cf480..d8956b45 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -18,6 +18,7 @@ export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./platform-release.ts";
export * from "./code.ts";
+export * from "./agents-md.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index acdc608c..026c6423 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -4,7 +4,8 @@
// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags.
import { execFileSync } from "node:child_process";
import { createHmac } from "node:crypto";
-import { mkdirSync } from "node:fs";
+import { mkdirSync, mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
@@ -451,12 +452,40 @@ export class MockGitea {
}
if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) {
try {
- const text = execFileSync("git", ["--git-dir", r.path, "show", `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
- return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64" } };
+ const spec = `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`;
+ const text = execFileSync("git", ["--git-dir", r.path, "show", spec], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+ const sha = execFileSync("git", ["--git-dir", r.path, "rev-parse", spec], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
+ return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64", sha } };
} catch {
return { status: 404, body: { message: "not found" } };
}
}
+ if ((method === "POST" || method === "PUT") && (m = sub.match(/^contents\/(.+)$/))) {
+ // Gitea's create (POST, file must not exist) / update (PUT, `sha` = current blob) — one commit on `branch`.
+ const path = decodeURIComponent(m[1]!);
+ const branch = String(body.branch ?? "main");
+ const git = (args: string[], env?: NodeJS.ProcessEnv, input?: string) =>
+ execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", input, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "ignore"] }).trim();
+ let parent: string | null = null;
+ try {
+ parent = git(["rev-parse", `refs/heads/${branch}`]);
+ } catch {}
+ let current: string | null = null;
+ try {
+ current = parent ? git(["rev-parse", `${parent}:${path}`]) : null;
+ } catch {}
+ if (method === "POST" && current) return { status: 422, body: { message: "repository file already exists" } };
+ if (method === "PUT" && current !== body.sha) return { status: 409, body: { message: `sha does not match [given: ${body.sha}, expected: ${current}]` } };
+ const blob = git(["hash-object", "-w", "--stdin"], undefined, Buffer.from(String(body.content), "base64").toString("utf8"));
+ const index = join(mkdtempSync(join(tmpdir(), "mock-gitea-idx-")), "index");
+ const env = { GIT_INDEX_FILE: index, GIT_AUTHOR_NAME: String(body.author?.name ?? me.login), GIT_AUTHOR_EMAIL: String(body.author?.email ?? "mock@example.invalid"), GIT_COMMITTER_NAME: me.login, GIT_COMMITTER_EMAIL: "mock@example.invalid" };
+ if (parent) git(["read-tree", parent], env);
+ git(["update-index", "--add", "--cacheinfo", `100644,${blob},${path}`], env);
+ const tree = git(["write-tree"], env);
+ const commit = git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", String(body.message ?? "update")], env);
+ git(["update-ref", `refs/heads/${branch}`, commit]);
+ return { status: method === "POST" ? 201 : 200, body: { content: { sha: blob, path }, commit: { sha: commit, html_url: `${this.url}/${r.owner}/${r.name}/commit/${commit}` } } };
+ }
if (method === "GET" && sub === "issues") {
const page = Number(q.get("page") ?? 1);
const limit = Number(q.get("limit") ?? 30);
diff --git a/packages/testkit/test/project-tabs.test.ts b/packages/testkit/test/project-tabs.test.ts
index 80bc9a0e..1c9ca2bb 100644
--- a/packages/testkit/test/project-tabs.test.ts
+++ b/packages/testkit/test/project-tabs.test.ts
@@ -153,3 +153,35 @@ describe("Эпики (цели как метки стори)", () => {
await assert.rejects(core.createTask(db, { projectId: a.id, title: "x", goalId: foreign.id }));
});
});
+
+describe("Вкладка «AGENTS.md» (PEP-73)", () => {
+ test("Scenario: читать, создать и изменить AGENTS.md — коммит в main от имени пользователя", async () => {
+ const p = await tabsProject("MTAG", { "README.md": "# Ag" });
+ const empty = await runner.readAgentsMd(db, p);
+ assert.equal(empty.error, null);
+ assert.equal(empty.text, "");
+ assert.equal(empty.sha, null);
+ assert.match(empty.url, /\/src\/branch\/main\/AGENTS\.md$/);
+
+ await runner.saveAgentsMd(db, alice, p, "# AGENTS.md\r\n\r\n## ИБ\r\n- без секретов\r\n", null);
+ const created = await runner.readAgentsMd(db, p);
+ assert.equal(created.text, "# AGENTS.md\n\n## ИБ\n- без секретов\n", "CRLF → LF");
+ assert.ok(created.sha);
+ assert.deepEqual(gitea.filesAt(ALICE.login, p.giteaRepo, "main").sort(), ["AGENTS.md", "README.md"], "other files kept");
+
+ await runner.saveAgentsMd(db, alice, p, created.text + "- зависимости без уязвимостей\n", created.sha);
+ const updated = await runner.readAgentsMd(db, p);
+ assert.match(updated.text, /зависимости без уязвимостей/);
+ const ev = await core.listJournal(db, { projectId: p.id, limit: 50 });
+ assert.ok(ev.some((e) => e.type === "agents_md_updated"), "journal entry");
+ });
+
+ test("Scenario: файл изменили, пока редактировали — сохранение отклонено, чужая правка цела", async () => {
+ const p = await tabsProject("MTAGC", { "README.md": "# C", "AGENTS.md": "v1\n" });
+ const stale = await runner.readAgentsMd(db, p);
+ gitea.commit(ALICE.login, p.giteaRepo, "main", { "AGENTS.md": "v2 от коллеги\n" }, "edit");
+ await assert.rejects(runner.saveAgentsMd(db, alice, p, "моя v1+\n", stale.sha), /изменили, пока вы редактировали/);
+ assert.equal((await runner.readAgentsMd(db, p)).text, "v2 от коллеги\n");
+ await assert.rejects(runner.saveAgentsMd(db, alice, p, "x".repeat(70 * 1024), (await runner.readAgentsMd(db, p)).sha), /больше 64 КБ/);
+ });
+});
--
2.45.2
From 2939bad87f0dc648490f6e650162a5f8e4468e18 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 18:27:18 +0500
Subject: [PATCH 009/439] PEP-73: type the commit author in mock-gitea contents
API
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/src/mock-gitea.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index 026c6423..bfde5b83 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -478,7 +478,8 @@ export class MockGitea {
if (method === "PUT" && current !== body.sha) return { status: 409, body: { message: `sha does not match [given: ${body.sha}, expected: ${current}]` } };
const blob = git(["hash-object", "-w", "--stdin"], undefined, Buffer.from(String(body.content), "base64").toString("utf8"));
const index = join(mkdtempSync(join(tmpdir(), "mock-gitea-idx-")), "index");
- const env = { GIT_INDEX_FILE: index, GIT_AUTHOR_NAME: String(body.author?.name ?? me.login), GIT_AUTHOR_EMAIL: String(body.author?.email ?? "mock@example.invalid"), GIT_COMMITTER_NAME: me.login, GIT_COMMITTER_EMAIL: "mock@example.invalid" };
+ const author = (body.author ?? {}) as { name?: string; email?: string };
+ const env = { GIT_INDEX_FILE: index, GIT_AUTHOR_NAME: String(author.name ?? me.login), GIT_AUTHOR_EMAIL: String(author.email ?? "mock@example.invalid"), GIT_COMMITTER_NAME: me.login, GIT_COMMITTER_EMAIL: "mock@example.invalid" };
if (parent) git(["read-tree", parent], env);
git(["update-index", "--add", "--cacheinfo", `100644,${blob},${path}`], env);
const tree = git(["write-tree"], env);
--
2.45.2
From d039a8ac7925e34b69c100017a47975e4f01f36b 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 18:39:36 +0500
Subject: [PATCH 010/439] =?UTF-8?q?PEP-74:=20a=20superadmin=20opens=20any?=
=?UTF-8?q?=20project;=20=C2=AB=D0=9F=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D1=8B?=
=?UTF-8?q?=20=D0=B4=D1=80=D1=83=D0=B3=D0=B8=D1=85=C2=BB=20on=20the=20proj?=
=?UTF-8?q?ects=20page?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 2 ++
apps/web/app/(app)/projects/page.tsx | 12 ++++++++---
apps/web/components/cards.tsx | 4 ++--
.../proposal.md | 12 +++++++++++
.../specs/web-auth/spec.md | 16 ++++++++++++++
.../tasks.md | 3 +++
openspec/specs/web-auth/spec.md | 15 +++++++++++++
packages/core/src/users.ts | 18 +++++++++++++++-
packages/testkit/test/web.test.ts | 21 +++++++++++++++++++
9 files changed, 97 insertions(+), 6 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/specs/web-auth/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index 1ce113bf..f6bd3d0e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -31,6 +31,8 @@
- `peppa session resume ` → `claude --resume`
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные пользователи (PEP-68), кроме отключённых; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
+- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
+- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/projects/page.tsx b/apps/web/app/(app)/projects/page.tsx
index f6c94222..31d55178 100644
--- a/apps/web/app/(app)/projects/page.tsx
+++ b/apps/web/app/(app)/projects/page.tsx
@@ -1,8 +1,8 @@
import Link from "next/link";
import { Plus } from "lucide-react";
-import { listUserProjects } from "@peppa/core";
+import { listOtherProjects, listUserProjects } from "@peppa/core";
import { ProjectList } from "@/components/cards";
-import { Flash, PageHeader } from "@/components/common";
+import { Flash, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
@@ -11,7 +11,7 @@ import { db } from "@/lib/db";
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { error } = await searchParams;
- const projects = await listUserProjects(db, user.id);
+ const [projects, others] = await Promise.all([listUserProjects(db, user.id), listOtherProjects(db, user.id)]);
return (
@@ -29,6 +29,12 @@ export default async function Projects({ searchParams }: { searchParams: Promise
Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.
+ {others.length > 0 && (
+
+ Видны вам как суперадмину. Вопросы агентов и уведомления этих проектов к вам не приходят.
+
+
+ )}
);
}
diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx
index 9d20dc88..865117f5 100644
--- a/apps/web/components/cards.tsx
+++ b/apps/web/components/cards.tsx
@@ -144,7 +144,7 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
);
}
-export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) {
+export function ProjectList({ projects, userId }: { projects: Array; userId: number }) {
if (!projects.length)
return (
@@ -159,7 +159,7 @@ export function ProjectList({ projects, userId }: { projects: Project[]; userId:
{p.key}
{p.name}
- {p.ownerId !== userId && общий }
+ {p.ownerId !== userId && {p.ownerLogin !== undefined ? (p.ownerLogin ?? "без владельца") : "общий"} }
{p.giteaOwner}/{p.giteaRepo}
diff --git a/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/proposal.md b/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/proposal.md
new file mode 100644
index 00000000..b379b655
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/proposal.md
@@ -0,0 +1,12 @@
+# PEP-74: суперадмин видит все проекты
+
+## Why
+Суперадмин платформы не видит проекты других пользователей: доступ есть только у владельца и участников.
+Он отвечает за подписки, пулы и пользователей, поэтому должен видеть, что происходит во всех проектах.
+
+## What Changes
+- `projectForUser` пускает суперадмина (`platform.admins`, не отключён) в любой проект с правами участника — в вебе, MCP и SSE.
+- «Проекты»: у суперадмина секция «Проекты других» (`listOtherProjects`) с логином владельца.
+- `userProjectIds` не меняется: Главная, счётчики, вопросы агентов, уведомления и дайджест остаются только по своим проектам.
+
+Вне scope: публичные проекты для обычных пользователей. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/specs/web-auth/spec.md
new file mode 100644
index 00000000..b0655825
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/specs/web-auth/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Суперадмин видит все проекты
+Суперадмин (логин в `platform.admins`) SHALL открывать любой проект с правами участника и
+видеть на странице «Проекты» секцию «Проекты других». Вопросы агентов, счётчики и
+уведомления чужих проектов ему SHALL NOT приходить.
+
+#### Scenario: Чужой проект
+- **GIVEN** проект «TZK» пользователя «dana» и суперадмин «asel», не участник проекта
+- **WHEN** asel открывает «Проекты» и затем `/p/TZK`
+- **THEN** «TZK» показан в секции «Проекты других» с владельцем «dana», и доска проекта открывается
+
+#### Scenario: Обычный пользователь
+- **GIVEN** пользователь «kate» не суперадмин и не участник «TZK»
+- **WHEN** она открывает `/p/TZK`
+- **THEN** она получает «не найдено», секции «Проекты других» у неё нет
diff --git a/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/tasks.md b/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/tasks.md
new file mode 100644
index 00000000..30151fe9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-74-superadmin-all-projects/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `projectForUser` для суперадмина, `listOtherProjects`
+- [x] 2 Секция «Проекты других» на странице «Проекты»
+- [x] 3 Тест в `web.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index 552b8730..49332709 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -164,3 +164,18 @@ nonce, созданные сервером для этого потока; по
- **GIVEN** вход начат, человек ушёл в eGov Mobile, браузер выгрузил вкладку
- **WHEN** он возвращается, и страница загружается заново
- **THEN** страница продолжает тот же вход и после подписи впускает его
+
+### Requirement: Суперадмин видит все проекты
+Суперадмин (логин в `platform.admins`) SHALL открывать любой проект с правами участника и
+видеть на странице «Проекты» секцию «Проекты других». Вопросы агентов, счётчики и
+уведомления чужих проектов ему SHALL NOT приходить.
+
+#### Scenario: Чужой проект
+- **GIVEN** проект «TZK» пользователя «dana» и суперадмин «asel», не участник проекта
+- **WHEN** asel открывает «Проекты» и затем `/p/TZK`
+- **THEN** «TZK» показан в секции «Проекты других» с владельцем «dana», и доска проекта открывается
+
+#### Scenario: Обычный пользователь
+- **GIVEN** пользователь «kate» не суперадмин и не участник «TZK»
+- **WHEN** она открывает `/p/TZK`
+- **THEN** она получает «не найдено», секции «Проекты других» у неё нет
diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts
index f23b25a6..9175a246 100644
--- a/packages/core/src/users.ts
+++ b/packages/core/src/users.ts
@@ -5,6 +5,7 @@ import { decrypt, encrypt, hashToken } from "./crypto.ts";
import { randomBytes } from "node:crypto";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { PeppaError } from "./errors.ts";
+import { allowedLogins } from "./access.ts";
import { GiteaClient, refreshOAuthToken, type GiteaUser, type OAuthTokens } from "./gitea.ts";
import type { Project } from "./projects.ts";
@@ -95,12 +96,27 @@ export async function projectForUser(db: Db, userId: number, projectId: number):
.select()
.from(projectMembers)
.where(and(eq(projectMembers.projectId, projectId), eq(projectMembers.userId, userId)));
- if (!m) throw new PeppaError("Не найдено");
+ if (!m && !(await isSuperadminId(db, userId))) throw new PeppaError("Не найдено");
}
if (!row) throw new PeppaError("Не найдено");
return row;
}
+/** PEP-74: a platform admin (`platform.admins`, else the allowlist) may open any project. */
+async function isSuperadminId(db: Db, userId: number): Promise {
+ const [u] = await db.select({ login: users.login, disabledAt: users.disabledAt }).from(users).where(eq(users.id, userId));
+ if (!u || u.disabledAt) return false;
+ return ((await getSetting(db, "platform.admins")) ?? (await allowedLogins(db))).includes(u.login.toLowerCase());
+}
+
+/** PEP-74: projects the user neither owns nor is a member of — for a superadmin's «Проекты других». */
+export async function listOtherProjects(db: Db, userId: number): Promise> {
+ if (!(await isSuperadminId(db, userId))) return [];
+ const mine = new Set(await userProjectIds(db, userId));
+ const rows = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).orderBy(asc(projects.key));
+ return rows.filter((r) => !mine.has(r.p.id)).map((r) => ({ ...r.p, ownerLogin: r.ownerLogin }));
+}
+
const loginIs = (login: string) => sql`lower(${users.login}) = ${login.toLowerCase()}`;
export interface ProjectMembers {
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 612613fa..137ad7a4 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -142,3 +142,24 @@ describe("access control", () => {
assert.ok((await core.listUserProjects(db, alice.id)).some((x) => x.key === "MDEMO"));
});
});
+
+describe("PEP-74: суперадмин видит все проекты", () => {
+ test("чужой проект открыт суперадмину и в списке «Проекты других»; обычному — «Не найдено»", async () => {
+ const owner = await core.upsertUserFromGitea(db, { id: 7401, login: "mock-p74-owner" }, { access_token: "x" });
+ const boss = await core.upsertUserFromGitea(db, { id: 7402, login: "mock-p74-boss" }, { access_token: "x" });
+ const other = await core.upsertUserFromGitea(db, { id: 7403, login: "mock-p74-other" }, { access_token: "x" });
+ const p = await core.createProject(db, { slug: "mock-p74", key: "MPSA", name: "P74", giteaOwner: "x", workspacePath: "/tmp/mock-p74", ownerId: owner.id });
+ await core.setPlatformAdmins(db, ["mock-p74-boss"]);
+ try {
+ assert.equal((await core.projectForUser(db, boss.id, p.id)).key, "MPSA");
+ await assert.rejects(core.projectForUser(db, other.id, p.id), /Не найдено/);
+ const list = await core.listOtherProjects(db, boss.id);
+ assert.ok(list.some((x) => x.key === "MPSA" && x.ownerLogin === "mock-p74-owner"));
+ assert.deepEqual(await core.listOtherProjects(db, other.id), []);
+ assert.ok(!(await core.listOtherProjects(db, owner.id)).some((x) => x.key === "MPSA"));
+ assert.ok(!(await core.userProjectIds(db, boss.id)).includes(p.id), "inbox and notifications stay own-only");
+ } finally {
+ await core.setPlatformAdmins(db, null);
+ }
+ });
+});
--
2.45.2
From 5b41e7d779d28c2ab39fff7048b06a343536b8aa 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 18:49:34 +0500
Subject: [PATCH 011/439] =?UTF-8?q?PEP-75:=20a=20team=20of=20agents=20?=
=?UTF-8?q?=E2=80=94=20Kazakh=20names=20on=20the=20board,=20a=20character?=
=?UTF-8?q?=20in=20the=20prompt?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Also: «Открыть терминал» on live session cards.
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/p/[key]/page.tsx | 4 +-
apps/web/app/(app)/team/actions.ts | 42 +
apps/web/app/(app)/team/page.tsx | 96 +
apps/web/components/AgentBadge.tsx | 16 +
apps/web/components/Board.tsx | 4 +
apps/web/components/Sidebar.tsx | 3 +-
apps/web/components/cards.tsx | 11 +-
.../2026-11-14-pep-75-agent-team/proposal.md | 17 +
.../specs/runner-sessions/spec.md | 26 +
.../2026-11-14-pep-75-agent-team/tasks.md | 5 +
openspec/specs/runner-sessions/spec.md | 25 +
packages/core/src/index.ts | 1 +
packages/core/src/sessions.ts | 12 +-
packages/core/src/team.ts | 155 +
packages/db/migrations/0014_agent_team.sql | 10 +
.../db/migrations/meta/0014_snapshot.json | 3727 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 12 +
packages/runner/src/sessions.ts | 7 +-
packages/testkit/test/team.test.ts | 74 +
22 files changed, 4248 insertions(+), 8 deletions(-)
create mode 100644 apps/web/app/(app)/team/actions.ts
create mode 100644 apps/web/app/(app)/team/page.tsx
create mode 100644 apps/web/components/AgentBadge.tsx
create mode 100644 openspec/changes/archive/2026-11-14-pep-75-agent-team/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-75-agent-team/specs/runner-sessions/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-75-agent-team/tasks.md
create mode 100644 packages/core/src/team.ts
create mode 100644 packages/db/migrations/0014_agent_team.sql
create mode 100644 packages/db/migrations/meta/0014_snapshot.json
create mode 100644 packages/testkit/test/team.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index f6bd3d0e..6ba94b29 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,6 +33,7 @@
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные пользователи (PEP-68), кроме отключённых; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
+- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 8845b10e..049e478e 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,6 +70,7 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
+ Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index f5588070..624b3c19 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, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-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 { 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, taskAgentNames, 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";
@@ -112,6 +112,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
+ const agentNames = await taskAgentNames(db, p.id);
const cards: Card[] = tasks
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
.map((t) => {
@@ -125,6 +126,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
// PEP-33: tasks.md progress of stories in work.
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
+ agent: agentNames.get(t.id) ?? null,
};
});
// Gitea and the working copy are read only for the open tab.
diff --git a/apps/web/app/(app)/team/actions.ts b/apps/web/app/(app)/team/actions.ts
new file mode 100644
index 00000000..7d8729fd
--- /dev/null
+++ b/apps/web/app/(app)/team/actions.ts
@@ -0,0 +1,42 @@
+"use server";
+
+import { createAgent, isSuperadmin, PeppaError, updateAgent } from "@peppa/core";
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { asWebActor, requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+
+/** PEP-75: the team is platform-wide, so only a superadmin changes it. */
+async function run(fn: () => Promise): Promise {
+ let target = "/team";
+ try {
+ const user = asWebActor(await requireUser());
+ if (!(await isSuperadmin(db, user))) throw new PeppaError("Команду меняет только суперадмин");
+ target = (await fn()) || target;
+ } catch (e) {
+ target = `/team?error=${encodeURIComponent((e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`).slice(0, 300))}`;
+ }
+ revalidatePath("/", "layout");
+ redirect(target);
+}
+
+export async function addAgentAction(f: FormData) {
+ await run(async () => {
+ const a = await createAgent(db, { name: String(f.get("name") ?? "") });
+ return `/team?saved=${a.id}#agent-${a.id}`;
+ });
+}
+
+export async function saveAgentAction(f: FormData) {
+ await run(async () => {
+ const id = Number(f.get("id"));
+ await updateAgent(db, id, { name: String(f.get("name") ?? ""), character: String(f.get("character") ?? "") });
+ return `/team?saved=${id}#agent-${id}`;
+ });
+}
+
+export async function toggleAgentAction(f: FormData) {
+ await run(async () => {
+ await updateAgent(db, Number(f.get("id")), { disabled: f.get("disabled") === "1" });
+ });
+}
diff --git a/apps/web/app/(app)/team/page.tsx b/apps/web/app/(app)/team/page.tsx
new file mode 100644
index 00000000..0624255d
--- /dev/null
+++ b/apps/web/app/(app)/team/page.tsx
@@ -0,0 +1,96 @@
+import { Plus } from "lucide-react";
+import { AGENT_CHARACTER_MAX, isSuperadmin, listAgents } from "@peppa/core";
+import { AgentBadge } from "@/components/AgentBadge";
+import { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
+import { Markdown } from "@/components/Markdown";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input, Label, Textarea } from "@/components/ui/input";
+import { Workspace } from "@/components/Workspace";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions";
+
+export const metadata = { title: "Команда — Пеппа" };
+
+/** PEP-75: the platform's team of agents — names and characters. Everyone sees it; a superadmin edits. */
+export default async function Team({ searchParams }: { searchParams: Promise<{ error?: string; saved?: string }> }) {
+ const user = await requireUser();
+ const { error, saved } = await searchParams;
+ const [team, admin] = await Promise.all([listAgents(db), isSuperadmin(db, user)]);
+ return (
+
+
+
+ {saved &&
Сохранено — агент получит новый характер при следующем запуске или перезапуске. }
+
+ Агенты Пеппы — постоянные персонажи, одна команда на все проекты. Раннер берёт свободного агента на стори, и тот ведёт её до конца; если все заняты — в команде
+ появляется новый. Характер агента добавляется к его промпту поверх правил Пеппы и AGENTS.md проекта.
+
+
+ {admin && (
+
+
+
+ Новый агент
+
+
+
+ Добавить
+
+
+
+ )}
+
+
+ {team.length === 0 && Пока никого: первый агент появится, когда стори уйдёт «В работу». }
+ {team.map((a) => (
+
+
+
+ {a.busy > 0 ?
работает{a.busy > 1 ? ` ×${a.busy}` : ""} :
свободен }
+ {a.disabledAt &&
не в команде }
+
запусков: {a.runs}
+
+ {admin ? (
+ <>
+
+
+
+ Имя
+
+
+
+ Характер и специализация
+
+
+ Сохранить
+
+
+
+
+
+ {a.disabledAt ? "Вернуть в команду" : "Убрать из команды — новые стори не получит"}
+
+
+ >
+ ) : a.character ? (
+
+ ) : (
+ Характер не задан.
+ )}
+
+ ))}
+
+
+
+ );
+}
diff --git a/apps/web/components/AgentBadge.tsx b/apps/web/components/AgentBadge.tsx
new file mode 100644
index 00000000..efe9eb35
--- /dev/null
+++ b/apps/web/components/AgentBadge.tsx
@@ -0,0 +1,16 @@
+import { cn } from "@/lib/utils";
+
+const TONES = ["bg-sky-500/20 text-sky-300", "bg-emerald-500/20 text-emerald-300", "bg-amber-500/20 text-amber-300", "bg-fuchsia-500/20 text-fuchsia-300", "bg-rose-500/20 text-rose-300", "bg-violet-500/20 text-violet-300", "bg-teal-500/20 text-teal-300", "bg-orange-500/20 text-orange-300"];
+
+/** PEP-75: an agent persona — a round initial in its own colour and the name. */
+export function AgentBadge({ name, className, large = false }: { name: string; className?: string; large?: boolean }) {
+ const tone = TONES[[...name].reduce((a, c) => a + c.codePointAt(0)!, 0) % TONES.length];
+ return (
+
+
+ {[...name][0]}
+
+ {name}
+
+ );
+}
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index fee5fc9c..248c244b 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -8,6 +8,7 @@ import { moveTaskCard } from "@/app/(app)/actions";
import { reorderTaskInline } from "@/app/(app)/board-actions";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
+import { AgentBadge } from "@/components/AgentBadge";
import { cn } from "@/lib/utils";
export type Column = "backlog" | "in_progress" | "review" | "done";
@@ -22,6 +23,8 @@ export interface Card {
progress?: CardProgress | null;
/** PEP-42: "ждёт PEP-3" while a predecessor isn't in review/done. */
blocked?: string | null;
+ /** PEP-75: the persona working on the story right now. */
+ agent?: string | null;
}
export interface CardProgress {
done: number;
@@ -183,6 +186,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
)}
+ {card.agent && }
{card.progress && }
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index dc34717d..0cd5a95d 100644
--- a/apps/web/components/Sidebar.tsx
+++ b/apps/web/components/Sidebar.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { Bot, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
+import { Bot, Contact, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@@ -22,6 +22,7 @@ const ITEMS: Item[] = [
{ href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" },
{ href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
{ href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" },
+ { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team") },
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx
index 865117f5..84057da0 100644
--- a/apps/web/components/cards.tsx
+++ b/apps/web/components/cards.tsx
@@ -1,9 +1,10 @@
// Domain cards shared by pages: agent questions, runners, project list.
import Link from "next/link";
-import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square } from "lucide-react";
+import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
import type { Project, Question, SessionView, StepView } from "@peppa/core";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
import { Button } from "@/components/ui/button";
+import { AgentBadge } from "@/components/AgentBadge";
import { Input } from "@/components/ui/input";
import { ago, Empty, Key, StatusBadge } from "@/components/common";
import { AgentSteps } from "@/components/AgentSteps";
@@ -126,6 +127,7 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
{s.taskKey ? {s.taskKey} : {s.projectKey} }
+ {s.agentName && }
{showTitle && (s.taskTitle ?? s.name) && {s.taskTitle ?? s.name} }
#{s.id} · {s.provider}
@@ -138,6 +140,13 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
+ {!terminal && !["done", "failed"].includes(s.status) && (
+
+
+ Открыть терминал
+
+
+ )}
{steps && }
{terminal && }
diff --git a/openspec/changes/archive/2026-11-14-pep-75-agent-team/proposal.md b/openspec/changes/archive/2026-11-14-pep-75-agent-team/proposal.md
new file mode 100644
index 00000000..48fadbae
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-75-agent-team/proposal.md
@@ -0,0 +1,17 @@
+# PEP-75: команда агентов — казахские имена и характер
+
+## Why
+Агент в Пеппе безымянный: «сессия #19». PM хочет видеть на доске, кто ведёт стори, и задавать агентам характер и
+специализацию. Решение PM: одна команда на всю платформу.
+
+## What Changes
+- Таблица `agents` (имя, характер-markdown, «не в команде») и `sessions.agent_id` (миграция 0014).
+- `ensureSessionAgent` (core/team.ts) при запуске раннера: персонаж прошлых раннеров этой стори → свободный (без живого раннера;
+ первым — отдыхавший дольше всех) → новый со следующим именем из `AGENT_NAMES` (40 казахских имён, дальше «Айгерим 2»).
+ Одна синхронная транзакция; resume и ротация подписок персонажа не меняют.
+- `launch` дописывает к правилам `agentPrompt`: имя и характер (правила Пеппы и AGENTS.md проекта важнее).
+- Веб: страница «Команда» (видят все; суперадмин добавляет, переименовывает, задаёт характер, убирает из команды), имя с цветным
+ кружком на карточках доски «В работе» и на карточках раннеров (`SessionView.agentName`).
+- Заодно: кнопка «Открыть терминал» у живых сессий на вкладке «Сессии» проекта и на Главной (раньше туда вела только ссылка «#id»).
+
+Вне scope: ручное назначение агента на стори, имя в сообщениях Telegram, команда на проект. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-75-agent-team/specs/runner-sessions/spec.md b/openspec/changes/archive/2026-11-14-pep-75-agent-team/specs/runner-sessions/spec.md
new file mode 100644
index 00000000..28b707e4
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-75-agent-team/specs/runner-sessions/spec.md
@@ -0,0 +1,26 @@
+## ADDED Requirements
+
+### Requirement: Команда агентов
+Каждый раннер SHALL работать от имени персонажа из команды платформы. Стори SHALL сохранять
+своего персонажа при перезапусках и новых раннерах; свободного персонажа получает новая стори,
+а когда все заняты, в команде появляется новый с казахским именем. Имя и характер персонажа
+SHALL попадать в промпт агента, имя — на карточку стори «В работе».
+
+#### Scenario: Первый запуск
+- **GIVEN** команда пуста
+- **WHEN** стори уходит «В работу»
+- **THEN** появляется агент «Айгерим», его имя видно на карточке стори, и в промпте агента есть «Тебя зовут **Айгерим**»
+
+#### Scenario: Все заняты
+- **GIVEN** «Айгерим» ведёт стори, других агентов нет
+- **WHEN** запускается вторая стори
+- **THEN** её ведёт новый агент «Нурлан», «Айгерим» остаётся на своей
+
+#### Scenario: Характер
+- **GIVEN** суперадмин записал агенту «Айгерим» характер «Педант по безопасности»
+- **WHEN** раннер этой стори перезапускается
+- **THEN** стори по-прежнему ведёт «Айгерим», и её характер есть в промпте агента
+
+#### Scenario: Имя занято
+- **WHEN** суперадмин называет агента именем, которое уже есть в команде (в любом регистре)
+- **THEN** изменение отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-75-agent-team/tasks.md b/openspec/changes/archive/2026-11-14-pep-75-agent-team/tasks.md
new file mode 100644
index 00000000..5262ee9a
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-75-agent-team/tasks.md
@@ -0,0 +1,5 @@
+- [x] 1 Схема `agents`, `sessions.agent_id`, миграция 0014
+- [x] 2 `core/team.ts`: имена, `ensureSessionAgent`, `agentPrompt`, `taskAgentNames`; персонаж в правилах запуска
+- [x] 3 Страница «Команда», имя на доске и карточках раннеров, пункт меню
+- [x] 4 Кнопка «Открыть терминал» у живых сессий
+- [x] 5 Тесты `team.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/runner-sessions/spec.md b/openspec/specs/runner-sessions/spec.md
index 31d9ab33..5f37c627 100644
--- a/openspec/specs/runner-sessions/spec.md
+++ b/openspec/specs/runner-sessions/spec.md
@@ -120,3 +120,28 @@
- **GIVEN** вопрос #12 сессии #7, tmux-сессии нет
- **WHEN** PM отвечает
- **THEN** ответ сохранён, PM видит «Ответ сохранён, но сессия сейчас не запущена»
+
+### Requirement: Команда агентов
+Каждый раннер SHALL работать от имени персонажа из команды платформы. Стори SHALL сохранять
+своего персонажа при перезапусках и новых раннерах; свободного персонажа получает новая стори,
+а когда все заняты, в команде появляется новый с казахским именем. Имя и характер персонажа
+SHALL попадать в промпт агента, имя — на карточку стори «В работе».
+
+#### Scenario: Первый запуск
+- **GIVEN** команда пуста
+- **WHEN** стори уходит «В работу»
+- **THEN** появляется агент «Айгерим», его имя видно на карточке стори, и в промпте агента есть «Тебя зовут **Айгерим**»
+
+#### Scenario: Все заняты
+- **GIVEN** «Айгерим» ведёт стори, других агентов нет
+- **WHEN** запускается вторая стори
+- **THEN** её ведёт новый агент «Нурлан», «Айгерим» остаётся на своей
+
+#### Scenario: Характер
+- **GIVEN** суперадмин записал агенту «Айгерим» характер «Педант по безопасности»
+- **WHEN** раннер этой стори перезапускается
+- **THEN** стори по-прежнему ведёт «Айгерим», и её характер есть в промпте агента
+
+#### Scenario: Имя занято
+- **WHEN** суперадмин называет агента именем, которое уже есть в команде (в любом регистре)
+- **THEN** изменение отклонено
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 57b2f81c..f06b1ada 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -20,6 +20,7 @@ export * from "./repo-info.ts";
export * from "./incidents.ts";
export * from "./ci.ts";
export * from "./egov.ts";
+export * from "./team.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";
diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts
index bb35313f..0b3a70ca 100644
--- a/packages/core/src/sessions.ts
+++ b/packages/core/src/sessions.ts
@@ -1,4 +1,4 @@
-import { events, projects, questions, runnerHosts, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db";
+import { agents, events, projects, questions, runnerHosts, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, inArray, isNull, lte, notInArray, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
@@ -23,6 +23,8 @@ export interface SessionView extends Session {
subscriptionSwitches: number;
/** PEP-40: where the runner's tmux lives (null = Peppa's own machine). */
host: SessionHost | null;
+ /** PEP-75: name of the persona working in the runner. */
+ agentName: string | null;
}
/** PEP-40: how to reach a runner's host (see runner/exec.ts). */
@@ -180,7 +182,7 @@ export async function raiseSessionQuestion(
function sessionQuery(db: Db) {
return db
- .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, subscriptionName: subscriptions.name,
+ .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, subscriptionName: subscriptions.name, agentName: agents.name,
switches: sql`(select count(*) from events e where e.session_id = ${sessions.id} and e.type = 'subscription_switched')`,
host: { id: runnerHosts.id, name: runnerHosts.name, sshTarget: runnerHosts.sshTarget, sshPort: runnerHosts.sshPort, workdir: runnerHosts.workdir, peppaUrl: runnerHosts.peppaUrl },
})
@@ -188,10 +190,11 @@ function sessionQuery(db: Db) {
.innerJoin(projects, eq(sessions.projectId, projects.id))
.leftJoin(tasks, eq(sessions.taskId, tasks.id))
.leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id))
- .leftJoin(runnerHosts, eq(sessions.hostId, runnerHosts.id));
+ .leftJoin(runnerHosts, eq(sessions.hostId, runnerHosts.id))
+ .leftJoin(agents, eq(sessions.agentId, agents.id));
}
-function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; taskStatus: string | null; subscriptionName: string | null; switches: number; host: SessionHost | { id: null } | null }): SessionView {
+function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; taskStatus: string | null; subscriptionName: string | null; agentName: string | null; switches: number; host: SessionHost | { id: null } | null }): SessionView {
return {
...r.session,
projectKey: r.projectKey,
@@ -199,6 +202,7 @@ function toView(r: { session: Session; projectKey: string; taskNumber: number |
taskTitle: r.taskTitle,
taskStatus: r.taskStatus,
subscriptionName: r.subscriptionName,
+ agentName: r.agentName,
subscriptionSwitches: Number(r.switches ?? 0),
host: r.host && r.host.id != null ? (r.host as SessionHost) : null,
};
diff --git a/packages/core/src/team.ts b/packages/core/src/team.ts
new file mode 100644
index 00000000..0b1348b9
--- /dev/null
+++ b/packages/core/src/team.ts
@@ -0,0 +1,155 @@
+// PEP-75: the platform's team of agents — permanent personas with Kazakh names. A runner takes a
+// free persona for its story (creating one when everybody is busy) and keeps it across resumes
+// and across the story's later runners; the PM gives each a character (markdown) that goes into
+// the agent's prompt on top of the shared rules and the project's AGENTS.md.
+import { agents, sessions, type Db } from "@peppa/db";
+import { and, asc, desc, eq, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+
+export type Agent = typeof agents.$inferSelect;
+
+/** Names new personas get, in order; when all are taken — «Айгерим 2», … */
+export const AGENT_NAMES = [
+ "Айгерим", "Нурлан", "Дана", "Ерлан", "Мадина", "Арман", "Жанар", "Тимур", "Асель", "Данияр", "Сауле", "Бауыржан",
+ "Гульнар", "Аскар", "Камила", "Ержан", "Айжан", "Санжар", "Динара", "Алмас", "Назерке", "Олжас", "Томирис", "Канат",
+ "Алия", "Марат", "Жибек", "Руслан", "Балжан", "Серик", "Меруерт", "Азамат", "Карлыгаш", "Дархан", "Толганай", "Абай",
+ "Шолпан", "Кайрат", "Айсулу", "Мухтар",
+];
+export const AGENT_CHARACTER_MAX = 8000;
+
+const FINISHED = ["done", "failed"] as const;
+
+export interface AgentView extends Agent {
+ /** Live runners of this persona right now. */
+ busy: number;
+ /** All runners it has ever worked in. */
+ runs: number;
+}
+
+export async function listAgents(db: Db): Promise {
+ const rows = await db
+ .select({
+ a: agents,
+ busy: sql`(select count(*) from sessions s where s.agent_id = ${agents.id} and s.status not in ('done', 'failed'))`,
+ runs: sql`(select count(*) from sessions s where s.agent_id = ${agents.id})`,
+ })
+ .from(agents)
+ .orderBy(asc(agents.id));
+ return rows.map((r) => ({ ...r.a, busy: Number(r.busy), runs: Number(r.runs) }));
+}
+
+export async function getAgent(db: Db, id: number): Promise {
+ const [a] = await db.select().from(agents).where(eq(agents.id, id));
+ return a ?? null;
+}
+
+const cleanName = (name: string) => {
+ const n = name.trim().replace(/\s+/g, " ");
+ if (!n || n.length > 40) throw new PeppaError("Имя агента: от 1 до 40 символов");
+ return n;
+};
+
+function nextName(taken: Set): string {
+ for (let round = 1; ; round++) {
+ for (const base of AGENT_NAMES) {
+ const name = round === 1 ? base : `${base} ${round}`;
+ if (!taken.has(name.toLowerCase())) return name;
+ }
+ }
+}
+
+/** A new persona; without a name — the next free one of `AGENT_NAMES`. */
+export async function createAgent(db: Db, o: { name?: string; character?: string } = {}): Promise {
+ const character = (o.character ?? "").trim();
+ if (character.length > AGENT_CHARACTER_MAX) throw new PeppaError(`Характер длиннее ${AGENT_CHARACTER_MAX} символов — сократите`);
+ return db.transaction((tx) => {
+ const taken = new Set(tx.select({ name: agents.name }).from(agents).all().map((r) => r.name.toLowerCase()));
+ const name = o.name?.trim() ? cleanName(o.name) : nextName(taken);
+ if (taken.has(name.toLowerCase())) throw new PeppaError(`Агент «${name}» уже есть`);
+ return tx.insert(agents).values({ name, character }).returning().get();
+ });
+}
+
+export async function updateAgent(db: Db, id: number, patch: { name?: string; character?: string; disabled?: boolean }): Promise {
+ const set: Partial = {};
+ if (patch.name !== undefined) {
+ set.name = cleanName(patch.name);
+ // Compared in JS: SQLite's lower() leaves Cyrillic and Kazakh letters as they are.
+ const lower = set.name.toLowerCase();
+ const other = (await db.select({ id: agents.id, name: agents.name }).from(agents)).find((a) => a.name.toLowerCase() === lower);
+ if (other && other.id !== id) throw new PeppaError(`Агент «${set.name}» уже есть`);
+ }
+ if (patch.character !== undefined) {
+ set.character = patch.character.replace(/\r\n/g, "\n").trim();
+ if (set.character.length > AGENT_CHARACTER_MAX) throw new PeppaError(`Характер длиннее ${AGENT_CHARACTER_MAX} символов — сократите`);
+ }
+ if (patch.disabled !== undefined) set.disabledAt = patch.disabled ? new Date() : null;
+ const [row] = Object.keys(set).length ? await db.update(agents).set(set).where(eq(agents.id, id)).returning() : await db.select().from(agents).where(eq(agents.id, id));
+ if (!row) throw new PeppaError("Агент не найден");
+ return row;
+}
+
+/**
+ * The persona of a runner, assigning one on first use: the story's previous persona if it is
+ * still in the team, else a free one (no live runner), else a new one with the next name.
+ * One synchronous transaction, so two runners starting together never share a free persona.
+ */
+export async function ensureSessionAgent(db: Db, sessionId: number): Promise {
+ return db.transaction((tx) => {
+ const s = tx.select().from(sessions).where(eq(sessions.id, sessionId)).get();
+ if (!s) return null;
+ if (s.agentId) {
+ const own = tx.select().from(agents).where(eq(agents.id, s.agentId)).get();
+ if (own) return own;
+ }
+ let agent: Agent | undefined;
+ if (s.taskId) {
+ agent = tx
+ .select({ a: agents })
+ .from(sessions)
+ .innerJoin(agents, eq(sessions.agentId, agents.id))
+ .where(and(eq(sessions.taskId, s.taskId), isNotNull(sessions.agentId), isNull(agents.disabledAt)))
+ .orderBy(desc(sessions.id))
+ .limit(1)
+ .get()?.a;
+ }
+ if (!agent) {
+ const busy = tx.select({ id: sessions.agentId }).from(sessions).where(and(isNotNull(sessions.agentId), notInArray(sessions.status, [...FINISHED]))).all().map((r) => r.id!);
+ agent = tx
+ .select()
+ .from(agents)
+ .where(and(isNull(agents.disabledAt), busy.length ? notInArray(agents.id, busy) : undefined))
+ // The one that rested longest goes first, so the team rotates.
+ .orderBy(sql`(select coalesce(max(s.id), 0) from sessions s where s.agent_id = ${agents.id})`, asc(agents.id))
+ .limit(1)
+ .get();
+ }
+ if (!agent) {
+ const taken = new Set(tx.select({ name: agents.name }).from(agents).all().map((r) => r.name.toLowerCase()));
+ agent = tx.insert(agents).values({ name: nextName(taken) }).returning().get();
+ }
+ tx.update(sessions).set({ agentId: agent.id }).where(eq(sessions.id, sessionId)).run();
+ return agent;
+ });
+}
+
+/** What the persona adds to the agent's system prompt. */
+export function agentPrompt(agent: Pick): string {
+ const lines = [
+ "## Твой персонаж в команде Пеппы",
+ `Тебя зовут **${agent.name}** — ты агент команды Пеппы. PM видит это имя на доске и в вопросах; если нужно представиться или подписаться — используй его.`,
+ ];
+ if (agent.character.trim()) lines.push("", "Твой характер и специализация (задал PM; правила Пеппы и AGENTS.md проекта важнее, если расходятся):", "", agent.character.trim());
+ return lines.join("\n");
+}
+
+/** Names of the personas working on stories right now: taskId → name (for the board). */
+export async function taskAgentNames(db: Db, projectId: number): Promise> {
+ const rows = await db
+ .select({ taskId: sessions.taskId, name: agents.name })
+ .from(sessions)
+ .innerJoin(agents, eq(sessions.agentId, agents.id))
+ .where(and(eq(sessions.projectId, projectId), isNotNull(sessions.taskId), notInArray(sessions.status, [...FINISHED])))
+ .orderBy(asc(sessions.id));
+ return new Map(rows.map((r) => [r.taskId!, r.name]));
+}
diff --git a/packages/db/migrations/0014_agent_team.sql b/packages/db/migrations/0014_agent_team.sql
new file mode 100644
index 00000000..a5320246
--- /dev/null
+++ b/packages/db/migrations/0014_agent_team.sql
@@ -0,0 +1,10 @@
+CREATE TABLE `agents` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `name` text NOT NULL,
+ `character` text DEFAULT '' NOT NULL,
+ `disabled_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `agents_name_unique` ON `agents` (`name`);--> statement-breakpoint
+ALTER TABLE `sessions` ADD `agent_id` integer REFERENCES agents(id);
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0014_snapshot.json b/packages/db/migrations/meta/0014_snapshot.json
new file mode 100644
index 00000000..df1b71b4
--- /dev/null
+++ b/packages/db/migrations/meta/0014_snapshot.json
@@ -0,0 +1,3727 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "c884cc4d-c58b-4874-ab39-9a1b9ce9718e",
+ "prevId": "300fd72c-077a-4631-88cc-8d38bf2ee05f",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "character": {
+ "name": "character",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "agents_name_unique": {
+ "name": "agents_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "check_runs": {
+ "name": "check_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check": {
+ "name": "check",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_sec": {
+ "name": "duration_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'report'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "check_runs_project_sha_check": {
+ "name": "check_runs_project_sha_check",
+ "columns": [
+ "project_id",
+ "sha",
+ "check"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "check_runs_project_id_projects_id_fk": {
+ "name": "check_runs_project_id_projects_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "check_runs_task_id_tasks_id_fk": {
+ "name": "check_runs_task_id_tasks_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "code_reviews": {
+ "name": "code_reviews",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "findings": {
+ "name": "findings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "code_reviews_project_id_projects_id_fk": {
+ "name": "code_reviews_project_id_projects_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "code_reviews_task_id_tasks_id_fk": {
+ "name": "code_reviews_task_id_tasks_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "error_sources": {
+ "name": "error_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "columns": [
+ "bugsink_project_id"
+ ],
+ "isUnique": true
+ },
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ "project_id",
+ "kind"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "error_sources_project_id_projects_id_fk": {
+ "name": "error_sources_project_id_projects_id_fk",
+ "tableFrom": "error_sources",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "events": {
+ "name": "events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_kind": {
+ "name": "actor_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_channel": {
+ "name": "actor_channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_client_id": {
+ "name": "actor_client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "events_created_at": {
+ "name": "events_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "events_actor_user_id_users_id_fk": {
+ "name": "events_actor_user_id_users_id_fk",
+ "tableFrom": "events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "goals": {
+ "name": "goals",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incident_settings": {
+ "name": "incident_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[\"prod\",\"production\"]'"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "columns": [
+ "hook_secret"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_settings_project_id_projects_id_fk": {
+ "name": "incident_settings_project_id_projects_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incident_settings_goal_id_goals_id_fk": {
+ "name": "incident_settings_goal_id_goals_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incidents": {
+ "name": "incidents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "columns": [
+ "bugsink_issue_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incidents_project_id_projects_id_fk": {
+ "name": "incidents_project_id_projects_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_task_id_tasks_id_fk": {
+ "name": "incidents_task_id_tasks_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_clients": {
+ "name": "oauth_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_codes": {
+ "name": "oauth_codes",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_tokens": {
+ "name": "oauth_tokens",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_invites": {
+ "name": "project_invites",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "columns": [
+ "project_id",
+ "login"
+ ],
+ "name": "project_invites_project_id_login_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_members": {
+ "name": "project_members",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "columns": [
+ "project_id",
+ "user_id"
+ ],
+ "name": "project_members_project_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_secrets": {
+ "name": "project_secrets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value_enc": {
+ "name": "value_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "project_secrets_project_name": {
+ "name": "project_secrets_project_name",
+ "columns": [
+ "project_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "project_secrets_project_id_projects_id_fk": {
+ "name": "project_secrets_project_id_projects_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_secrets_created_by_users_id_fk": {
+ "name": "project_secrets_created_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_secrets_updated_by_users_id_fk": {
+ "name": "project_secrets_updated_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "updated_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "subscription_pool_id": {
+ "name": "subscription_pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "projects_subscription_pool_id_subscription_pools_id_fk": {
+ "name": "projects_subscription_pool_id_subscription_pools_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "subscription_pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_outbox": {
+ "name": "push_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "urgency": {
+ "name": "urgency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_outbox_dedupe_key_unique": {
+ "name": "push_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_outbox_subscription_id_push_subscriptions_id_fk": {
+ "name": "push_outbox_subscription_id_push_subscriptions_id_fk",
+ "tableFrom": "push_outbox",
+ "tableTo": "push_subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_subscriptions": {
+ "name": "push_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "p256dh": {
+ "name": "p256dh",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_ok_at": {
+ "name": "last_ok_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_subscriptions_endpoint_unique": {
+ "name": "push_subscriptions_endpoint_unique",
+ "columns": [
+ "endpoint"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_subscriptions_user_id_users_id_fk": {
+ "name": "push_subscriptions_user_id_users_id_fk",
+ "tableFrom": "push_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "questions": {
+ "name": "questions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "reminders": {
+ "name": "reminders",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "releases": {
+ "name": "releases",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "previous_sha": {
+ "name": "previous_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tasks": {
+ "name": "tasks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'deploying'"
+ },
+ "deployed_by": {
+ "name": "deployed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ci'"
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "releases_project_id_projects_id_fk": {
+ "name": "releases_project_id_projects_id_fk",
+ "tableFrom": "releases",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "review_settings": {
+ "name": "review_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "max_iterations": {
+ "name": "max_iterations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 2
+ },
+ "rules": {
+ "name": "rules",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "review_settings_project_id_projects_id_fk": {
+ "name": "review_settings_project_id_projects_id_fk",
+ "tableFrom": "review_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_commands": {
+ "name": "runner_commands",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_kind": {
+ "name": "error_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor": {
+ "name": "actor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_commands_status_idx": {
+ "name": "runner_commands_status_idx",
+ "columns": [
+ "status",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_hosts": {
+ "name": "runner_hosts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_target": {
+ "name": "ssh_target",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_port": {
+ "name": "ssh_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 22
+ },
+ "workdir": {
+ "name": "workdir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'peppa'"
+ },
+ "peppa_url": {
+ "name": "peppa_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "info": {
+ "name": "info",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "runner_hosts_name_unique": {
+ "name": "runner_hosts_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_tasks": {
+ "name": "runner_tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "front": {
+ "name": "front",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_tasks_session_idx": {
+ "name": "runner_tasks_session_idx",
+ "columns": [
+ "session_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "runner_tasks_session_id_sessions_id_fk": {
+ "name": "runner_tasks_session_id_sessions_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runner_tasks_task_id_tasks_id_fk": {
+ "name": "runner_tasks_task_id_tasks_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude'"
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rotate_reason": {
+ "name": "rotate_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_id": {
+ "name": "host_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container": {
+ "name": "container",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "watch_state": {
+ "name": "watch_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "columns": [
+ "tmux_name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_subscription_id_subscriptions_id_fk": {
+ "name": "sessions_subscription_id_subscriptions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_host_id_runner_hosts_id_fk": {
+ "name": "sessions_host_id_runner_hosts_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "runner_hosts",
+ "columnsFrom": [
+ "host_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pool_members": {
+ "name": "subscription_pool_members",
+ "columns": {
+ "pool_id": {
+ "name": "pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscription_pool_members_pool_id_subscription_pools_id_fk": {
+ "name": "subscription_pool_members_pool_id_subscription_pools_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subscription_pool_members_subscription_id_subscriptions_id_fk": {
+ "name": "subscription_pool_members_subscription_id_subscriptions_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subscription_pool_members_pool_id_subscription_id_pk": {
+ "columns": [
+ "pool_id",
+ "subscription_id"
+ ],
+ "name": "subscription_pool_members_pool_id_subscription_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pools": {
+ "name": "subscription_pools",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "subscription_pools_name_unique": {
+ "name": "subscription_pools_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "subscription_pools_created_by_users_id_fk": {
+ "name": "subscription_pools_created_by_users_id_fk",
+ "tableFrom": "subscription_pools",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth_kind": {
+ "name": "auth_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret_enc": {
+ "name": "secret_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "key_provider": {
+ "name": "key_provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "limited_until": {
+ "name": "limited_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "activated_at": {
+ "name": "activated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscriptions_created_by_users_id_fk": {
+ "name": "subscriptions_created_by_users_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_deps": {
+ "name": "task_deps",
+ "columns": {
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_by_id": {
+ "name": "blocked_by_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "task_deps_blocked_by": {
+ "name": "task_deps_blocked_by",
+ "columns": [
+ "blocked_by_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "task_deps_task_id_tasks_id_fk": {
+ "name": "task_deps_task_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_deps_blocked_by_id_tasks_id_fk": {
+ "name": "task_deps_blocked_by_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "blocked_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "task_deps_task_id_blocked_by_id_pk": {
+ "columns": [
+ "task_id",
+ "blocked_by_id"
+ ],
+ "name": "task_deps_task_id_blocked_by_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tasks": {
+ "name": "tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ci_attempts": {
+ "name": "ci_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "ci_failed_sha": {
+ "name": "ci_failed_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_issue": {
+ "name": "gitea_issue",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ "project_id",
+ "number"
+ ],
+ "isUnique": true
+ },
+ "tasks_project_issue": {
+ "name": "tasks_project_issue",
+ "columns": [
+ "project_id",
+ "gitea_issue"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_outbox": {
+ "name": "telegram_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "params": {
+ "name": "params",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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 ab59703e..09e80588 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -99,6 +99,13 @@
"when": 1794624555440,
"tag": "0013_runner_hosts",
"breakpoints": true
+ },
+ {
+ "idx": 14,
+ "version": "6",
+ "when": 1794663938633,
+ "tag": "0014_agent_team",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index 07387751..bad12eee 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -256,6 +256,16 @@ export const subscriptionPoolMembers = sqliteTable(
* PEP-40: a server runners run on. Peppa reaches it over SSH with its own key; tmux and the
* agent's container live there (PEP-17). No daemon on the host.
*/
+// PEP-75: the platform's team of agent personas — a name on the board and a character
+// (markdown) appended to the agent's prompt. A runner takes a free persona for its story.
+export const agents = sqliteTable("agents", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ name: text("name").notNull().unique(),
+ character: text("character").notNull().default(""),
+ disabledAt: integer("disabled_at", { mode: "timestamp_ms" }),
+ createdAt: createdAt(),
+});
+
export const runnerHosts = sqliteTable("runner_hosts", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull().unique(),
@@ -314,6 +324,8 @@ export const sessions = sqliteTable("sessions", {
hostId: integer("host_id").references(() => runnerHosts.id, { onDelete: "set null" }),
// PEP-17: the agent's docker container (null = the agent runs directly in tmux).
container: text("container"),
+ // PEP-75: the persona working in this runner (kept across resumes and across runners of a story).
+ agentId: integer("agent_id").references(() => agents.id, { onDelete: "set null" }),
// 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(),
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 20876aa6..86aaf6ad 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -16,6 +16,8 @@ import {
listSessions,
loadSharedRules,
memoryContext,
+ agentPrompt,
+ ensureSessionAgent,
checkEscalation,
launchModelFor,
resolveAgentSettings,
@@ -250,6 +252,9 @@ async function launch(
// On a host (PEP-40) the working copy is not here: the project's own copy stands in.
const memDir = s.host ? (await db.select().from(projects).where(eq(projects.id, s.projectId)))[0]?.workspacePath ?? cwd : cwd;
const memory = await memoryContext(db, s.projectId, memDir).catch(() => "");
+ // PEP-75: the runner's persona (assigned on the first launch) — name and character in the prompt.
+ const persona = await ensureSessionAgent(db, s.id).catch(() => null);
+ const extras = [memory, persona ? agentPrompt(persona) : ""].filter(Boolean).join("\n\n");
// 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).
@@ -271,7 +276,7 @@ async function launch(
generation,
cwd,
prompt: opts.prompt,
- rules: memory ? `${rules.text}\n\n${memory}` : rules.text,
+ rules: extras ? `${rules.text}\n\n${extras}` : rules.text,
resume: opts.resume,
permissionMode: opts.permissionMode,
model,
diff --git a/packages/testkit/test/team.test.ts b/packages/testkit/test/team.test.ts
new file mode 100644
index 00000000..7b8f4047
--- /dev/null
+++ b/packages/testkit/test/team.test.ts
@@ -0,0 +1,74 @@
+// PEP-75: the platform's team of agents — Kazakh names, one persona per story, character in the
+// agent's prompt (mock-claude sees it in the rules file).
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { after, describe, test } from "node:test";
+import { core, db, project, runner, teardown } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+after(teardown);
+
+const rulesOf = (e: object) => {
+ const argv = (e as { argv?: string[] }).argv ?? [];
+ return readFileSync(argv[argv.indexOf("--append-system-prompt-file") + 1]!, "utf8");
+};
+
+describe("Команда агентов", () => {
+ test("Scenario: первая стори получает агента с казахским именем, имя и характер — в промпте", async () => {
+ assert.deepEqual(await core.listAgents(db), []);
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ const sid = await p.start();
+ const start = await p.waitLog("started", (e) => e.ev === "start");
+ const s = await core.getSession(db, sid);
+ assert.equal(s.agentName, core.AGENT_NAMES[0]);
+ assert.match(rulesOf(start), new RegExp(`Тебя зовут \\*\\*${core.AGENT_NAMES[0]}\\*\\*`));
+ const proj = await core.getProject(db, p.key);
+ assert.equal((await core.taskAgentNames(db, proj.id)).get((await p.task()).id), core.AGENT_NAMES[0]);
+ const [a] = await core.listAgents(db);
+ assert.equal(a!.busy, 1);
+
+ // The PM gives a character; a resume of the same runner keeps the persona and carries it.
+ await core.updateAgent(db, a!.id, { character: "Педант по безопасности: любой ввод проверяет." });
+ await runner.stopSession(db, sid);
+ await runner.resumeSession(db, sid, { prompt: "дальше" });
+ const again = await p.waitLog("resumed", (e) => e.ev === "start" && rulesOf(e).includes("Педант по безопасности"));
+ assert.match(rulesOf(again), /правила Пеппы и AGENTS\.md проекта важнее/);
+ assert.equal((await core.getSession(db, sid)).agentName, core.AGENT_NAMES[0]);
+ await runner.stopSession(db, sid);
+ });
+
+ test("Scenario: занятый агент не делится — второй раннер получает нового; свободный берётся снова", async () => {
+ const p1 = await project({ turns: [[{ say: "ok" }]] });
+ const p2 = await project({ turns: [[{ say: "ok" }]] });
+ const s1 = await p1.start();
+ const s2 = await p2.start();
+ const n1 = (await core.getSession(db, s1)).agentName;
+ const n2 = (await core.getSession(db, s2)).agentName;
+ assert.equal(n1, core.AGENT_NAMES[0], "the free persona of the first test is reused");
+ assert.equal(n2, core.AGENT_NAMES[1], "everyone busy → a new persona with the next name");
+ await runner.stopSession(db, s1);
+ await runner.stopSession(db, s2);
+
+ // The story's next runner gets the story's persona, even though another one rested longer.
+ const s3 = await p2.start();
+ assert.equal((await core.getSession(db, s3)).agentName, n2);
+ await runner.stopSession(db, s3);
+ });
+
+ test("имена: свои, дубли, выбывший из команды", async () => {
+ const mine = await core.createAgent(db, { name: " Қайсар " });
+ assert.equal(mine.name, "Қайсар");
+ await assert.rejects(core.createAgent(db, { name: "қайсар" }), /уже есть/);
+ await assert.rejects(core.updateAgent(db, mine.id, { name: core.AGENT_NAMES[0] }), /уже есть/);
+ await assert.rejects(core.updateAgent(db, mine.id, { character: "x".repeat(core.AGENT_CHARACTER_MAX + 1) }), /длиннее/);
+ assert.equal((await core.createAgent(db)).name, core.AGENT_NAMES[2], "auto name = the next free one");
+
+ // Out of the team: not picked for new stories.
+ for (const a of await core.listAgents(db)) if (a.id !== mine.id) await core.updateAgent(db, a.id, { disabled: true });
+ const p = await project({ turns: [[{ say: "ok" }]] });
+ const sid = await p.start();
+ assert.equal((await core.getSession(db, sid)).agentName, "Қайсар");
+ await runner.stopSession(db, sid);
+ assert.equal(core.agentPrompt({ name: "Дана", character: "" }).includes("характер"), false);
+ });
+});
--
2.45.2
From b3766d200d80d30a95a185c2fa8917e3ad7b8f09 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 19:02:55 +0500
Subject: [PATCH 012/439] PEP-62: chats model, projection of events into
project chats, master feed, post to chat
Co-Authored-By: Claude Opus 5.5
---
openspec/changes/pep-62-chats/design.md | 84 +
openspec/changes/pep-62-chats/proposal.md | 50 +
.../pep-62-chats/specs/project-chats/spec.md | 96 +
openspec/changes/pep-62-chats/tasks.md | 21 +
packages/core/src/chats.ts | 544 +++
packages/core/src/index.ts | 1 +
packages/core/src/notifications.ts | 19 +
packages/core/src/notify.ts | 3 +-
packages/core/src/projects.ts | 4 +-
packages/core/src/tasks.ts | 4 +-
packages/db/migrations/0015_chats.sql | 48 +
.../db/migrations/meta/0015_snapshot.json | 4106 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 48 +
packages/runner/src/chats.ts | 184 +
packages/runner/src/index.ts | 1 +
16 files changed, 5216 insertions(+), 4 deletions(-)
create mode 100644 openspec/changes/pep-62-chats/design.md
create mode 100644 openspec/changes/pep-62-chats/proposal.md
create mode 100644 openspec/changes/pep-62-chats/specs/project-chats/spec.md
create mode 100644 openspec/changes/pep-62-chats/tasks.md
create mode 100644 packages/core/src/chats.ts
create mode 100644 packages/db/migrations/0015_chats.sql
create mode 100644 packages/db/migrations/meta/0015_snapshot.json
create mode 100644 packages/runner/src/chats.ts
diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/pep-62-chats/design.md
new file mode 100644
index 00000000..eb2c3412
--- /dev/null
+++ b/openspec/changes/pep-62-chats/design.md
@@ -0,0 +1,84 @@
+# Design: PEP-62 — чаты
+
+## Решения PM (2026-11-13)
+- Telegram: обычная группа на проект, треды = цепочки реплаев (без тем форума).
+- Мастер-чат: лента событий и команды, без LLM.
+- Чаты рядом с Главной; вопросы видны и в треде, и на Главной.
+- Переписку чатов храним недолго (TTL); задачи/вопросы/события — в своих таблицах.
+
+## Модель данных
+- `chats`: `kind` (`master`|`project`), `user_id` (master, уникален), `project_id` (project,
+ уникален), Telegram-группа `tg_chat_id` (уникальна: одна группа — один чат), `tg_title`,
+ `tg_linked_at`, `tg_linked_by`.
+- `chat_messages`: `chat_id`, `thread_key` (`task:` / `incident:` / `release:`;
+ null = общий канал), `thread_title` (снимок, чтобы тред читался и после удаления сущности),
+ `kind` (`event`|`question`|`user`|`system`), `important` (попадает в мастер-ленту),
+ автор (`author_kind` system/agent/user, `author_user_id`, `author_login`, `via` web/telegram),
+ `text`, `question_id`, `task_id`, `url`, `dedupe_key` (уникален — проекция идемпотентна),
+ `tg_chat_id`/`tg_message_id` (сообщение пришло из Telegram — по нему находим тред реплая).
+- `telegram_outbox.chat_message_id` — какое сообщение чата ушло в группу; по нему
+ реплай в группе находит тред, а бот при отправке находит «якорь» треда.
+- Тредов как таблицы нет: тред = `thread_key` в сообщениях; список тредов — group by.
+
+## Откуда берутся сообщения — проекция
+`syncChats(db)` (core) идемпотентно переносит в чаты:
+- `events` по курсору `chat.cursor.events` (id): `task_updated` со сменой статуса, `progress`,
+ `pm_comment`, `question_answered`, `pr_merged_in_gitea`, сбои раннера (`stalled`,
+ `stop_failure`, `exited`, `usage_limit`, `auto_restarted`, `restart_failed`,
+ `budget_paused`, `subscription_switched`, `model_escalated`), `started`/`stopped`;
+- `questions` по курсору `chat.cursor.questions` → сообщение-вопрос (состояние ответа
+ читается из `questions` при показе, кнопки — те же, что на Главной);
+- `releases` и `incidents` по `updated_at` (окно с запасом) → сообщение на каждую пару
+ (id, статус): `dedupe_key = release::`.
+Первый запуск без курсора берёт только последние сутки — не заливаем историю.
+Вызывают: бот (вместе с `reconcile`, т.е. ≤1 с после записи), вачдог (`tick`) и веб при
+рендере страницы чатов — кто первый, тот и перенёс, дубли отсекает `dedupe_key`.
+Почему проекция, а не вызовы в каждом месте: источников десятки (хуки, вачдог, CI, деплой),
+проекция не трогает их код и переживает падение любого процесса.
+
+Мастер-лента не копирует сообщения: это собственные сообщения мастер-чата (команды,
+ответы, мониторинг и дайджест из `deliverToUser`) ∪ `important` сообщения чатов доступных
+проектов (кроме выключенных в настройках уведомлений).
+
+## Ответ в треде (runner/chats.ts `postToChat`)
+- Проверка доступа: проект — `projectForUser`; мастер — только его владелец.
+- Текст с `/` — команда (`/help`, `/status`, `/task KEY-N`, `/move KEY-N <колонка>`), ответ —
+ системное сообщение в тот же тред.
+- Тред стори: конкретный вопрос (реплай в Telegram на вопрос) или последний открытый вопрос
+ стори → `answerAndDeliver`; иначе `addStoryComment` + `sendToSession`, если раннер жив.
+ Итог («Ответ ушёл агенту ✅» / «Комментарий сохранён…») — системное сообщение.
+- Тред инцидента/релиза и общий канал — заметка в чате (агенту ничего не уходит).
+Функции жизненного цикла (`answerAndDeliver`, `sendToSession`, `moveTask`) у клиентов
+PEP-21 сами уходят в раннер-сервис.
+
+## Telegram
+- **Связка**: веб «Связать с Telegram» → код (HMAC в `settings` `chat.link:`, 10 мин) →
+ ссылка `https://t.me/?startgroup=<код>` (Telegram добавит бота и пришлёт
+ `/start <код>`) или `/link <код>` в группе. Группа, связанная с другим чатом,
+ перепривязывается. `migrate_to_chat_id` (группа стала супергруппой) переносит связку.
+ «Отвязать» — в вебе.
+- **Зеркало** (бот, курсор `chat.mirror.cursor`): новое сообщение чата → `sendMessage` в
+ группу чата; `important` сообщение проекта — ещё и в мастер-группы участников проекта.
+ Сообщение, пришедшее из этой же группы, обратно не шлётся. Тред: первое сообщение треда в
+ группе — с заголовком «🧵 PEP-42 · название», остальные — реплаем на него (якорь ищется при
+ отправке, `allow_sending_without_reply`). Вопрос — с кнопками (`questionId` в outbox, так
+ что существующая правка «отвечено» и `questionByTelegramMessage` работают и в группе).
+- **Приём**: сообщение в связанной группе → пользователь по `users.telegram_user_id`
+ (личная привязка PEP-2) и не отключён → доступ к проекту / владелец мастер-чата.
+ Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); иначе — общий
+ канал. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает
+ привязать Telegram. Privacy mode бота оставляем: он видит команды и реплаи на свои
+ сообщения — этого достаточно для тредов.
+- Личные уведомления в личку не меняются (их можно выключить по проекту в «Уведомлениях»).
+
+## TTL
+`PEPPA_CHAT_TTL_DAYS` (14) — `pruneChats` в вачдоге раз в час удаляет старые сообщения
+(outbox теряет ссылку — `ON DELETE SET NULL`; реплай на такое сообщение уходит в общий канал).
+
+## Живое обновление
+Область `chats` у `/api/live`: отпечаток — max id сообщений чатов, вопросов и событий без
+шагов; страница при обновлении снова вызывает `syncChats`.
+
+## Вне scope
+- Темы форума Telegram, LLM-ассистент, слияние Главной с чатами (решения PM).
+- Push по сообщениям чатов (уведомления остаются как в PEP-35).
diff --git a/openspec/changes/pep-62-chats/proposal.md b/openspec/changes/pep-62-chats/proposal.md
new file mode 100644
index 00000000..a6853e73
--- /dev/null
+++ b/openspec/changes/pep-62-chats/proposal.md
@@ -0,0 +1,50 @@
+# Proposal: PEP-62 — чаты: мастер-чат и чат проекта с тредами, связка с Telegram-группой
+
+Стори Пеппы: **PEP-62** · эпик «Удобство для PM» · связано с PEP-2, PEP-35, PEP-37, PEP-45, PEP-60, PEP-61.
+
+## Why
+
+Уведомления и диалоги с агентами разбросаны: вопросы — на Главной и в личке бота, прогресс и
+сбои — в журнале стори, релизы и ошибки — по своим вкладкам. PM хочет одно место, как
+каналы в Slack: чат проекта с тредами по стори, инцидентам и релизам и мастер-чат со всем
+важным, — и чтобы проект можно было вести из своей Telegram-группы.
+
+## What Changes
+
+- **Раздел «Чаты»** в меню веба (рядом с Главной; Главная и вопросы на ней не меняются).
+- **Чат проекта** создаётся вместе с проектом (у старых проектов — при первом обращении).
+ Треды: стори (`task:` — вопросы агента, смена статуса, прогресс, комментарии,
+ ревью, сбои раннера), инцидент (`incident:`), релиз (`release:`); общий канал —
+ то, что не про конкретную вещь.
+- **Мастер-чат** — у каждого пользователя свой: лента важного по всем его проектам (вопросы,
+ «готово к ревью», сбои, лимиты, релизы, ошибки из прода), мониторинг и дайджест, плюс
+ команды `/status`, `/task KEY-N`, `/move KEY-N <колонка>`, `/help`. Без LLM (решение PM).
+- **Ответ в треде = ответ агенту**: есть открытый вопрос стори — ответ на него
+ (`answerAndDeliver`); нет — комментарий PM к стори (агент видит в `get_task`) и, если раннер
+ жив, текст уходит в сессию.
+- **Telegram-группа**: любой чат (проект или мастер) связывается с обычной группой по
+ одноразовому коду (кнопка «Связать» → ссылка `t.me/?startgroup=<код>` или `/link <код>`
+ в группе). Сообщения чата дублируются в группу, тред = цепочка реплаев на первое сообщение
+ треда (без тем форума — решение PM). Ответ реплаем в группе виден в вебе и уходит агенту;
+ кнопки вопросов работают и в группе. Отвечать могут только люди Пеппы с привязанным
+ Telegram (PEP-2) и доступом к проекту; в мастер-группе — только владелец мастер-чата.
+ Личная привязка и личные уведомления (PEP-2/35) не меняются.
+- **Короткое хранение**: сообщения чатов живут `PEPPA_CHAT_TTL_DAYS` (по умолчанию 14) дней и
+ удаляются вачдогом; стори, вопросы, события, релизы и инциденты остаются в своих таблицах.
+
+## Capabilities
+
+### New Capabilities
+- `project-chats`: чаты проектов и мастер-чат, треды, ответы агентам, связка с Telegram-группой, TTL.
+
+### Modified Capabilities
+
+## Impact
+
+- **Модель данных** (решено PM: отдельная сущность с коротким сроком): таблицы `chats`,
+ `chat_messages`, колонка `telegram_outbox.chat_message_id`; миграция.
+- `packages/core/src/chats.ts` — проекция событий в сообщения, ленты, коды связки, TTL.
+- `packages/runner/src/chats.ts` — сообщение в тред/канал (ответ агенту, команды).
+- `apps/bot` — зеркало сообщений в группы, приём реплаев/команд/кнопок из групп, `/link`.
+- `apps/web` — `/chats/[chat]`, пункт меню «Чаты», живое обновление (область `chats`).
+- Вачдог — проекция и чистка по TTL.
diff --git a/openspec/changes/pep-62-chats/specs/project-chats/spec.md b/openspec/changes/pep-62-chats/specs/project-chats/spec.md
new file mode 100644
index 00000000..d75ef5e8
--- /dev/null
+++ b/openspec/changes/pep-62-chats/specs/project-chats/spec.md
@@ -0,0 +1,96 @@
+## ADDED Requirements
+
+### Requirement: Чат проекта с тредами
+У каждого проекта SHALL быть чат. События проекта SHALL попадать в чат: про стори — в тред
+стори, про инцидент — в тред инцидента, про релиз — в тред релиза, остальное — в общий
+канал. Перенос событий SHALL быть идемпотентным: повторный запуск не создаёт дублей.
+
+#### Scenario: Вопрос агента в треде стори
+- **GIVEN** проект PAY со стори PAY-7 «Экспорт в CSV»
+- **WHEN** агент PAY-7 задаёт вопрос «Какой разделитель?»
+- **THEN** в чате PAY появляется тред «PAY-7 · Экспорт в CSV» с этим вопросом и кнопками ответа
+- **AND** вопрос по-прежнему виден на Главной
+
+#### Scenario: Повторный перенос
+- **GIVEN** вопрос PAY-7 уже перенесён в чат
+- **WHEN** перенос запускается ещё раз из бота и из веба
+- **THEN** в треде PAY-7 одно сообщение с этим вопросом
+
+### Requirement: Ответ в треде уходит агенту
+Сообщение участника в треде стори SHALL отвечать на открытый вопрос стори, а без открытого
+вопроса — становиться комментарием PM к стори и уходить в живой раннер. Сообщение в треде
+инцидента, релиза или в общем канале SHALL оставаться заметкой. Писать в чат проекта SHALL
+могут только владелец и участники проекта.
+
+#### Scenario: Ответ на вопрос
+- **GIVEN** у PAY-7 открыт вопрос «Какой разделитель?»
+- **WHEN** участник пишет в тред PAY-7 «точка с запятой»
+- **THEN** вопрос отвечен «точка с запятой», ответ ушёл в сессию агента
+- **AND** в треде видно сообщение участника и отметку «Ответ ушёл агенту»
+
+#### Scenario: Комментарий без вопроса
+- **GIVEN** у PAY-7 нет открытых вопросов и раннер не запущен
+- **WHEN** участник пишет в тред PAY-7 «не забудь заголовки»
+- **THEN** у стори появляется комментарий PM «не забудь заголовки», агент увидит его в get_task
+
+#### Scenario: Чужой проект
+- **GIVEN** пользователь «bob» не участник проекта PAY
+- **WHEN** он пытается написать в чат PAY
+- **THEN** запрос отклонён как «не найдено», сообщения в чате нет
+
+### Requirement: Мастер-чат
+У каждого пользователя SHALL быть мастер-чат: важные события всех его проектов (вопросы,
+готово к ревью, сбои и лимиты раннеров, релизы, ошибки из прода), мониторинг и дайджест.
+Мастер-чат SHALL выполнять команды `/help`, `/status`, `/task KEY-N`, `/move KEY-N <колонка>`
+без LLM; писать в мастер-чат SHALL может только его владелец.
+
+#### Scenario: Сбой раннера в мастер-чате
+- **GIVEN** пользователь «anna» владеет проектом PAY
+- **WHEN** раннер PAY-7 зависает
+- **THEN** в мастер-чате «anna» видно сообщение о зависании PAY-7 со ссылкой на тред
+
+#### Scenario: Команда перемещения
+- **GIVEN** стори PAY-8 в бэклоге проекта «anna»
+- **WHEN** «anna» пишет в мастер-чат `/move PAY-8 in_progress`
+- **THEN** стори PAY-8 в работе, агент запущен, в мастер-чате ответ «PAY-8 → В работе»
+
+#### Scenario: Неизвестная команда
+- **WHEN** «anna» пишет в мастер-чат `/deploy всё`
+- **THEN** в ответ — «Не знаю такую команду» и список команд, ничего не выполнено
+
+### Requirement: Связка чата с Telegram-группой
+Чат проекта и мастер-чат SHALL связываться с обычной Telegram-группой по одноразовому коду
+(10 минут). Сообщения связанного чата SHALL дублироваться в группу, тред — цепочкой реплаев
+на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и обрабатываться как
+сообщение из веба; принимать его SHALL только от пользователя Пеппы с привязанным Telegram и
+доступом к проекту (в мастер-группе — от владельца мастер-чата).
+
+#### Scenario: Связать группу
+- **GIVEN** участник открыл чат PAY и нажал «Связать с Telegram»
+- **WHEN** в группе «PAY team» отправлено `/link <код>` до истечения кода
+- **THEN** чат PAY связан с «PAY team», бот подтверждает это в группе, веб показывает название группы
+
+#### Scenario: Просроченный код
+- **GIVEN** код связки выдан 11 минут назад
+- **WHEN** в группе отправлено `/link <код>`
+- **THEN** бот отвечает, что код неверный или истёк, чат не связан
+
+#### Scenario: Ответ реплаем из группы
+- **GIVEN** чат PAY связан с группой, вопрос PAY-7 пришёл в группу
+- **AND** «anna» привязала Telegram и участник PAY
+- **WHEN** «anna» отвечает реплаем на вопрос «точка с запятой»
+- **THEN** вопрос отвечен, в веб-треде PAY-7 видно её сообщение с пометкой Telegram
+
+#### Scenario: Посторонний в группе
+- **GIVEN** в группе PAY есть человек без привязки Telegram в Пеппе
+- **WHEN** он отвечает реплаем на вопрос PAY-7
+- **THEN** вопрос не отвечен, сообщения в чате нет, бот подсказывает привязать Telegram
+
+### Requirement: Короткое хранение переписки
+Сообщения чатов SHALL удаляться через `PEPPA_CHAT_TTL_DAYS` дней (по умолчанию 14); стори,
+вопросы, события, релизы и инциденты при этом SHALL оставаться.
+
+#### Scenario: Старые сообщения удалены
+- **GIVEN** сообщение в треде PAY-7 от 15 дней назад и вопрос PAY-7, к которому оно относится
+- **WHEN** вачдог чистит чаты
+- **THEN** сообщения в чате нет, вопрос PAY-7 остаётся в стори
diff --git a/openspec/changes/pep-62-chats/tasks.md b/openspec/changes/pep-62-chats/tasks.md
new file mode 100644
index 00000000..cbf0dcdf
--- /dev/null
+++ b/openspec/changes/pep-62-chats/tasks.md
@@ -0,0 +1,21 @@
+## 1. Модель и ядро
+- [ ] 1.1 Схема `chats`, `chat_messages`, `telegram_outbox.chat_message_id`, миграция
+- [ ] 1.2 core/chats.ts: чаты (ensure), проекция `syncChats`, ленты/треды, коды связки, TTL
+- [ ] 1.3 Мастер-чат: мониторинг и дайджест из `deliverToUser`
+
+## 2. Ответы и команды
+- [ ] 2.1 runner/chats.ts `postToChat`: ответ агенту / комментарий / заметка, команды
+
+## 3. Telegram
+- [ ] 3.1 Бот: связка группы (`/start <код>`, `/link`), миграция в супергруппу
+- [ ] 3.2 Бот: зеркало сообщений в группы, треды реплаями, кнопки вопросов
+- [ ] 3.3 Бот: приём реплаев, команд и кнопок из групп с проверкой доступа
+
+## 4. Веб и вачдог
+- [ ] 4.1 `/chats/[chat]`: список чатов, треды, лента, композер, связка с Telegram; меню
+- [ ] 4.2 Живое обновление (`chats`), вызовы проекции и TTL в вачдоге, создание чата с проектом
+- [ ] 4.3 Справка `/help`, AGENTS.md
+
+## 5. Проверка
+- [ ] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
+- [ ] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
new file mode 100644
index 00000000..1422ed20
--- /dev/null
+++ b/packages/core/src/chats.ts
@@ -0,0 +1,544 @@
+// PEP-62: chats — a channel per project with threads (story / incident / release) and a master
+// chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events,
+// questions, releases and incidents, which stay in their own tables; people's messages are
+// stored here too. Telegram groups linked to chats are the bot's business (apps/bot).
+import { createHmac, randomBytes } from "node:crypto";
+import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+import { getNotifyPrefs, projectAudience } from "./notifications.ts";
+import { notify } from "./notify.ts";
+import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+import { projectForUser, userProjectIds, type User } from "./users.ts";
+import type { OutboxRow } from "./telegram.ts";
+
+export type Chat = typeof chats.$inferSelect;
+export type ChatMessage = typeof chatMessages.$inferSelect;
+export type NewChatMessage = typeof chatMessages.$inferInsert;
+
+const DAY = 24 * 3600_000;
+export const chatTtlMs = () => Math.max(1, Number(process.env.PEPPA_CHAT_TTL_DAYS ?? 14) || 14) * DAY;
+
+// ── chats ──────────────────────────────────────────────────────────────────────────
+
+export async function ensureProjectChat(db: Db, projectId: number): Promise {
+ await db.insert(chats).values({ kind: "project", projectId }).onConflictDoNothing();
+ const [c] = await db.select().from(chats).where(eq(chats.projectId, projectId));
+ return c!;
+}
+
+export async function ensureMasterChat(db: Db, userId: number): Promise {
+ await db.insert(chats).values({ kind: "master", userId }).onConflictDoNothing();
+ const [c] = await db.select().from(chats).where(eq(chats.userId, userId));
+ return c!;
+}
+
+export async function getChat(db: Db, id: number): Promise {
+ const [c] = await db.select().from(chats).where(eq(chats.id, id));
+ if (!c) throw new PeppaError("Чат не найден");
+ return c;
+}
+
+/** The chat if this user may read and write it: project chat — owner/members, master — its owner. */
+export async function chatForUser(db: Db, user: Pick, chatId: number): Promise {
+ const c = await getChat(db, chatId);
+ if (c.kind === "master") {
+ if (c.userId !== user.id) throw new PeppaError("Чат не найден");
+ } else await projectForUser(db, user.id, c.projectId!).catch(() => {
+ throw new PeppaError("Чат не найден");
+ });
+ return c;
+}
+
+export async function chatByTelegram(db: Db, tgChatId: number): Promise {
+ const [c] = await db.select().from(chats).where(eq(chats.tgChatId, tgChatId));
+ return c ?? null;
+}
+
+export interface ChatListItem {
+ id: number;
+ kind: Chat["kind"];
+ /** "master" or the project key — the URL segment of /chats/. */
+ slug: string;
+ title: string;
+ projectId: number | null;
+ tgTitle: string | null;
+ lastAt: Date | null;
+ /** Open agent questions of the project (the master chat: all of the user's). */
+ open: number;
+}
+
+/** The master chat and the chats of the user's projects (created on first look). */
+export async function listChats(db: Db, user: Pick): Promise {
+ const master = await ensureMasterChat(db, user.id);
+ const ids = await userProjectIds(db, user.id);
+ const ps = ids.length ? await db.select().from(projects).where(inArray(projects.id, ids)).orderBy(asc(projects.key)) : [];
+ const projectChats = new Map();
+ for (const p of ps) projectChats.set(p.id, await ensureProjectChat(db, p.id));
+ const chatIds = [master.id, ...[...projectChats.values()].map((c) => c.id)];
+ const last = new Map(
+ (await db.select({ chatId: chatMessages.chatId, at: sql`max(${chatMessages.createdAt})` }).from(chatMessages).where(inArray(chatMessages.chatId, chatIds)).groupBy(chatMessages.chatId)).map((r) => [r.chatId, r.at ? new Date(Number(r.at)) : null]),
+ );
+ const open = new Map(
+ ids.length
+ ? (await db.select({ p: questions.projectId, n: sql`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)])
+ : [],
+ );
+ const masterAt = [...last.values()].reduce((a, b) => (b && (!a || b > a) ? b : a), null);
+ return [
+ { id: master.id, kind: "master", slug: "master", title: "Мастер-чат", projectId: null, tgTitle: master.tgTitle, lastAt: masterAt, open: [...open.values()].reduce((a, b) => a + b, 0) },
+ ...ps.map((p) => {
+ const c = projectChats.get(p.id)!;
+ return { id: c.id, kind: "project" as const, slug: p.key, title: `${p.key} · ${p.name}`, projectId: p.id, tgTitle: c.tgTitle, lastAt: last.get(c.id) ?? null, open: open.get(p.id) ?? 0 };
+ }),
+ ];
+}
+
+// ── messages ───────────────────────────────────────────────────────────────────────
+
+/** Adds a message; with a `dedupeKey` seen before it is a no-op and returns null. */
+export async function addChatMessage(db: Db, m: NewChatMessage): Promise {
+ if (m.threadKey && m.threadTitle == null) {
+ const [prev] = await db
+ .select({ t: chatMessages.threadTitle })
+ .from(chatMessages)
+ .where(and(eq(chatMessages.chatId, m.chatId), eq(chatMessages.threadKey, m.threadKey), isNotNull(chatMessages.threadTitle)))
+ .orderBy(desc(chatMessages.id))
+ .limit(1);
+ m = { ...m, threadTitle: prev?.t ?? (await threadTitle(db, m.threadKey)) };
+ }
+ const [row] = await db.insert(chatMessages).values(m).onConflictDoNothing().returning();
+ return row ?? null;
+}
+
+/** A message in the user's master chat (monitoring, digest, command replies). */
+export async function addMasterMessage(db: Db, userId: number, m: Omit): Promise {
+ const chat = await ensureMasterChat(db, userId);
+ const row = await addChatMessage(db, { ...m, chatId: chat.id });
+ if (row) await notify(db, { type: "chat_message", messageId: row.id });
+ return row;
+}
+
+/** Current title of a thread: "PAY-7 · Экспорт", "Ошибка: …", "Релиз staging abc1234". */
+export async function threadTitle(db: Db, key: string): Promise {
+ const [kind, raw] = key.split(":");
+ const id = Number(raw);
+ if (kind === "task") {
+ const [t] = await db.select({ key: projects.key, n: tasks.number, title: tasks.title }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, id));
+ return t ? `${formatTaskKey(t.key, t.n)} · ${t.title}` : null;
+ }
+ if (kind === "incident") {
+ const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id));
+ return i ? `Ошибка: ${i.title}` : null;
+ }
+ if (kind === "release") {
+ const [r] = await db.select({ env: releases.env, sha: releases.sha }).from(releases).where(eq(releases.id, id));
+ return r ? `Релиз ${r.env} ${r.sha.slice(0, 7)}` : null;
+ }
+ return null;
+}
+
+export const THREAD_KEY = /^(task|incident|release):[1-9]\d{0,9}$/;
+
+export interface ChatMessageView {
+ id: number;
+ chatId: number;
+ /** Project of the chat the message lives in (master feed mixes projects). */
+ projectKey: string | null;
+ threadKey: string | null;
+ threadTitle: string | null;
+ kind: ChatMessage["kind"];
+ important: boolean;
+ authorKind: ChatMessage["authorKind"];
+ authorLogin: string | null;
+ via: ChatMessage["via"];
+ text: string;
+ url: string | null;
+ createdAt: Date;
+ /** A question message: its live state (answered elsewhere shows here too). */
+ question: { id: number; kind: string; options: string[] | null; answer: string | null; answeredVia: string | null; answeredAt: Date | null } | null;
+}
+
+async function views(db: Db, where: SQL, limit: number, before?: number): Promise {
+ const rows = await db
+ .select({ m: chatMessages, projectKey: projects.key, q: questions })
+ .from(chatMessages)
+ .innerJoin(chats, eq(chatMessages.chatId, chats.id))
+ .leftJoin(projects, eq(chats.projectId, projects.id))
+ .leftJoin(questions, eq(chatMessages.questionId, questions.id))
+ .where(before ? and(where, lt(chatMessages.id, before)) : where)
+ .orderBy(desc(chatMessages.id))
+ .limit(Math.min(limit, 500));
+ return rows.reverse().map(({ m, projectKey, q }) => ({
+ id: m.id,
+ chatId: m.chatId,
+ projectKey,
+ threadKey: m.threadKey,
+ threadTitle: m.threadTitle,
+ kind: m.kind,
+ important: m.important,
+ authorKind: m.authorKind,
+ authorLogin: m.authorLogin,
+ via: m.via,
+ text: m.text,
+ url: m.url,
+ createdAt: m.createdAt,
+ question: q ? { id: q.id, kind: q.kind, options: q.options ?? null, answer: q.answer, answeredVia: q.answeredVia, answeredAt: q.answeredAt } : null,
+ }));
+}
+
+/** Messages of a chat: the whole stream, or one thread (`threadKey`), or the channel only (null). */
+export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?: string | null; limit?: number; before?: number } = {}): Promise {
+ const w: SQL[] = [eq(chatMessages.chatId, chatId)];
+ if (o.threadKey === null) w.push(isNull(chatMessages.threadKey));
+ else if (o.threadKey) w.push(eq(chatMessages.threadKey, o.threadKey));
+ return views(db, and(...w)!, o.limit ?? 100, o.before);
+}
+
+/**
+ * The master feed: the user's own master messages and the important messages of the chats
+ * of their projects (muted projects left out). `threadKey` narrows it to one project thread.
+ */
+export async function masterFeed(db: Db, user: Pick, o: { limit?: number; threadKey?: string; before?: number } = {}): Promise {
+ const master = await ensureMasterChat(db, user.id);
+ const muted = new Set((await getNotifyPrefs(db, user.id)).mutedProjects);
+ const ids = (await userProjectIds(db, user.id)).filter((id) => !muted.has(id));
+ const projectChats = ids.length ? (await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids))).map((c) => c.id) : [];
+ const fromProjects = projectChats.length ? and(inArray(chatMessages.chatId, projectChats), eq(chatMessages.important, true)) : undefined;
+ let where: SQL = fromProjects ? or(eq(chatMessages.chatId, master.id), fromProjects)! : eq(chatMessages.chatId, master.id);
+ if (o.threadKey) where = and(where, eq(chatMessages.threadKey, o.threadKey))!;
+ return views(db, where, o.limit ?? 100, o.before);
+}
+
+export interface ThreadView {
+ key: string;
+ title: string;
+ count: number;
+ lastAt: Date;
+ /** Unanswered questions in the thread. */
+ open: number;
+}
+
+/** Threads of a project chat, most recently active first. */
+export async function chatThreads(db: Db, chatId: number, limit = 50): Promise {
+ const rows = await db
+ .select({
+ key: chatMessages.threadKey,
+ title: sql`max(${chatMessages.threadTitle})`,
+ count: sql`count(*)`,
+ lastId: sql`max(${chatMessages.id})`,
+ lastAt: sql`max(${chatMessages.createdAt})`,
+ open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`,
+ })
+ .from(chatMessages)
+ .leftJoin(questions, eq(chatMessages.questionId, questions.id))
+ .where(and(eq(chatMessages.chatId, chatId), isNotNull(chatMessages.threadKey)))
+ .groupBy(chatMessages.threadKey)
+ .orderBy(desc(sql`max(${chatMessages.id})`))
+ .limit(limit);
+ return rows.map((r) => ({ key: r.key!, title: r.title ?? r.key!, count: Number(r.count), lastAt: new Date(Number(r.lastAt)), open: Number(r.open) || 0 }));
+}
+
+// ── projection ─────────────────────────────────────────────────────────────────────
+
+const CURSOR_EVENTS = "chat.cursor.events";
+const CURSOR_QUESTIONS = "chat.cursor.questions";
+const CURSOR_OBJECTS = "chat.cursor.objects";
+const BATCH = 500;
+
+const STATUS_RU: Record = {
+ backlog: "бэклог",
+ proposing: "proposal",
+ awaiting_approval: "ждёт одобрения",
+ in_progress: "в работе",
+ review: "ревью",
+ done: "готово",
+ blocked: "заблокирована",
+};
+export const statusRu = (s: string) => STATUS_RU[s] ?? s;
+
+type P = Record;
+const s = (v: unknown) => (v == null ? "" : String(v));
+const cut = (t: string, n = 600) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);
+
+/** Event types that become chat messages: text, and whether the master chat shows it. */
+const EVENT_TEXT: Record { text: string; important?: boolean; author?: "agent" } | null> = {
+ task_updated: (p) => {
+ const from = (p.from as P | undefined)?.status;
+ const to = (p.to as P | undefined)?.status;
+ if (!to || from === to) return null;
+ const icon = to === "review" ? "👀" : to === "done" ? "✅" : to === "in_progress" ? "▶️" : to === "blocked" ? "⛔" : "•";
+ const tail = to === "review" ? " — готово к ревью" : "";
+ return { text: `${icon} Статус: ${from ? `${statusRu(String(from))} → ` : ""}${statusRu(String(to))}${tail}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
+ },
+ progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
+ pm_comment: () => null, // handled separately: a person's message
+ pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
+ started: () => ({ text: "▶️ Агент запущен" }),
+ resumed: () => ({ text: "🔁 Агент продолжает работу" }),
+ stopped: () => ({ text: "⏹ Агент остановлен" }),
+ stalled: (p) => ({ text: `⚠️ Агент молчит${p.idleMinutes ? ` ${s(p.idleMinutes)} мин` : ""}`, important: true }),
+ stop_failure: (p) => ({ text: `❌ Ход агента прерван: ${s(p.error) || "ошибка"}`, important: true }),
+ exited: (p) => ({ text: `💀 Процесс агента завершился${p.exitStatus != null ? ` (код ${s(p.exitStatus)})` : ""}`, important: true }),
+ usage_limit: (p) => ({ text: `⏳ Лимит подписки${p.line ? `: ${cut(s(p.line), 200)}` : ""}`, important: true }),
+ auto_restarted: (p) => ({ text: `🔁 Перезапуск после сбоя${p.attempt ? ` (${s(p.attempt)} из ${s(p.of)})` : ""}`, important: true }),
+ restart_failed: (p) => ({ text: `❌ Перезапуск не удался${p.error ? `: ${cut(s(p.error), 200)}` : ""}`, important: true }),
+ budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе", important: true }),
+ subscription_switched: (p) => ({ text: `🔀 Подписка переключена${p.to ? ` на ${s(p.to)}` : ""}`, important: true }),
+ model_escalated: (p) => ({ text: `⬆️ Модель усилена${p.model ? `: ${s(p.model)}` : ""}` }),
+};
+
+const RELEASE_ICON: Record = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
+const RELEASE_RU: Record = { deploying: "выкатывается", healthy: "здоров", rolled_back: "откатан", failed: "не выкатился", removed: "убран" };
+const INCIDENT_RU: Record = { new: "новая", open: "открыта", pending: "ждёт решения", task: "заведена стори", ignored: "игнорируем", resolved: "исправлена", regressed: "вернулась" };
+
+/** First id of rows newer than a day (a fresh install doesn't import the whole history). */
+async function initialCursor(db: Db, table: typeof events | typeof questions, now: Date): Promise {
+ const since = new Date(now.getTime() - DAY);
+ const [r] = await db.select({ min: sql`min(${table.id})`, max: sql`max(${table.id})` }).from(table).where(gt(table.createdAt, since));
+ if (r?.min != null) return Number(r.min) - 1;
+ const [all] = await db.select({ max: sql`max(${table.id})` }).from(table);
+ return Number(all?.max ?? 0);
+}
+
+/**
+ * Moves new events, questions, releases and incidents into the project chats. Idempotent
+ * (every message has a dedupe key), so the bot, the watchdog and the web may all call it.
+ * Returns the number of new messages.
+ */
+export async function syncChats(db: Db, o: { now?: Date } = {}): Promise {
+ const now = o.now ?? new Date();
+ const chatOf = new Map();
+ const chatId = async (projectId: number) => {
+ if (!chatOf.has(projectId)) chatOf.set(projectId, (await ensureProjectChat(db, projectId)).id);
+ return chatOf.get(projectId)!;
+ };
+ const titles = new Map();
+ const titleOf = async (key: string) => {
+ if (!titles.has(key)) titles.set(key, await threadTitle(db, key));
+ return titles.get(key) ?? null;
+ };
+ let added = 0;
+ const add = async (m: NewChatMessage) => {
+ if (m.threadKey) m.threadTitle = await titleOf(m.threadKey);
+ if (await addChatMessage(db, m)) added++;
+ };
+
+ // events
+ let cursor = (await getSetting(db, CURSOR_EVENTS)) ?? (await initialCursor(db, events, now));
+ for (;;) {
+ // Read the newest id first: a row committed after it is picked up by the next call.
+ const [top] = await db.select({ max: sql`max(${events.id})` }).from(events);
+ const upTo = Number(top?.max ?? cursor);
+ const rows = await db
+ .select({ e: events, login: users.login })
+ .from(events)
+ .leftJoin(users, eq(events.actorUserId, users.id))
+ .where(and(gt(events.id, cursor), lte(events.id, upTo), inArray(events.type, Object.keys(EVENT_TEXT))))
+ .orderBy(asc(events.id))
+ .limit(BATCH);
+ for (const { e, login } of rows) {
+ const p = (e.payload ?? {}) as P;
+ const base = { chatId: await chatId(e.projectId), threadKey: e.taskId ? `task:${e.taskId}` : null, taskId: e.taskId, dedupeKey: `event:${e.id}`, createdAt: e.createdAt };
+ if (e.type === "pm_comment") {
+ if (p.chatMessageId) continue; // written in a chat: already there
+ await add({ ...base, kind: "user", authorKind: "user", authorUserId: (p.userId as number) ?? e.actorUserId, authorLogin: s(p.login) || login, via: e.actorChannel === "telegram" ? "telegram" : "web", text: s(p.text) });
+ continue;
+ }
+ const t = EVENT_TEXT[e.type]?.(p);
+ if (!t) continue;
+ const authorKind = t.author ?? (e.actorKind === "user" ? "user" : e.actorKind === "agent" ? "agent" : "system");
+ await add({ ...base, kind: "event", important: !!t.important, authorKind, authorUserId: e.actorUserId, authorLogin: authorKind === "user" ? login : null, text: t.text });
+ }
+ // The cursor moves past filtered-out events too.
+ cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo);
+ if (rows.length < BATCH) break;
+ }
+ await setSetting(db, CURSOR_EVENTS, cursor);
+
+ // questions
+ let qCursor = (await getSetting(db, CURSOR_QUESTIONS)) ?? (await initialCursor(db, questions, now));
+ for (;;) {
+ const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH);
+ for (const q of rows) {
+ const head = q.kind === "approval" ? "🟡 Нужно одобрение" : q.kind === "permission" ? "🔐 Нужно разрешение" : q.kind === "question" ? "❓ Вопрос агента" : "🔔";
+ await add({
+ chatId: await chatId(q.projectId),
+ threadKey: q.taskId ? `task:${q.taskId}` : null,
+ taskId: q.taskId,
+ kind: "question",
+ important: true,
+ authorKind: q.sessionId ? "agent" : "system",
+ text: `${head}\n${cut(q.text, 3000)}`,
+ questionId: q.id,
+ dedupeKey: `question:${q.id}`,
+ createdAt: q.createdAt,
+ });
+ qCursor = q.id;
+ }
+ if (rows.length < BATCH) break;
+ }
+ await setSetting(db, CURSOR_QUESTIONS, qCursor);
+
+ // releases and incidents: one message per (id, status); the window overlaps a little.
+ const since = new Date(((await getSetting(db, CURSOR_OBJECTS)) ?? now.getTime() - DAY) - 60_000);
+ for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
+ const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
+ await add({
+ chatId: await chatId(r.projectId),
+ threadKey: `release:${r.id}`,
+ kind: "event",
+ important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back",
+ text: `${RELEASE_ICON[r.status] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
+ url: r.host ? `https://${r.host}` : r.runUrl,
+ dedupeKey: `release:${r.id}:${r.status}`,
+ });
+ }
+ for (const i of await db.select().from(incidents).where(gt(incidents.updatedAt, since)).orderBy(asc(incidents.id))) {
+ await add({
+ chatId: await chatId(i.projectId),
+ threadKey: `incident:${i.id}`,
+ taskId: i.taskId,
+ kind: "event",
+ important: i.status === "new" || i.status === "regressed" || i.status === "pending",
+ text: `🐞 ${INCIDENT_RU[i.status] ?? i.status}: ${cut(i.title, 300)}${i.culprit ? `\n${cut(i.culprit, 200)}` : ""}${i.environment ? ` · ${i.environment}` : ""}${i.events > 1 ? ` · ${i.events} раз` : ""}`,
+ url: i.url,
+ dedupeKey: `incident:${i.id}:${i.status}`,
+ });
+ }
+ await setSetting(db, CURSOR_OBJECTS, now.getTime());
+ if (added) await notify(db, { type: "chat_message", messageId: 0 });
+ return added;
+}
+
+/** Deletes chat messages older than the TTL (the stories, questions and events stay). */
+export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise {
+ const before = new Date((o.now ?? new Date()).getTime() - chatTtlMs());
+ const old = db.select({ id: chatMessages.id }).from(chatMessages).where(lt(chatMessages.createdAt, before));
+ await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old));
+ const rows = await db.delete(chatMessages).where(lt(chatMessages.createdAt, before)).returning({ id: chatMessages.id });
+ return rows.length;
+}
+
+// ── Telegram groups ────────────────────────────────────────────────────────────────
+
+const LINK_TTL_MS = 10 * 60_000;
+const linkKey = (code: string, secret: string) => `chat.link:${createHmac("sha256", secret).update(`chat:${code}`).digest("hex")}`;
+
+/** One-time code (10 minutes) that links a Telegram group to this chat. */
+export async function createChatLinkCode(db: Db, secret: string, user: Pick, chatId: number): Promise {
+ await chatForUser(db, user, chatId);
+ const code = `c${randomBytes(12).toString("base64url")}`;
+ await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, expiresAt: Date.now() + LINK_TTL_MS });
+ return code;
+}
+
+/** Codes of chat links start with "c"; the personal pairing codes of PEP-2 never collide with them. */
+export const isChatLinkCode = (code: string) => /^c[\w-]{16}$/.test(code);
+
+/** Links the group the code was sent from. A group linked to another chat moves to this one. */
+export async function acceptChatLink(db: Db, secret: string, code: string, group: { tgChatId: number; title: string | null }, now = Date.now()): Promise {
+ const key = linkKey(code, secret);
+ const saved = await getSetting<{ chatId: number; userId: number; expiresAt: number }>(db, key);
+ if (!saved) return null;
+ await deleteSetting(db, key);
+ if (now >= saved.expiresAt) return null;
+ return db.transaction((tx) => {
+ tx.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null }).where(eq(chats.tgChatId, group.tgChatId)).run();
+ return tx.update(chats).set({ tgChatId: group.tgChatId, tgTitle: group.title, tgLinkedAt: new Date(now), tgLinkedBy: saved.userId }).where(eq(chats.id, saved.chatId)).returning().get() ?? null;
+ });
+}
+
+export async function unlinkChat(db: Db, user: Pick, chatId: number): Promise {
+ await chatForUser(db, user, chatId);
+ await db.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null }).where(eq(chats.id, chatId));
+}
+
+/** A group became a supergroup: Telegram gives it a new id. */
+export async function migrateChatGroup(db: Db, from: number, to: number): Promise {
+ await db.update(chats).set({ tgChatId: to }).where(eq(chats.tgChatId, from));
+}
+
+/** The person writing in a linked group: a Peppa user with this personal Telegram account (PEP-2). */
+export async function telegramAccountUser(db: Db, fromId: number): Promise {
+ const rows = await db.select().from(users).where(eq(users.telegramUserId, fromId));
+ return rows.find((u) => !u.disabledAt) ?? null;
+}
+
+/** May this user write into the chat from Telegram (project access / the master chat's owner)? */
+export async function mayWriteChat(db: Db, user: Pick, chat: Chat): Promise {
+ return chatForUser(db, user, chat.id).then(
+ () => true,
+ () => false,
+ );
+}
+
+export interface MirrorTarget {
+ tgChatId: number;
+ /** The group of a master chat (a project's message reached it as an important one). */
+ master: boolean;
+}
+
+/** Messages after `afterId` with the chat they belong to (the bot mirrors them). */
+export async function chatMessagesAfter(db: Db, afterId: number, limit = 100) {
+ return db.select({ m: chatMessages, chat: chats }).from(chatMessages).innerJoin(chats, eq(chatMessages.chatId, chats.id)).where(gt(chatMessages.id, afterId)).orderBy(asc(chatMessages.id)).limit(limit);
+}
+
+export async function lastChatMessageId(db: Db): Promise {
+ const [r] = await db.select({ max: sql`max(${chatMessages.id})` }).from(chatMessages);
+ return Number(r?.max ?? 0);
+}
+
+/** Linked groups a message goes to: its chat's group, and for an important project message the master groups of the project's people. */
+export async function mirrorTargets(db: Db, m: ChatMessage, chat: Chat): Promise {
+ const out: MirrorTarget[] = [];
+ if (chat.tgChatId && chat.tgChatId !== m.tgChatId) out.push({ tgChatId: chat.tgChatId, master: chat.kind === "master" });
+ if (chat.kind === "project" && m.important) {
+ for (const u of await projectAudience(db, chat.projectId!)) {
+ const [mc] = await db.select().from(chats).where(and(eq(chats.userId, u.id), isNotNull(chats.tgChatId)));
+ if (!mc?.tgChatId || mc.tgChatId === m.tgChatId || out.some((t) => t.tgChatId === mc.tgChatId)) continue;
+ if ((await getNotifyPrefs(db, u.id)).mutedProjects.includes(chat.projectId!)) continue;
+ out.push({ tgChatId: mc.tgChatId, master: true });
+ }
+ }
+ return out;
+}
+
+/** The chat message a Telegram message in this group stands for (sent by the bot, or written there). */
+export async function chatMessageByTelegram(db: Db, tgChatId: number, tgMessageId: number): Promise {
+ const [sent] = await db
+ .select({ m: chatMessages })
+ .from(telegramOutbox)
+ .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id))
+ .where(and(eq(telegramOutbox.telegramMessageId, tgMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(tgChatId)}`));
+ if (sent) return sent.m;
+ const [own] = await db.select().from(chatMessages).where(and(eq(chatMessages.tgChatId, tgChatId), eq(chatMessages.tgMessageId, tgMessageId)));
+ return own ?? null;
+}
+
+/**
+ * The Telegram message a thread hangs on in this group: the first message of the thread
+ * that reached the group (sent by the bot or written there). Null — this is the thread's first.
+ */
+export async function threadAnchor(db: Db, row: Pick): Promise {
+ if (!row.chatMessageId) return null;
+ const [m] = await db.select({ threadKey: chatMessages.threadKey }).from(chatMessages).where(eq(chatMessages.id, row.chatMessageId));
+ if (!m?.threadKey) return null;
+ const group = String(row.params.chat_id);
+ const [sent] = await db
+ .select({ id: telegramOutbox.telegramMessageId })
+ .from(telegramOutbox)
+ .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id))
+ .where(and(eq(chatMessages.threadKey, m.threadKey), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${group}`))
+ .orderBy(asc(telegramOutbox.id))
+ .limit(1);
+ if (sent?.id) return sent.id;
+ const [own] = await db
+ .select({ id: chatMessages.tgMessageId })
+ .from(chatMessages)
+ .where(and(eq(chatMessages.threadKey, m.threadKey), eq(chatMessages.tgChatId, Number(group)), isNotNull(chatMessages.tgMessageId)))
+ .orderBy(asc(chatMessages.id))
+ .limit(1);
+ return own?.id ?? null;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f06b1ada..a7e18ba0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -44,3 +44,4 @@ export * from "./secrets-audit.ts";
export * from "./memory.ts";
export * from "./agent-model.ts";
export * from "./onboarding.ts";
+export * from "./chats.ts";
diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts
index 9774da6a..3c3540b3 100644
--- a/packages/core/src/notifications.ts
+++ b/packages/core/src/notifications.ts
@@ -7,6 +7,20 @@ import { enqueueTelegram, type OutboxRow } from "./telegram.ts";
import type { Question } from "./tasks.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
+import { addMasterMessage } from "./chats.ts";
+
+/** Telegram HTML → plain text for the web chat. */
+export function htmlToText(html: string): string {
+ return html
+ .replace(/ /gi, "\n")
+ .replace(/]*>([^<]*)<\/a>/gi, (_m, href: string, t: string) => (t && t !== href ? `${t} (${href})` : href))
+ .replace(/<[^>]+>/g, "")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/&/g, "&");
+}
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
@@ -154,6 +168,11 @@ export interface Delivered {
/** Routes one notification to one user by their preferences. */
export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: NotifyPrefs): Promise {
+ // PEP-62: monitoring and the digest also land in the user's master chat (a feed, not a channel).
+ if (d.projectId == null && (d.event === "monitoring" || d.event === "digest") && typeof d.telegram?.params.text === "string") {
+ const text = htmlToText(d.telegram.params.text);
+ await addMasterMessage(db, user.id, { kind: "event", important: true, text, dedupeKey: `master:u${user.id}:${d.dedupeKey}`, url: d.push?.url ?? null }).catch(() => null);
+ }
const p = prefs ?? (await getNotifyPrefs(db, user.id));
const out: Delivered = { telegram: false, push: 0, muted: false };
if (d.projectId != null && p.mutedProjects.includes(d.projectId)) return { ...out, muted: true };
diff --git a/packages/core/src/notify.ts b/packages/core/src/notify.ts
index 9b9d91c8..ca816d39 100644
--- a/packages/core/src/notify.ts
+++ b/packages/core/src/notify.ts
@@ -10,7 +10,8 @@ export type PeppaNotification =
| { type: "task_updated"; taskId: number }
| { type: "progress"; eventId: number }
| { type: "session_updated"; sessionId: number }
- | { type: "incident"; incidentId: number };
+ | { type: "incident"; incidentId: number }
+ | { type: "chat_message"; messageId: number };
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME (web: PEP-37). */
export const SUBSCRIBERS = ["bot", "web"] as const;
diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts
index eeb4918a..8bd03813 100644
--- a/packages/core/src/projects.ts
+++ b/packages/core/src/projects.ts
@@ -1,4 +1,4 @@
-import { goals, projects, type Db } from "@peppa/db";
+import { chats, goals, projects, type Db } from "@peppa/db";
import { and, asc, eq, or } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
@@ -24,6 +24,8 @@ export async function createProject(db: Db, p: NewProject): Promise {
.insert(projects)
.values({ ...p, key, giteaRepo: p.giteaRepo ?? p.slug })
.returning();
+ // PEP-62: every project gets its chat (a channel with threads) right away.
+ await db.insert(chats).values({ kind: "project", projectId: row!.id }).onConflictDoNothing();
return row!;
}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 8e048805..1958bb6d 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -256,13 +256,13 @@ export interface StoryComment {
}
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
-export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string): Promise {
+export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string, extra: { chatMessageId?: number } = {}): Promise {
const body = text.trim();
if (!body) throw new PeppaError("Пустой комментарий");
if (body.length > 8000) throw new PeppaError("Комментарий длиннее 8000 символов");
const [row] = await db
.insert(events)
- .values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body }, ...actorColumns() })
+ .values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body, ...extra }, ...actorColumns() })
.returning();
await notify(db, { type: "task_updated", taskId: ref.task.id });
return { id: row!.id, login: author.login, text: body, createdAt: row!.createdAt };
diff --git a/packages/db/migrations/0015_chats.sql b/packages/db/migrations/0015_chats.sql
new file mode 100644
index 00000000..c57421c4
--- /dev/null
+++ b/packages/db/migrations/0015_chats.sql
@@ -0,0 +1,48 @@
+CREATE TABLE `chat_messages` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `chat_id` integer NOT NULL,
+ `thread_key` text,
+ `thread_title` text,
+ `kind` text NOT NULL,
+ `important` integer DEFAULT false NOT NULL,
+ `author_kind` text DEFAULT 'system' NOT NULL,
+ `author_user_id` integer,
+ `author_login` text,
+ `via` text,
+ `text` text NOT NULL,
+ `question_id` integer,
+ `task_id` integer,
+ `url` text,
+ `dedupe_key` text,
+ `tg_chat_id` integer,
+ `tg_message_id` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`author_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `chat_messages_dedupe_key_unique` ON `chat_messages` (`dedupe_key`);--> statement-breakpoint
+CREATE INDEX `chat_messages_chat` ON `chat_messages` (`chat_id`,`id`);--> statement-breakpoint
+CREATE INDEX `chat_messages_created_at` ON `chat_messages` (`created_at`);--> statement-breakpoint
+CREATE INDEX `chat_messages_tg` ON `chat_messages` (`tg_chat_id`,`tg_message_id`);--> statement-breakpoint
+CREATE TABLE `chats` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `kind` text NOT NULL,
+ `user_id` integer,
+ `project_id` integer,
+ `tg_chat_id` integer,
+ `tg_title` text,
+ `tg_linked_at` integer,
+ `tg_linked_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`tg_linked_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_user_id_unique` ON `chats` (`user_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_project_id_unique` ON `chats` (`project_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_tg_chat_id_unique` ON `chats` (`tg_chat_id`);--> statement-breakpoint
+ALTER TABLE `telegram_outbox` ADD `chat_message_id` integer REFERENCES chat_messages(id) ON DELETE set null;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0015_snapshot.json b/packages/db/migrations/meta/0015_snapshot.json
new file mode 100644
index 00000000..0b659949
--- /dev/null
+++ b/packages/db/migrations/meta/0015_snapshot.json
@@ -0,0 +1,4106 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "a95c0441-3ac0-47f1-a36d-b0caea076cbd",
+ "prevId": "c884cc4d-c58b-4874-ab39-9a1b9ce9718e",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "character": {
+ "name": "character",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "agents_name_unique": {
+ "name": "agents_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chat_messages": {
+ "name": "chat_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_key": {
+ "name": "thread_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thread_title": {
+ "name": "thread_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "important": {
+ "name": "important",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "author_kind": {
+ "name": "author_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_login": {
+ "name": "author_login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "via": {
+ "name": "via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_message_id": {
+ "name": "tg_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "chat_messages_dedupe_key_unique": {
+ "name": "chat_messages_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ },
+ "chat_messages_chat": {
+ "name": "chat_messages_chat",
+ "columns": [
+ "chat_id",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_created_at": {
+ "name": "chat_messages_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_tg": {
+ "name": "chat_messages_tg",
+ "columns": [
+ "tg_chat_id",
+ "tg_message_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "chat_messages_chat_id_chats_id_fk": {
+ "name": "chat_messages_chat_id_chats_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_messages_author_user_id_users_id_fk": {
+ "name": "chat_messages_author_user_id_users_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "author_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_question_id_questions_id_fk": {
+ "name": "chat_messages_question_id_questions_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_task_id_tasks_id_fk": {
+ "name": "chat_messages_task_id_tasks_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chats": {
+ "name": "chats",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_title": {
+ "name": "tg_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_at": {
+ "name": "tg_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_by": {
+ "name": "tg_linked_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "chats_user_id_unique": {
+ "name": "chats_user_id_unique",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": true
+ },
+ "chats_project_id_unique": {
+ "name": "chats_project_id_unique",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": true
+ },
+ "chats_tg_chat_id_unique": {
+ "name": "chats_tg_chat_id_unique",
+ "columns": [
+ "tg_chat_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_users_id_fk": {
+ "name": "chats_user_id_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_project_id_projects_id_fk": {
+ "name": "chats_project_id_projects_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_tg_linked_by_users_id_fk": {
+ "name": "chats_tg_linked_by_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "tg_linked_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "check_runs": {
+ "name": "check_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check": {
+ "name": "check",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_sec": {
+ "name": "duration_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'report'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "check_runs_project_sha_check": {
+ "name": "check_runs_project_sha_check",
+ "columns": [
+ "project_id",
+ "sha",
+ "check"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "check_runs_project_id_projects_id_fk": {
+ "name": "check_runs_project_id_projects_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "check_runs_task_id_tasks_id_fk": {
+ "name": "check_runs_task_id_tasks_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "code_reviews": {
+ "name": "code_reviews",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "findings": {
+ "name": "findings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "code_reviews_project_id_projects_id_fk": {
+ "name": "code_reviews_project_id_projects_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "code_reviews_task_id_tasks_id_fk": {
+ "name": "code_reviews_task_id_tasks_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "error_sources": {
+ "name": "error_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "columns": [
+ "bugsink_project_id"
+ ],
+ "isUnique": true
+ },
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ "project_id",
+ "kind"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "error_sources_project_id_projects_id_fk": {
+ "name": "error_sources_project_id_projects_id_fk",
+ "tableFrom": "error_sources",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "events": {
+ "name": "events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_kind": {
+ "name": "actor_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_channel": {
+ "name": "actor_channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_client_id": {
+ "name": "actor_client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "events_created_at": {
+ "name": "events_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "events_actor_user_id_users_id_fk": {
+ "name": "events_actor_user_id_users_id_fk",
+ "tableFrom": "events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "goals": {
+ "name": "goals",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incident_settings": {
+ "name": "incident_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[\"prod\",\"production\"]'"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "columns": [
+ "hook_secret"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_settings_project_id_projects_id_fk": {
+ "name": "incident_settings_project_id_projects_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incident_settings_goal_id_goals_id_fk": {
+ "name": "incident_settings_goal_id_goals_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incidents": {
+ "name": "incidents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "columns": [
+ "bugsink_issue_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incidents_project_id_projects_id_fk": {
+ "name": "incidents_project_id_projects_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_task_id_tasks_id_fk": {
+ "name": "incidents_task_id_tasks_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_clients": {
+ "name": "oauth_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_codes": {
+ "name": "oauth_codes",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_tokens": {
+ "name": "oauth_tokens",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_invites": {
+ "name": "project_invites",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "columns": [
+ "project_id",
+ "login"
+ ],
+ "name": "project_invites_project_id_login_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_members": {
+ "name": "project_members",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "columns": [
+ "project_id",
+ "user_id"
+ ],
+ "name": "project_members_project_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_secrets": {
+ "name": "project_secrets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value_enc": {
+ "name": "value_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "project_secrets_project_name": {
+ "name": "project_secrets_project_name",
+ "columns": [
+ "project_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "project_secrets_project_id_projects_id_fk": {
+ "name": "project_secrets_project_id_projects_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_secrets_created_by_users_id_fk": {
+ "name": "project_secrets_created_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_secrets_updated_by_users_id_fk": {
+ "name": "project_secrets_updated_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "updated_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "subscription_pool_id": {
+ "name": "subscription_pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "projects_subscription_pool_id_subscription_pools_id_fk": {
+ "name": "projects_subscription_pool_id_subscription_pools_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "subscription_pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_outbox": {
+ "name": "push_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "urgency": {
+ "name": "urgency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_outbox_dedupe_key_unique": {
+ "name": "push_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_outbox_subscription_id_push_subscriptions_id_fk": {
+ "name": "push_outbox_subscription_id_push_subscriptions_id_fk",
+ "tableFrom": "push_outbox",
+ "tableTo": "push_subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_subscriptions": {
+ "name": "push_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "p256dh": {
+ "name": "p256dh",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_ok_at": {
+ "name": "last_ok_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_subscriptions_endpoint_unique": {
+ "name": "push_subscriptions_endpoint_unique",
+ "columns": [
+ "endpoint"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_subscriptions_user_id_users_id_fk": {
+ "name": "push_subscriptions_user_id_users_id_fk",
+ "tableFrom": "push_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "questions": {
+ "name": "questions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "reminders": {
+ "name": "reminders",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "releases": {
+ "name": "releases",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "previous_sha": {
+ "name": "previous_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tasks": {
+ "name": "tasks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'deploying'"
+ },
+ "deployed_by": {
+ "name": "deployed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ci'"
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "releases_project_id_projects_id_fk": {
+ "name": "releases_project_id_projects_id_fk",
+ "tableFrom": "releases",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "review_settings": {
+ "name": "review_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "max_iterations": {
+ "name": "max_iterations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 2
+ },
+ "rules": {
+ "name": "rules",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "review_settings_project_id_projects_id_fk": {
+ "name": "review_settings_project_id_projects_id_fk",
+ "tableFrom": "review_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_commands": {
+ "name": "runner_commands",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_kind": {
+ "name": "error_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor": {
+ "name": "actor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_commands_status_idx": {
+ "name": "runner_commands_status_idx",
+ "columns": [
+ "status",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_hosts": {
+ "name": "runner_hosts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_target": {
+ "name": "ssh_target",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_port": {
+ "name": "ssh_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 22
+ },
+ "workdir": {
+ "name": "workdir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'peppa'"
+ },
+ "peppa_url": {
+ "name": "peppa_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "info": {
+ "name": "info",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "runner_hosts_name_unique": {
+ "name": "runner_hosts_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_tasks": {
+ "name": "runner_tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "front": {
+ "name": "front",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_tasks_session_idx": {
+ "name": "runner_tasks_session_idx",
+ "columns": [
+ "session_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "runner_tasks_session_id_sessions_id_fk": {
+ "name": "runner_tasks_session_id_sessions_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runner_tasks_task_id_tasks_id_fk": {
+ "name": "runner_tasks_task_id_tasks_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude'"
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rotate_reason": {
+ "name": "rotate_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_id": {
+ "name": "host_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container": {
+ "name": "container",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "watch_state": {
+ "name": "watch_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "columns": [
+ "tmux_name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_subscription_id_subscriptions_id_fk": {
+ "name": "sessions_subscription_id_subscriptions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_host_id_runner_hosts_id_fk": {
+ "name": "sessions_host_id_runner_hosts_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "runner_hosts",
+ "columnsFrom": [
+ "host_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pool_members": {
+ "name": "subscription_pool_members",
+ "columns": {
+ "pool_id": {
+ "name": "pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscription_pool_members_pool_id_subscription_pools_id_fk": {
+ "name": "subscription_pool_members_pool_id_subscription_pools_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subscription_pool_members_subscription_id_subscriptions_id_fk": {
+ "name": "subscription_pool_members_subscription_id_subscriptions_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subscription_pool_members_pool_id_subscription_id_pk": {
+ "columns": [
+ "pool_id",
+ "subscription_id"
+ ],
+ "name": "subscription_pool_members_pool_id_subscription_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pools": {
+ "name": "subscription_pools",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "subscription_pools_name_unique": {
+ "name": "subscription_pools_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "subscription_pools_created_by_users_id_fk": {
+ "name": "subscription_pools_created_by_users_id_fk",
+ "tableFrom": "subscription_pools",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth_kind": {
+ "name": "auth_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret_enc": {
+ "name": "secret_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "key_provider": {
+ "name": "key_provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "limited_until": {
+ "name": "limited_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "activated_at": {
+ "name": "activated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscriptions_created_by_users_id_fk": {
+ "name": "subscriptions_created_by_users_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_deps": {
+ "name": "task_deps",
+ "columns": {
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_by_id": {
+ "name": "blocked_by_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "task_deps_blocked_by": {
+ "name": "task_deps_blocked_by",
+ "columns": [
+ "blocked_by_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "task_deps_task_id_tasks_id_fk": {
+ "name": "task_deps_task_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_deps_blocked_by_id_tasks_id_fk": {
+ "name": "task_deps_blocked_by_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "blocked_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "task_deps_task_id_blocked_by_id_pk": {
+ "columns": [
+ "task_id",
+ "blocked_by_id"
+ ],
+ "name": "task_deps_task_id_blocked_by_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tasks": {
+ "name": "tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ci_attempts": {
+ "name": "ci_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "ci_failed_sha": {
+ "name": "ci_failed_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_issue": {
+ "name": "gitea_issue",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ "project_id",
+ "number"
+ ],
+ "isUnique": true
+ },
+ "tasks_project_issue": {
+ "name": "tasks_project_issue",
+ "columns": [
+ "project_id",
+ "gitea_issue"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_outbox": {
+ "name": "telegram_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "params": {
+ "name": "params",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "chat_message_id": {
+ "name": "chat_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "telegram_outbox_chat_message_id_chat_messages_id_fk": {
+ "name": "telegram_outbox_chat_message_id_chat_messages_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "chat_messages",
+ "columnsFrom": [
+ "chat_message_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_updates": {
+ "name": "telegram_updates",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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 09e80588..cc8db5f4 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -106,6 +106,13 @@
"when": 1794663938633,
"tag": "0014_agent_team",
"breakpoints": true
+ },
+ {
+ "idx": 15,
+ "version": "6",
+ "when": 1794665444878,
+ "tag": "0015_chats",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index bad12eee..cdbc71d2 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -481,6 +481,8 @@ export const telegramOutbox = sqliteTable("telegram_outbox", {
method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(),
params: text("params", { mode: "json" }).$type>().notNull(),
questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
+ // PEP-62: the chat message mirrored into a linked Telegram group (finds the thread of a reply).
+ chatMessageId: integer("chat_message_id").references((): AnySQLiteColumn => chatMessages.id, { onDelete: "set null" }),
status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"),
attempts: integer("attempts").notNull().default(0),
nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs),
@@ -490,6 +492,52 @@ export const telegramOutbox = sqliteTable("telegram_outbox", {
sentAt: integer("sent_at", { mode: "timestamp_ms" }),
});
+/** PEP-62: a chat — one per project (a channel with threads) and one per user (the master chat). */
+export const chats = sqliteTable("chats", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ kind: text("kind", { enum: ["master", "project"] }).notNull(),
+ userId: integer("user_id").unique().references(() => users.id, { onDelete: "cascade" }),
+ projectId: integer("project_id").unique().references(() => projects.id, { onDelete: "cascade" }),
+ // Linked Telegram group: messages are mirrored there, replies come back (one group — one chat).
+ tgChatId: integer("tg_chat_id").unique(),
+ tgTitle: text("tg_title"),
+ tgLinkedAt: integer("tg_linked_at", { mode: "timestamp_ms" }),
+ tgLinkedBy: integer("tg_linked_by").references(() => users.id, { onDelete: "set null" }),
+ createdAt: createdAt(),
+});
+
+/**
+ * PEP-62: a chat message, kept for PEPPA_CHAT_TTL_DAYS only. A thread is `thread_key`
+ * (task: / incident: / release:; null = the channel); events, questions,
+ * releases and incidents are projected here and stay in their own tables.
+ */
+export const chatMessages = sqliteTable(
+ "chat_messages",
+ {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ chatId: integer("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }),
+ threadKey: text("thread_key"),
+ threadTitle: text("thread_title"),
+ kind: text("kind", { enum: ["event", "question", "user", "system"] }).notNull(),
+ // Shown in the master chats of the project's people.
+ important: integer("important", { mode: "boolean" }).notNull().default(false),
+ authorKind: text("author_kind", { enum: ["system", "agent", "user"] }).notNull().default("system"),
+ authorUserId: integer("author_user_id").references(() => users.id, { onDelete: "set null" }),
+ authorLogin: text("author_login"),
+ via: text("via", { enum: ["web", "telegram"] }),
+ text: text("text").notNull(),
+ questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
+ url: text("url"),
+ dedupeKey: text("dedupe_key").unique(),
+ // Came from a Telegram group: a reply to this message finds its thread.
+ tgChatId: integer("tg_chat_id"),
+ tgMessageId: integer("tg_message_id"),
+ createdAt: createdAt(),
+ },
+ (t) => [index("chat_messages_chat").on(t.chatId, t.id), index("chat_messages_created_at").on(t.createdAt), index("chat_messages_tg").on(t.tgChatId, t.tgMessageId)],
+);
+
/** Telegram updates already taken: recorded before acting, so a restart never replays one. */
export const telegramUpdates = sqliteTable("telegram_updates", {
updateId: integer("update_id").primaryKey(),
diff --git a/packages/runner/src/chats.ts b/packages/runner/src/chats.ts
new file mode 100644
index 00000000..5dde50e5
--- /dev/null
+++ b/packages/runner/src/chats.ts
@@ -0,0 +1,184 @@
+// PEP-62: a person's message in a chat (web or a linked Telegram group). In a story thread it
+// answers the story's open question or becomes a PM comment typed into the live runner; in
+// other threads and the channel it is a note; a text starting with "/" is a command.
+import {
+ addChatMessage,
+ addStoryComment,
+ chatForUser,
+ listSessions,
+ notify,
+ pendingQuestions,
+ projectForUser,
+ resolveTask,
+ statusRu,
+ THREAD_KEY,
+ userProjectIds,
+ type Chat,
+ type ChatMessage,
+ type User,
+ PeppaError,
+} from "@peppa/core";
+import { projects, questions, tasks, type Db } from "@peppa/db";
+import { and, desc, eq, isNull, ne } from "drizzle-orm";
+import { moveTask, type BoardColumn } from "./flow.ts";
+import { answerAndDeliver, sendToSession } from "./sessions.ts";
+
+export interface ChatPost {
+ chatId: number;
+ /** null = the channel. */
+ threadKey: string | null;
+ text: string;
+ via: "web" | "telegram";
+ /** A reply to this question's message (Telegram): answer exactly it. */
+ questionId?: number | null;
+ /** Where it was written in Telegram (a reply to it finds the thread). */
+ tg?: { chatId: number; messageId: number };
+}
+
+export interface ChatPostResult {
+ message: ChatMessage;
+ /** Peppa's reply in the same thread (what happened), if any. */
+ reply: ChatMessage | null;
+}
+
+const MAX_TEXT = 8000;
+
+export const CHAT_HELP = [
+ "Команды:",
+ "/status — активные агенты и открытые вопросы",
+ "/task KEY-N — где стори и что она ждёт",
+ "/move KEY-N — передвинуть стори (in_progress запускает агента)",
+ "/help — эта справка",
+ "",
+ "В треде стори обычный текст — ответ агенту: на открытый вопрос, иначе комментарий, который агент увидит сразу.",
+].join("\n");
+
+const COLUMNS: Record = {
+ backlog: "backlog",
+ бэклог: "backlog",
+ in_progress: "in_progress",
+ work: "in_progress",
+ работа: "in_progress",
+ "в работу": "in_progress",
+ review: "review",
+ ревью: "review",
+ done: "done",
+ готово: "done",
+};
+const COLUMN_RU: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
+
+/** Posts a person's message and does what it means. Access: chatForUser (project people / master owner). */
+export async function postToChat(db: Db, user: User, p: ChatPost): Promise {
+ const chat = await chatForUser(db, user, p.chatId);
+ const text = p.text.trim();
+ if (!text) throw new PeppaError("Пустое сообщение");
+ if (text.length > MAX_TEXT) throw new PeppaError(`Сообщение длиннее ${MAX_TEXT} символов`);
+ if (p.threadKey && !THREAD_KEY.test(p.threadKey)) throw new PeppaError("Неизвестный тред");
+ if (chat.kind === "master" && p.threadKey) throw new PeppaError("В мастер-чате нет своих тредов — ответь в чате проекта");
+ const taskId = p.threadKey?.startsWith("task:") ? Number(p.threadKey.slice(5)) : null;
+ if (taskId) await assertTaskInChat(db, chat, taskId);
+
+ const message = (await addChatMessage(db, {
+ chatId: chat.id,
+ threadKey: p.threadKey,
+ taskId,
+ kind: "user",
+ authorKind: "user",
+ authorUserId: user.id,
+ authorLogin: user.login,
+ via: p.via,
+ text,
+ tgChatId: p.tg?.chatId ?? null,
+ tgMessageId: p.tg?.messageId ?? null,
+ }))!;
+ const say = async (t: string) => {
+ const r = await addChatMessage(db, { chatId: chat.id, threadKey: p.threadKey, taskId, kind: "system", text: t });
+ return r;
+ };
+
+ let replyText: string | null;
+ try {
+ if (text.startsWith("/")) replyText = await runCommand(db, user, chat, text);
+ else if (taskId) replyText = await toAgent(db, user, message, taskId, text, p);
+ else replyText = chat.kind === "master" ? `Здесь работают команды.\n${CHAT_HELP}` : null;
+ } catch (e) {
+ replyText = `⚠️ ${(e as Error).message}`;
+ }
+ const reply = replyText ? await say(replyText) : null;
+ await notify(db, { type: "chat_message", messageId: message.id });
+ return { message, reply };
+}
+
+async function assertTaskInChat(db: Db, chat: Chat, taskId: number) {
+ const ref = await resolveTaskById(db, taskId);
+ if (chat.kind !== "project" || ref.project.id !== chat.projectId) throw new PeppaError("Тред не из этого чата");
+ return ref;
+}
+
+async function resolveTaskById(db: Db, taskId: number) {
+ const [row] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, taskId));
+ if (!row) throw new PeppaError("Стори не найдена");
+ return resolveTask(db, `${row.key}-${row.number}`);
+}
+
+/** Story thread: answer its open question, or comment and type into the live runner. */
+async function toAgent(db: Db, user: User, message: ChatMessage, taskId: number, text: string, p: ChatPost): Promise {
+ let q = p.questionId ? (await db.select().from(questions).where(and(eq(questions.id, p.questionId), eq(questions.taskId, taskId))))[0] : undefined;
+ if (q?.answeredAt) return `Этот вопрос уже закрыт${q.answeredVia && q.answeredVia !== "system" ? ` (${q.answeredVia})` : ""}: ${q.answer ?? ""}`;
+ // The latest open real question first; «ждёт тебя» (attention) only when nothing else is open.
+ q ??=
+ (await db.select().from(questions).where(and(eq(questions.taskId, taskId), isNull(questions.answeredAt), ne(questions.kind, "attention"))).orderBy(desc(questions.id)).limit(1))[0] ??
+ (await db.select().from(questions).where(and(eq(questions.taskId, taskId), isNull(questions.answeredAt))).orderBy(desc(questions.id)).limit(1))[0];
+ if (q) {
+ const { delivered } = await answerAndDeliver(db, q.id, text, p.via);
+ return delivered ? "Ответ ушёл агенту ✅" : "Ответ сохранён; сессия не запущена — агент увидит его в истории стори.";
+ }
+ const ref = await resolveTaskById(db, taskId);
+ // The comment event carries this message's id: the projection doesn't repeat it in the thread.
+ const c = await addStoryComment(db, ref, user, text, { chatMessageId: message.id });
+ const [live] = await listSessions(db, { active: true, taskId });
+ if (!live) return "Комментарий сохранён — агент увидит его в get_task, когда возьмётся за стори.";
+ await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
+ return "Комментарий ушёл агенту ✅";
+}
+
+/** /status, /task, /move, /help — no LLM (PM's decision). */
+export async function runCommand(db: Db, user: User, chat: Chat, text: string): Promise {
+ const [cmd0, ...args] = text.trim().split(/\s+/);
+ const cmd = cmd0!.toLowerCase().replace(/@\w+$/, "");
+ if (cmd === "/help" || cmd === "/start") return CHAT_HELP;
+ if (cmd === "/status") return status(db, user, chat);
+ if (cmd === "/task" || cmd === "/move") {
+ if (!args[0]) throw new PeppaError(`Укажи стори: ${cmd} KEY-N${cmd === "/move" ? " in_progress" : ""}`);
+ const defaultKey = chat.kind === "project" ? await projectKey(db, chat.projectId!) : undefined;
+ const ref = await resolveTask(db, args[0], defaultKey);
+ await projectForUser(db, user.id, ref.project.id).catch(() => {
+ throw new PeppaError(`Стори ${args[0]} не найдена`);
+ });
+ if (cmd === "/task") {
+ const open = (await pendingQuestions(db)).filter((q) => q.taskId === ref.task.id);
+ const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
+ return [`${ref.key}: ${ref.task.title}`, `Статус: ${statusRu(ref.task.status)}`, live ? `Агент: ${live.status}` : "Агент не запущен", open.length ? `Ждёт ответа: ${open.length}` : "Открытых вопросов нет"].join("\n");
+ }
+ const col = COLUMNS[args.slice(1).join(" ").toLowerCase()];
+ if (!col) throw new PeppaError("Колонка: backlog, in_progress, review или done");
+ await moveTask(db, ref, col);
+ return `${ref.key} → ${COLUMN_RU[col]}${col === "in_progress" ? " (агент взялся)" : ""}`;
+ }
+ throw new PeppaError(`Не знаю такую команду: ${cmd}\n${CHAT_HELP}`);
+}
+
+async function projectKey(db: Db, projectId: number) {
+ const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
+ return p?.key;
+}
+
+async function status(db: Db, user: User, chat: Chat): Promise {
+ const ids = new Set(chat.kind === "project" ? [chat.projectId!] : await userProjectIds(db, user.id));
+ const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
+ const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
+ const lines = [`Активные агенты: ${sessions.length}`];
+ for (const s of sessions.slice(0, 20)) lines.push(`• ${s.taskKey ?? s.name ?? `#${s.id}`} — ${s.status}`);
+ lines.push(`Открытых вопросов: ${open.length}`);
+ return lines.join("\n");
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d8956b45..27da7158 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -39,3 +39,4 @@ export * from "./exec.ts";
export * from "./sandbox.ts";
export * from "./hosts.ts";
export * from "./agent-relay.ts";
+export * from "./chats.ts";
--
2.45.2
From 46840ffef57cdbda1f8520675360a17d8d3e242f 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 19:04:18 +0500
Subject: [PATCH 013/439] =?UTF-8?q?PEP-62:=20bot=20=E2=80=94=20link=20grou?=
=?UTF-8?q?ps=20by=20code,=20mirror=20chat=20messages=20with=20reply=20thr?=
=?UTF-8?q?eads,=20replies=20and=20buttons=20from=20groups?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/bot/src/bot.ts | 125 +++++++++++++++++++++++-
apps/bot/src/telegram.ts | 4 +-
openspec/changes/pep-62-chats/design.md | 5 +-
packages/core/src/telegram.ts | 2 +-
4 files changed, 129 insertions(+), 7 deletions(-)
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 435ab96a..50b3a401 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -47,10 +47,25 @@ import {
type OutboxRow,
type Question,
type SessionView,
+ acceptChatLink,
+ chatByTelegram,
+ chatMessageByTelegram,
+ chatMessagesAfter,
+ getSetting,
+ isChatLinkCode,
+ lastChatMessageId,
+ mayWriteChat,
+ migrateChatGroup,
+ mirrorTargets,
+ syncChats,
+ telegramAccountUser,
+ threadAnchor,
+ type Chat,
+ type ChatMessage,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
-import { acceptTask, answerAndDeliver, decideIncident, moveTask, resumeSession, stopSession } from "@peppa/runner";
+import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
@@ -161,6 +176,7 @@ export function createBot(o: BotOptions) {
});
}
}
+ await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`));
for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) {
await enqueueTelegram(db, {
dedupeKey: `qa:${q.id}:${sent.params.chat_id}`,
@@ -178,6 +194,52 @@ export function createBot(o: BotOptions) {
wakeOutbox?.();
}
+ // ── chats → linked Telegram groups (PEP-62) ────────────────────────────────────
+ const MIRROR_CURSOR = "chat.mirror.cursor";
+
+ /** Projects new events into chats and queues new chat messages for the linked groups. */
+ async function mirrorChats(): Promise {
+ await syncChats(db);
+ let cursor = await getSetting(db, MIRROR_CURSOR);
+ // First start: only what comes from now on (a newly linked group doesn't get the backlog).
+ if (cursor == null) return setSetting(db, MIRROR_CURSOR, await lastChatMessageId(db));
+ for (;;) {
+ const rows = await chatMessagesAfter(db, cursor);
+ for (const { m, chat } of rows) {
+ for (const t of await mirrorTargets(db, m, chat)) await mirrorOne(m, chat, t.tgChatId, t.master);
+ cursor = m.id;
+ }
+ await setSetting(db, MIRROR_CURSOR, cursor);
+ if (rows.length < 100) break;
+ }
+ }
+
+ async function mirrorOne(m: ChatMessage, chat: Chat, tgChatId: number, master: boolean): Promise {
+ const key = chat.projectId ? await projectKey(chat.projectId) : "";
+ const where = [master && key ? `[${esc(key)}]` : null, m.threadTitle ? `🧵 ${esc(m.threadTitle)} ` : null].filter(Boolean).join(" ");
+ let text: string;
+ let buttons: InlineButton[][] = [];
+ let questionId: number | undefined;
+ if (m.kind === "question" && m.questionId) {
+ const q = await getQuestion(db, m.questionId).catch(() => null);
+ if (!q || q.answeredAt) return;
+ const r = renderQuestion(q, await context(q));
+ text = r.text;
+ buttons = r.buttons;
+ questionId = q.id;
+ } else {
+ const who = m.kind === "user" ? `${esc(m.authorLogin ?? "?")} ${m.via === "telegram" ? "" : " (веб)"}: ` : m.authorKind === "agent" ? "🤖 " : "";
+ text = `${where ? `${where}\n` : ""}${who}${esc(m.text.slice(0, 3500))}${m.url ? `\n${esc(m.url)}` : ""}`;
+ }
+ await enqueueTelegram(db, {
+ dedupeKey: `cm:${m.id}:${tgChatId}`,
+ method: "sendMessage",
+ questionId,
+ chatMessageId: m.id,
+ params: { chat_id: tgChatId, text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(buttons.length ? { reply_markup: { inline_keyboard: buttons } } : {}) },
+ });
+ }
+
async function projectKey(projectId: number): Promise {
const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
return p?.key ?? "";
@@ -199,8 +261,14 @@ export function createBot(o: BotOptions) {
const q = await getQuestion(db, row.questionId).catch(() => null);
if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null);
}
+ let params = row.params;
+ if (row.method === "sendMessage" && row.chatMessageId && !params.reply_parameters) {
+ // PEP-62: a thread in a group = a chain of replies to its first message.
+ const anchor = await threadAnchor(db, row);
+ if (anchor) params = { ...params, reply_parameters: { message_id: anchor, allow_sending_without_reply: true } };
+ }
try {
- const res = await api.call(row.method, row.params);
+ const res = await api.call(row.method, params);
await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null);
} catch (e) {
if (!(e instanceof TelegramError)) throw e;
@@ -377,7 +445,52 @@ export function createBot(o: BotOptions) {
return "Неизвестная кнопка";
}
+ /** A message in a group (PEP-62): linking by code, then replies and commands of the linked chat. */
+ async function onGroupMessage(m: TgMessage): Promise<"done" | "ignored"> {
+ const text = m.text?.trim() ?? "";
+ const link = /^\/(?:start|link)(?:@\w+)?\s+(\S+)$/.exec(text);
+ if (link) {
+ if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done");
+ const chat = await acceptChatLink(db, o.secret, link[1]!, { tgChatId: m.chat.id, title: m.chat.title ?? null });
+ if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done");
+ const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом";
+ await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь реплаем — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды.`);
+ return "done";
+ }
+ const chat = await chatByTelegram(db, m.chat.id);
+ if (!chat || !m.from || !text) return "ignored";
+ // Group chatter stays in Telegram: only replies and commands reach the chat.
+ if (!m.reply_to_message && !text.startsWith("/")) return "ignored";
+ const user = await telegramAccountUser(db, m.from.id);
+ if (!user || !(await mayWriteChat(db, user, chat))) {
+ await reply(m.chat.id, user ? "У тебя нет доступа к этому чату." : `Не знаю тебя в Пеппе — привяжи Telegram: ${esc(o.webUrl)}/settings → Telegram.`, m.message_id);
+ return "done";
+ }
+ enterActor({ kind: "user", userId: user.id, channel: "telegram" });
+ // A reply finds its thread (and chat: the master group holds project threads too).
+ const target = m.reply_to_message ? await chatMessageByTelegram(db, m.chat.id, m.reply_to_message.message_id) : null;
+ try {
+ await postToChat(db, user, {
+ chatId: target?.chatId ?? chat.id,
+ threadKey: target?.threadKey ?? null,
+ text,
+ via: "telegram",
+ questionId: target?.kind === "question" ? target.questionId : null,
+ tg: { chatId: m.chat.id, messageId: m.message_id },
+ });
+ } catch (e) {
+ await reply(m.chat.id, esc((e as Error).message), m.message_id);
+ }
+ scheduleReconcile();
+ return "done";
+ }
+
async function onMessage(m: TgMessage): Promise<"done" | "ignored"> {
+ if (m.migrate_to_chat_id) {
+ await migrateChatGroup(db, m.chat.id, m.migrate_to_chat_id);
+ return "done";
+ }
+ if (m.chat.type !== "private") return onGroupMessage(m);
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
@@ -426,7 +539,13 @@ export function createBot(o: BotOptions) {
}
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
- const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
+ let user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
+ if (!user && c.message && c.message.chat.type !== "private") {
+ // PEP-62: buttons in a linked group — the presser's own account and access to the chat.
+ const chat = await chatByTelegram(db, c.message.chat.id);
+ const who = chat ? await telegramAccountUser(db, c.from.id) : null;
+ if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who;
+ }
if (!user) {
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
return "ignored";
diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts
index b8039146..2e734cff 100644
--- a/apps/bot/src/telegram.ts
+++ b/apps/bot/src/telegram.ts
@@ -8,9 +8,11 @@ export interface TgUser {
}
export interface TgMessage {
message_id: number;
- chat: { id: number; type: string };
+ chat: { id: number; type: string; title?: string };
from?: TgUser;
text?: string;
+ /** PEP-62: a group became a supergroup (new chat id). */
+ migrate_to_chat_id?: number;
reply_to_message?: TgMessage;
/** PEP-45: voice notes and audio files become stories after transcription. */
voice?: TgFileRef;
diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/pep-62-chats/design.md
index eb2c3412..c59eb13e 100644
--- a/openspec/changes/pep-62-chats/design.md
+++ b/openspec/changes/pep-62-chats/design.md
@@ -65,8 +65,9 @@ PEP-21 сами уходят в раннер-сервис.
что существующая правка «отвечено» и `questionByTelegramMessage` работают и в группе).
- **Приём**: сообщение в связанной группе → пользователь по `users.telegram_user_id`
(личная привязка PEP-2) и не отключён → доступ к проекту / владелец мастер-чата.
- Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); иначе — общий
- канал. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает
+ Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); команда без
+ реплая — общий канал. Обычная болтовня в группе (не реплай и не команда) остаётся в Telegram
+ и в чат не попадает — даже если privacy mode бота выключен. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает
привязать Telegram. Privacy mode бота оставляем: он видит команды и реплаи на свои
сообщения — этого достаточно для тредов.
- Личные уведомления в личку не меняются (их можно выключить по проекту в «Уведомлениях»).
diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts
index 72dbe607..f14ef30e 100644
--- a/packages/core/src/telegram.ts
+++ b/packages/core/src/telegram.ts
@@ -85,7 +85,7 @@ export async function finishUpdate(db: Db, updateId: number, status: "done" | "i
/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */
export async function enqueueTelegram(
db: Db,
- m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number },
+ m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number; chatMessageId?: number },
): Promise {
const rows = await db.insert(telegramOutbox).values(m).onConflictDoNothing().returning();
return rows.length > 0;
--
2.45.2
From a0d1097e376b4ace82221513f7186d8216834f25 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 19:09:32 +0500
Subject: [PATCH 014/439] =?UTF-8?q?PEP-62:=20web=20=C2=AB=D0=A7=D0=B0?=
=?UTF-8?q?=D1=82=D1=8B=C2=BB=20(master=20+=20project=20chats,=20threads,?=
=?UTF-8?q?=20composer,=20Telegram=20link),=20live=20scope,=20watchdog=20s?=
=?UTF-8?q?ync/TTL,=20e2e?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/web/app/(app)/chats/[chat]/page.tsx | 248 ++++++++++++++++++++++
apps/web/app/(app)/chats/actions.ts | 54 +++++
apps/web/app/(app)/chats/page.tsx | 5 +
apps/web/components/Sidebar.tsx | 11 +-
packages/runner/src/live.ts | 17 +-
packages/runner/src/watchdog.ts | 10 +
packages/testkit/src/mock-telegram.ts | 21 +-
packages/testkit/test/chats.test.ts | 253 +++++++++++++++++++++++
8 files changed, 611 insertions(+), 8 deletions(-)
create mode 100644 apps/web/app/(app)/chats/[chat]/page.tsx
create mode 100644 apps/web/app/(app)/chats/actions.ts
create mode 100644 apps/web/app/(app)/chats/page.tsx
create mode 100644 packages/testkit/test/chats.test.ts
diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx
new file mode 100644
index 00000000..8b915adf
--- /dev/null
+++ b/apps/web/app/(app)/chats/[chat]/page.tsx
@@ -0,0 +1,248 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
+import { chatMessagesView, chatThreads, chatTtlMs, getSetting, listChats, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
+import { projects, questions, tasks } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { eq, inArray } from "drizzle-orm";
+import { LiveRefresh } from "@/components/LiveRefresh";
+import { ago, Empty, Flash, PageHeader } from "@/components/common";
+import { Hidden, QuestionCard } from "@/components/cards";
+import { Workspace } from "@/components/Workspace";
+import { Button } from "@/components/ui/button";
+import { Textarea } from "@/components/ui/input";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { cn } from "@/lib/utils";
+import { linkChatAction, postChatAction, unlinkChatAction } from "../actions";
+
+type Params = { error?: string; thread?: string; link?: string };
+
+const CHANNEL = "channel";
+
+/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
+export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise }) {
+ const user = await requireUser();
+ const { chat: slug } = await params;
+ const { error, thread: rawThread, link } = await searchParams;
+ // Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too).
+ await syncChats(db).catch((e) => console.error("syncChats", e));
+ const list = await listChats(db, user);
+ const chat = list.find((c) => c.slug.toLowerCase() === slug.toLowerCase());
+ if (!chat) notFound();
+ const master = chat.kind === "master";
+ const thread = rawThread === CHANNEL ? null : rawThread && THREAD_KEY.test(rawThread) ? rawThread : undefined;
+
+ const threads = master ? [] : await chatThreads(db, chat.id);
+ const messages = master ? await masterFeed(db, user, { limit: 150 }) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
+ const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null;
+
+ // Live state of the questions in view (answer buttons, «отвечено» marks).
+ const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
+ const qs = qIds.length
+ ? await db.select({ q: questions, status: tasks.status, key: projects.key, number: tasks.number }).from(questions).innerJoin(projects, eq(questions.projectId, projects.id)).leftJoin(tasks, eq(questions.taskId, tasks.id)).where(inArray(questions.id, qIds))
+ : [];
+ const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }]));
+
+ const url = (p: { thread?: string | null }) => {
+ const base = `/chats/${chat.slug}`;
+ return p.thread ? `${base}?thread=${encodeURIComponent(p.thread)}` : base;
+ };
+ const here = url({ thread: thread === null ? CHANNEL : thread });
+ const bot = (await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null;
+ const ttlDays = Math.round(chatTtlMs() / 86_400_000);
+ const taskThread = thread?.startsWith("task:");
+ const placeholder = master
+ ? "/status, /task KEY-N, /move KEY-N in_progress, /help"
+ : taskThread
+ ? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
+ : thread
+ ? "Заметка в тред или команда /help"
+ : "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
+
+ const aside = (
+
+
+ Telegram
+ {chat.tgTitle ? (
+ <>
+
+ Связан с группой {chat.tgTitle} . Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}.
+
+
+
+
+
+ Отвязать группу
+
+
+ >
+ ) : link ? (
+
+ ) : (
+ <>
+ {master ? "Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам." : "Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}
+
+
+
+
+ Связать с Telegram
+
+
+ >
+ )}
+ Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только ты)" : "проекту"}.
+
+
+ Как это устроено
+ {master ? "Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM." : "Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной."}
+ Переписка хранится {ttlDays} дн.; стори, вопросы и события остаются на своих страницах.
+
+
+ );
+
+ return (
+
+
+
+ Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.
+
+
+ {list.map((c) => (
+
+ {c.kind === "master" ? : }
+ {c.kind === "master" ? "Мастер-чат" : c.slug}
+ {c.tgTitle && }
+ {c.open > 0 && {c.open} }
+
+ ))}
+
+
+
+ {!master && (
+
+
+
+ {threads.length > 0 &&
}
+ {threads.map((t) => (
+
+ ))}
+ {threads.length === 0 && Тредов пока нет.
}
+
+ )}
+
+
+ {current && (
+
+ 🧵 {current}
+ {taskThread && }
+
+ )}
+ {messages.length === 0 ? (
+ {master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}
+ ) : (
+
+ {messages.map((m) => (
+
+
+
+ ))}
+
+ )}
+
+
+
+
+ {thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}
+
+
+ Отправить
+
+
+
+
+
+
+ );
+}
+
+function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) {
+ return (
+
+
+ {title}
+ {open > 0 && {open} }
+
+ {meta && {meta} }
+
+ );
+}
+
+function TaskLink({ messages }: { messages: ChatMessageView[] }) {
+ const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
+ return key ? открыть стори → : null;
+}
+
+function threadHref(m: ChatMessageView) {
+ return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
+}
+
+function MessageItem({ m, q, back, showThread, masterView }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean }) {
+ const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
+ const href = threadHref(m);
+ const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle].filter(Boolean).join(" · ");
+ const head = (
+
+ {m.authorKind === "user" ? : m.authorKind === "agent" ? : }
+ {m.authorKind === "user" ? (m.authorLogin ?? "?") : m.authorKind === "agent" ? "агент" : "Пеппа"}
+ {m.via === "telegram" && · Telegram }
+ {where && href && (
+
+ 🧵 {label}
+
+ )}
+ {ago(m.createdAt)}
+
+ );
+ if (q) {
+ return (
+
+ {head}
+
+
+ );
+ }
+ return (
+
+ {head}
+ {m.text}
+ {m.url && (
+
+ {m.url}
+
+ )}
+
+ );
+}
diff --git a/apps/web/app/(app)/chats/actions.ts b/apps/web/app/(app)/chats/actions.ts
new file mode 100644
index 00000000..019d2c91
--- /dev/null
+++ b/apps/web/app/(app)/chats/actions.ts
@@ -0,0 +1,54 @@
+"use server";
+// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
+
+import { chatForUser, createChatLinkCode, PeppaError, unlinkChat } from "@peppa/core";
+import { postToChat } from "@peppa/runner";
+import { loadEnv } from "@peppa/shared";
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { asWebActor, requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+
+const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
+
+/** Runs an action; errors come back as ?error=… (redirect stays outside try). */
+async function attempt(f: FormData, fn: () => Promise): Promise {
+ let target = str(f, "back") || "/chats";
+ try {
+ target = (await fn()) || target;
+ } catch (e) {
+ const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
+ const [path, query] = target.split("?");
+ const params = new URLSearchParams(query);
+ params.set("error", msg.slice(0, 300));
+ target = `${path}?${params}`;
+ }
+ revalidatePath("/chats", "layout");
+ redirect(target);
+}
+
+export async function postChatAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const thread = str(f, "thread");
+ await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web" });
+ });
+}
+
+/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link that sends it. */
+export async function linkChatAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const token = loadEnv().TELEGRAM_BOT_TOKEN;
+ if (!token) throw new PeppaError("Telegram-бот Пеппы не настроен");
+ const chat = await chatForUser(db, user, Number(str(f, "chatId")));
+ const code = await createChatLinkCode(db, token, user, chat.id);
+ const back = str(f, "back") || "/chats";
+ return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`;
+ });
+}
+
+export async function unlinkChatAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId"))));
+}
diff --git a/apps/web/app/(app)/chats/page.tsx b/apps/web/app/(app)/chats/page.tsx
new file mode 100644
index 00000000..3e0aa8cf
--- /dev/null
+++ b/apps/web/app/(app)/chats/page.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "next/navigation";
+
+export default function Chats() {
+ redirect("/chats/master");
+}
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 0cd5a95d..10260786 100644
--- a/apps/web/components/Sidebar.tsx
+++ b/apps/web/components/Sidebar.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { Bot, Contact, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
+import { Bot, Contact, FolderKanban, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@@ -16,13 +16,16 @@ interface Item {
count?: "questions" | "waitingRunners";
/** Superadmin only (PEP-68, PEP-67; others get 404 on the URL too); desktop panel only — on phones it is linked from Settings. */
admin?: boolean;
+ /** Not in the phone tab bar (six tabs fit; PEP-62 added «Чаты»). */
+ desktopOnly?: boolean;
}
const ITEMS: Item[] = [
{ href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" },
+ { href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") },
{ href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
{ href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" },
- { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team") },
+ { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
@@ -55,7 +58,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
{ITEMS.filter((i) => !i.admin || superadmin).map((i) => {
const active = i.match(path);
@@ -66,7 +69,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
href={i.href}
aria-current={active ? "page" : undefined}
className={cn(
- i.admin && "max-md:hidden",
+ (i.admin || i.desktopOnly) && "max-md:hidden",
"relative flex flex-col items-center gap-0.5 px-1 pt-2 pb-1.5 text-[10px] text-muted-foreground transition-colors hover:text-foreground hover:no-underline md:flex-row md:gap-2 md:rounded-md md:px-2.5 md:py-1.5 md:text-sm md:hover:bg-accent",
active && "font-medium text-foreground md:bg-accent md:before:absolute md:before:inset-y-1.5 md:before:-left-3 md:before:w-0.5 md:before:rounded-full md:before:bg-primary",
)}
diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts
index b042192e..1f1211b1 100644
--- a/packages/runner/src/live.ts
+++ b/packages/runner/src/live.ts
@@ -9,7 +9,7 @@ import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type
import { events, sessions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
-export type LiveScope = "home" | "runners" | `project:${number}` | `task:${number}` | `steps:${number}`;
+export type LiveScope = "home" | "runners" | "chats" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
type Listener = (e: LiveEvent) => void;
@@ -29,7 +29,7 @@ const WAKE_DEBOUNCE_MS = 250;
export function parseScopes(raw: string | null): LiveScope[] {
const out = new Set();
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
- if (part === "home" || part === "runners") out.add(part);
+ if (part === "home" || part === "runners" || part === "chats") out.add(part);
else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
else throw new LiveError(`Неизвестная область: ${part}`, 400);
}
@@ -99,6 +99,19 @@ function fingerprint(db: Db, scope: LiveScope): string {
.get(id) as Record;
return Object.values(row).join("|");
}
+ if (kind === "chats") {
+ // PEP-62: a new chat message (projected or written) or a question answered anywhere.
+ const row = c
+ .prepare(
+ `SELECT
+ (SELECT coalesce(max(id),0) FROM chat_messages) AS m,
+ (SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
+ (SELECT coalesce(max(id),0) FROM events WHERE type <> 'step') AS e,
+ (SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`,
+ )
+ .get() as Record;
+ return Object.values(row).join("|");
+ }
// home / runners: across projects (only wakes the page — data stays behind access checks).
const row = c
.prepare(
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 3175e7a0..3a1bf448 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
+ pruneChats,
+ syncChats,
getBudgetState,
runAsActor,
expireSessionQuestions,
@@ -83,7 +85,15 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise {
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
// Daily digest at each user's time (PEP-29); a no-op outside their window.
await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`));
+ // PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour.
+ await syncChats(db, { now: opts.now }).catch((e) => log(`chats: ${(e as Error).message}`));
+ const nowMs = (opts.now ?? new Date()).getTime();
+ if (nowMs - lastChatPrune >= 3600_000) {
+ lastChatPrune = nowMs;
+ await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch((e) => log(`chats prune: ${(e as Error).message}`));
+ }
}
+let lastChatPrune = 0;
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
if (s.tmuxName.startsWith("pending-")) return;
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 9b177f04..d415bf6f 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -18,6 +18,9 @@ export interface MockTgUser {
username?: string;
}
+/** Groups have negative ids in Telegram. */
+const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
+
export class MockTelegram {
readonly token = "mock-123:TOKEN";
readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
@@ -104,7 +107,7 @@ export class MockTelegram {
reply_to: (p.reply_parameters as { message_id?: number } | undefined)?.message_id,
};
this.messages.set(m.message_id, m);
- return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: "private" }, text: m.text } };
+ return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: chatType(m.chat_id) }, text: m.text } };
}
case "editMessageText": {
const m = this.messages.get(Number(p.message_id));
@@ -148,6 +151,20 @@ export class MockTelegram {
});
}
+ /** PEP-62: a user writes in a group (negative chat id, as in Telegram), optionally as a reply. */
+ userSendsInGroup(user: MockTgUser, group: { id: number; title: string }, text: string, replyTo?: number) {
+ const chat = { id: group.id, type: "group", title: group.title };
+ return this.push({
+ message: {
+ message_id: this.nextMessageId++,
+ chat,
+ from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
+ text,
+ ...(replyTo ? { reply_to_message: { message_id: replyTo, chat } } : {}),
+ },
+ });
+ }
+
/** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */
userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) {
const fileId = `mock-voice-${this.nextMessageId}`;
@@ -170,7 +187,7 @@ export class MockTelegram {
callback_query: {
id,
from: { id: user.id, username: user.username },
- message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: "private" }, text: m?.text },
+ message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: chatType(m?.chat_id ?? user.chatId) }, text: m?.text },
data,
},
});
diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts
new file mode 100644
index 00000000..7b7a0c60
--- /dev/null
+++ b/packages/testkit/test/chats.test.ts
@@ -0,0 +1,253 @@
+// PEP-62: chats — events projected into project chats with threads, a reply in a story thread
+// goes to the agent, the master feed and its commands, a linked Telegram group (the real bot
+// against mock-telegram), and the short TTL.
+import assert from "node:assert/strict";
+import { after, before, describe, test } from "node:test";
+// helpers must load first: it sets the isolated test env that runner modules read on load.
+import { core, db, runner, teardown, waitFor } from "./helpers.ts";
+import { MockTelegram } from "../src/mock-telegram.ts";
+import { chatMessages, users } from "@peppa/db";
+import { eq } from "drizzle-orm";
+import type { Bot } from "@peppa/bot";
+
+const { createBot } = await import("@peppa/bot");
+const { TelegramApi } = await import("@peppa/bot/telegram");
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const tg = await new MockTelegram().start();
+const PM = { id: 701, chatId: 701, username: "pm" };
+const BOB = { id: 702, chatId: 702, username: "bob" };
+const STRANGER = { id: 709, chatId: 709, username: "stranger" };
+const GROUP = { id: -100500, title: "PAY team" };
+let bot: Bot;
+let pm: Awaited>;
+let bob: typeof pm;
+let eve: typeof pm;
+let seq = 0;
+
+async function newProject() {
+ const key = `C${String.fromCharCode(65 + seq++)}`;
+ const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
+ await core.addMember(db, p, bob.login, pm.id);
+ return p;
+}
+async function newTask(p: { id: number }, title = "Экспорт в CSV") {
+ const ref = await core.createTask(db, { projectId: p.id, title });
+ return core.resolveTask(db, ref.key);
+}
+const threadOf = (taskId: number) => `task:${taskId}`;
+const groupMessages = () => tg.botMessages(GROUP.id);
+
+before(async () => {
+ pm = await core.upsertUserFromGitea(db, { id: 81, login: "mock-pm" }, { access_token: "x" });
+ bob = await core.upsertUserFromGitea(db, { id: 82, login: "mock-bob" }, { access_token: "y" });
+ eve = await core.upsertUserFromGitea(db, { id: 83, login: "mock-eve" }, { access_token: "z" });
+ await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
+ await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
+ pm = (await core.getUser(db, pm.id))!;
+ bob = (await core.getUser(db, bob.id))!;
+});
+after(async () => {
+ await bot?.stop();
+ await tg.stop();
+ await teardown();
+});
+
+describe("project chat", () => {
+ test("Вопрос агента в треде стори; повторный перенос без дублей", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
+ await core.syncChats(db);
+ await core.syncChats(db);
+ const msgs = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ const qs = msgs.filter((m) => m.question?.id === q.id);
+ assert.equal(qs.length, 1);
+ assert.equal(qs[0]!.threadTitle, `${ref.key} · Экспорт в CSV`);
+ const threads = await core.chatThreads(db, chat.id);
+ assert.equal(threads[0]!.key, threadOf(ref.task.id));
+ assert.equal(threads[0]!.open, 1);
+ // The question is still on the home page (pending questions).
+ assert.ok((await core.pendingQuestions(db)).some((x) => x.id === q.id));
+ });
+
+ test("Ответ на вопрос из треда уходит агенту", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?" });
+ const r = await runner.postToChat(db, bob, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "точка с запятой", via: "web" });
+ const fresh = await core.getQuestion(db, q.id);
+ assert.equal(fresh.answer, "точка с запятой");
+ assert.equal(fresh.answeredVia, "web");
+ assert.match(r.reply!.text, /сохранён|ушёл агенту/);
+ const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ assert.ok(thread.some((m) => m.kind === "user" && m.authorLogin === bob.login && m.text === "точка с запятой"));
+ });
+
+ test("Комментарий без вопроса: у стори комментарий, в треде одно сообщение", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const r = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "не забудь заголовки", via: "web" });
+ assert.match(r.reply!.text, /Комментарий сохранён/);
+ const comments = await core.storyComments(db, ref.task.id);
+ assert.deepEqual(comments.map((c) => c.text), ["не забудь заголовки"]);
+ await core.syncChats(db);
+ const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ assert.equal(thread.filter((m) => m.text === "не забудь заголовки").length, 1);
+ });
+
+ test("Чужой проект: запрос отклонён, сообщения нет", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ await assert.rejects(runner.postToChat(db, eve, { chatId: chat.id, threadKey: null, text: "привет", via: "web" }), /не найден/);
+ assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
+ assert.equal((await core.listChats(db, eve)).filter((c) => c.kind === "project").length, 0);
+ });
+
+ test("Тред чужого проекта нельзя подставить", async () => {
+ const a = await newProject();
+ const b = await newProject();
+ const ref = await newTask(b);
+ const chat = await core.ensureProjectChat(db, a.id);
+ await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "x", via: "web" }), /не из этого чата/);
+ });
+
+ test("Релиз и инцидент — свои треды", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const { releases } = await import("@peppa/db");
+ const [rel] = await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "abcdef1234567", status: "healthy", tasks: ["CX-1"] }).returning();
+ await core.syncChats(db);
+ const threads = await core.chatThreads(db, chat.id);
+ assert.ok(threads.some((t) => t.key === `release:${rel!.id}` && t.title === "Релиз staging abcdef1"));
+ });
+});
+
+describe("master chat", () => {
+ test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => {
+ const p = await newProject();
+ const ref = await newTask(p, "Платежи");
+ await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "stalled", payload: { idleMinutes: 15 } });
+ await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "progress", payload: { text: "половина готова" } });
+ await core.syncChats(db);
+ const feed = await core.masterFeed(db, pm);
+ assert.ok(feed.some((m) => /Агент молчит 15 мин/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
+ assert.ok(!feed.some((m) => /половина готова/.test(m.text)), "progress is not important");
+
+ const master = await core.ensureMasterChat(db, pm.id);
+ const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/task ${ref.key}`, via: "web" });
+ assert.match(r.reply!.text, new RegExp(`${ref.key}: Платежи[\\s\\S]*бэклог`));
+ const bad = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: "/deploy всё", via: "web" });
+ assert.match(bad.reply!.text, /Не знаю такую команду[\s\S]*\/move/);
+ // Bob's master chat is his own.
+ await assert.rejects(runner.postToChat(db, bob, { chatId: master.id, threadKey: null, text: "/status", via: "web" }), /не найден/);
+ });
+
+ test("Команда перемещения", async () => {
+ const p = await newProject();
+ const ref = await newTask(p);
+ const master = await core.ensureMasterChat(db, pm.id);
+ const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/move ${ref.key} done`, via: "web" });
+ assert.match(r.reply!.text, new RegExp(`${ref.key} → Готово`));
+ assert.equal((await core.resolveTask(db, ref.key)).task.status, "done");
+ });
+});
+
+describe("Telegram group", () => {
+ let p: Awaited>;
+ let chat: Awaited>;
+
+ before(async () => {
+ p = await newProject();
+ chat = await core.ensureProjectChat(db, p.id);
+ bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, changesIntervalMs: 200, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
+ await bot.start();
+ await bot.reconcile(); // first start: mirroring begins from here
+ });
+
+ test("Просроченный код и связка группы", async () => {
+ const code = await core.createChatLinkCode(db, tg.token, pm, chat.id);
+ // A stale code: accepted 11 minutes later.
+ const stale = await core.createChatLinkCode(db, tg.token, pm, chat.id);
+ assert.equal(await core.acceptChatLink(db, tg.token, stale, { tgChatId: -1, title: "x" }, Date.now() + 11 * 60_000), null);
+ tg.userSendsInGroup(PM, GROUP, `/link ${stale}`);
+ await waitFor("stale code reply", async () => groupMessages().some((m) => /неверный или истёк/.test(m.text)));
+ tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${code}`);
+ await waitFor("linked", async () => groupMessages().some((m) => /Группа связана с чатом проекта/.test(m.text)));
+ const linked = await core.getChat(db, chat.id);
+ assert.equal(linked.tgChatId, GROUP.id);
+ assert.equal(linked.tgTitle, GROUP.title);
+ });
+
+ test("Вопрос в группе, ответ реплаем, тред — цепочка ответов", async () => {
+ const ref = await newTask(p, "Экспорт отчёта");
+ const q = await core.askPm(db, ref, { kind: "question", text: "Какой формат даты?", options: ["ISO", "ДД.ММ.ГГГГ"] });
+ const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Какой формат даты?")));
+ assert.ok(qMsg.reply_markup?.inline_keyboard.flat().some((b) => b.callback_data === `q:${q.id}:o0`));
+
+ // Somebody without a Peppa account replies: ignored with a hint.
+ tg.userSendsInGroup(STRANGER, GROUP, "ISO конечно", qMsg.message_id);
+ await waitFor("stranger hint", async () => groupMessages().some((m) => /Не знаю тебя в Пеппе/.test(m.text)));
+ assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
+
+ tg.userSendsInGroup(BOB, GROUP, "ДД.ММ.ГГГГ", qMsg.message_id);
+ const answered = await waitFor("answered from the group", async () => {
+ const x = await core.getQuestion(db, q.id);
+ return x.answeredAt ? x : null;
+ });
+ assert.equal(answered.answer, "ДД.ММ.ГГГГ");
+ assert.equal(answered.answeredVia, "telegram");
+ const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
+ assert.ok(thread.some((m) => m.kind === "user" && m.via === "telegram" && m.authorLogin === bob.login));
+ // Peppa's note about it hangs on the thread's first message; Bob's own message isn't echoed.
+ const note = await waitFor("reply note in the thread", async () => groupMessages().find((m) => /Ответ (ушёл агенту|сохранён)/.test(m.text)));
+ assert.equal(note.reply_to, qMsg.message_id);
+ assert.ok(!groupMessages().some((m) => m.text.includes("mock-bob") && m.text.includes("ДД.ММ.ГГГГ") && !m.text.includes("Какой формат")));
+
+ // A web message in the same thread reaches the group as a reply too.
+ await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "и время в UTC", via: "web" });
+ const web = await waitFor("web message in the group", async () => groupMessages().find((m) => m.text.includes("и время в UTC")));
+ assert.equal(web.reply_to, qMsg.message_id);
+ assert.match(web.text, /mock-pm.*\(веб\)/);
+ });
+
+ test("Кнопка вопроса в группе", async () => {
+ const ref = await newTask(p, "Кнопки");
+ const q = await core.askPm(db, ref, { kind: "question", text: "Кнопкой?", options: ["да", "нет"] });
+ const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Кнопкой?")));
+ tg.userClicks(STRANGER, qMsg.message_id, `q:${q.id}:o0`);
+ await waitFor("stranger refused", async () => tg.callbackAnswers.some((c) => /Нет доступа/.test(c.text ?? "")));
+ tg.userClicks(BOB, qMsg.message_id, `q:${q.id}:o1`);
+ const x = await waitFor("answered by button", async () => {
+ const r = await core.getQuestion(db, q.id);
+ return r.answeredAt ? r : null;
+ });
+ assert.equal(x.answer, "нет");
+ });
+
+ test("Супергруппа сохраняет связку", async () => {
+ // Telegram sends migrate_to_chat_id when a group is upgraded.
+ await core.migrateChatGroup(db, GROUP.id, -1009999);
+ assert.equal((await core.getChat(db, chat.id)).tgChatId, -1009999);
+ await core.migrateChatGroup(db, -1009999, GROUP.id);
+ });
+});
+
+describe("TTL", () => {
+ test("Старые сообщения удалены, вопрос остаётся", async () => {
+ const p = await newProject();
+ const chat = await core.ensureProjectChat(db, p.id);
+ const ref = await newTask(p);
+ const q = await core.askPm(db, ref, { kind: "question", text: "Старый вопрос" });
+ await core.syncChats(db);
+ const old = new Date(Date.now() - 15 * 86_400_000);
+ await db.update(chatMessages).set({ createdAt: old }).where(eq(chatMessages.chatId, chat.id));
+ const n = await core.pruneChats(db);
+ assert.ok(n >= 1);
+ assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
+ assert.equal((await core.getQuestion(db, q.id)).text, "Старый вопрос");
+ });
+});
--
2.45.2
From c751291bb9aab4d2a5f83410575e1748736236f8 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 19:10:12 +0500
Subject: [PATCH 015/439] PEP-62: help and AGENTS.md for chats
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
apps/web/app/(app)/help/page.tsx | 16 ++++++++++++++++
openspec/changes/pep-62-chats/tasks.md | 22 +++++++++++-----------
3 files changed, 28 insertions(+), 11 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 6ba94b29..e02aefcd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,6 +34,7 @@
- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
+- **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 049e478e..dc1ebc3b 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -204,6 +204,22 @@ export default async function Help() {
+
+
+ Чаты — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы,
+ прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый
+ вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам
+ (вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N,
+ /move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней.
+
+
+ Любой чат можно связать с группой Telegram: «Связать с Telegram» в чате → добавьте бота в группу по ссылке (или
+ отправьте в группе /link код ). Сообщения чата придут в группу, тред — цепочкой
+ ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в
+ Настройках и имеет доступ к проекту (в мастер-группе — только владелец).
+
+
+
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
diff --git a/openspec/changes/pep-62-chats/tasks.md b/openspec/changes/pep-62-chats/tasks.md
index cbf0dcdf..1e389b73 100644
--- a/openspec/changes/pep-62-chats/tasks.md
+++ b/openspec/changes/pep-62-chats/tasks.md
@@ -1,21 +1,21 @@
## 1. Модель и ядро
-- [ ] 1.1 Схема `chats`, `chat_messages`, `telegram_outbox.chat_message_id`, миграция
-- [ ] 1.2 core/chats.ts: чаты (ensure), проекция `syncChats`, ленты/треды, коды связки, TTL
-- [ ] 1.3 Мастер-чат: мониторинг и дайджест из `deliverToUser`
+- [x] 1.1 Схема `chats`, `chat_messages`, `telegram_outbox.chat_message_id`, миграция
+- [x] 1.2 core/chats.ts: чаты (ensure), проекция `syncChats`, ленты/треды, коды связки, TTL
+- [x] 1.3 Мастер-чат: мониторинг и дайджест из `deliverToUser`
## 2. Ответы и команды
-- [ ] 2.1 runner/chats.ts `postToChat`: ответ агенту / комментарий / заметка, команды
+- [x] 2.1 runner/chats.ts `postToChat`: ответ агенту / комментарий / заметка, команды
## 3. Telegram
-- [ ] 3.1 Бот: связка группы (`/start <код>`, `/link`), миграция в супергруппу
-- [ ] 3.2 Бот: зеркало сообщений в группы, треды реплаями, кнопки вопросов
-- [ ] 3.3 Бот: приём реплаев, команд и кнопок из групп с проверкой доступа
+- [x] 3.1 Бот: связка группы (`/start <код>`, `/link`), миграция в супергруппу
+- [x] 3.2 Бот: зеркало сообщений в группы, треды реплаями, кнопки вопросов
+- [x] 3.3 Бот: приём реплаев, команд и кнопок из групп с проверкой доступа
## 4. Веб и вачдог
-- [ ] 4.1 `/chats/[chat]`: список чатов, треды, лента, композер, связка с Telegram; меню
-- [ ] 4.2 Живое обновление (`chats`), вызовы проекции и TTL в вачдоге, создание чата с проектом
-- [ ] 4.3 Справка `/help`, AGENTS.md
+- [x] 4.1 `/chats/[chat]`: список чатов, треды, лента, композер, связка с Telegram; меню
+- [x] 4.2 Живое обновление (`chats`), вызовы проекции и TTL в вачдоге, создание чата с проектом
+- [x] 4.3 Справка `/help`, AGENTS.md
## 5. Проверка
-- [ ] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
+- [x] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
- [ ] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
--
2.45.2
From 5cfc2cb269f5572d0517b947405392ece154a109 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 19:12:57 +0500
Subject: [PATCH 016/439] PEP-62: archive change pep-62-chats, project memory
Co-Authored-By: Claude Opus 5.5
---
.peppa/memory.md | 9 ++
.../2026-11-14-pep-62-chats}/design.md | 0
.../2026-11-14-pep-62-chats}/proposal.md | 0
.../specs/project-chats/spec.md | 0
.../2026-11-14-pep-62-chats}/tasks.md | 2 +-
openspec/specs/project-chats/spec.md | 101 ++++++++++++++++++
6 files changed, 111 insertions(+), 1 deletion(-)
create mode 100644 .peppa/memory.md
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/design.md (100%)
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/proposal.md (100%)
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/specs/project-chats/spec.md (100%)
rename openspec/changes/{pep-62-chats => archive/2026-11-14-pep-62-chats}/tasks.md (95%)
create mode 100644 openspec/specs/project-chats/spec.md
diff --git a/.peppa/memory.md b/.peppa/memory.md
new file mode 100644
index 00000000..d53119c3
--- /dev/null
+++ b/.peppa/memory.md
@@ -0,0 +1,9 @@
+# Память проекта
+
+Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.
+
+## Грабли
+- node --test из шелла Claude Code молча ничего не запускает («run() is being called recursively») — в env висит NODE_TEST_CONTEXT; запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test …`
+
+## Решения
+- Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents.
diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/archive/2026-11-14-pep-62-chats/design.md
similarity index 100%
rename from openspec/changes/pep-62-chats/design.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/design.md
diff --git a/openspec/changes/pep-62-chats/proposal.md b/openspec/changes/archive/2026-11-14-pep-62-chats/proposal.md
similarity index 100%
rename from openspec/changes/pep-62-chats/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/proposal.md
diff --git a/openspec/changes/pep-62-chats/specs/project-chats/spec.md b/openspec/changes/archive/2026-11-14-pep-62-chats/specs/project-chats/spec.md
similarity index 100%
rename from openspec/changes/pep-62-chats/specs/project-chats/spec.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/specs/project-chats/spec.md
diff --git a/openspec/changes/pep-62-chats/tasks.md b/openspec/changes/archive/2026-11-14-pep-62-chats/tasks.md
similarity index 95%
rename from openspec/changes/pep-62-chats/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-62-chats/tasks.md
index 1e389b73..0d8f7aab 100644
--- a/openspec/changes/pep-62-chats/tasks.md
+++ b/openspec/changes/archive/2026-11-14-pep-62-chats/tasks.md
@@ -18,4 +18,4 @@
## 5. Проверка
- [x] 5.1 e2e: проекция, ответ в треде, мастер-лента, связка и реплай из группы, TTL
-- [ ] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
+- [x] 5.2 typecheck, тесты, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/project-chats/spec.md b/openspec/specs/project-chats/spec.md
new file mode 100644
index 00000000..10c091dd
--- /dev/null
+++ b/openspec/specs/project-chats/spec.md
@@ -0,0 +1,101 @@
+# project-chats Specification
+
+## Purpose
+TBD - created by archiving change pep-62-chats. Update Purpose after archive.
+
+## Requirements
+
+### Requirement: Чат проекта с тредами
+У каждого проекта SHALL быть чат. События проекта SHALL попадать в чат: про стори — в тред
+стори, про инцидент — в тред инцидента, про релиз — в тред релиза, остальное — в общий
+канал. Перенос событий SHALL быть идемпотентным: повторный запуск не создаёт дублей.
+
+#### Scenario: Вопрос агента в треде стори
+- **GIVEN** проект PAY со стори PAY-7 «Экспорт в CSV»
+- **WHEN** агент PAY-7 задаёт вопрос «Какой разделитель?»
+- **THEN** в чате PAY появляется тред «PAY-7 · Экспорт в CSV» с этим вопросом и кнопками ответа
+- **AND** вопрос по-прежнему виден на Главной
+
+#### Scenario: Повторный перенос
+- **GIVEN** вопрос PAY-7 уже перенесён в чат
+- **WHEN** перенос запускается ещё раз из бота и из веба
+- **THEN** в треде PAY-7 одно сообщение с этим вопросом
+
+### Requirement: Ответ в треде уходит агенту
+Сообщение участника в треде стори SHALL отвечать на открытый вопрос стори, а без открытого
+вопроса — становиться комментарием PM к стори и уходить в живой раннер. Сообщение в треде
+инцидента, релиза или в общем канале SHALL оставаться заметкой. Писать в чат проекта SHALL
+могут только владелец и участники проекта.
+
+#### Scenario: Ответ на вопрос
+- **GIVEN** у PAY-7 открыт вопрос «Какой разделитель?»
+- **WHEN** участник пишет в тред PAY-7 «точка с запятой»
+- **THEN** вопрос отвечен «точка с запятой», ответ ушёл в сессию агента
+- **AND** в треде видно сообщение участника и отметку «Ответ ушёл агенту»
+
+#### Scenario: Комментарий без вопроса
+- **GIVEN** у PAY-7 нет открытых вопросов и раннер не запущен
+- **WHEN** участник пишет в тред PAY-7 «не забудь заголовки»
+- **THEN** у стори появляется комментарий PM «не забудь заголовки», агент увидит его в get_task
+
+#### Scenario: Чужой проект
+- **GIVEN** пользователь «bob» не участник проекта PAY
+- **WHEN** он пытается написать в чат PAY
+- **THEN** запрос отклонён как «не найдено», сообщения в чате нет
+
+### Requirement: Мастер-чат
+У каждого пользователя SHALL быть мастер-чат: важные события всех его проектов (вопросы,
+готово к ревью, сбои и лимиты раннеров, релизы, ошибки из прода), мониторинг и дайджест.
+Мастер-чат SHALL выполнять команды `/help`, `/status`, `/task KEY-N`, `/move KEY-N <колонка>`
+без LLM; писать в мастер-чат SHALL может только его владелец.
+
+#### Scenario: Сбой раннера в мастер-чате
+- **GIVEN** пользователь «anna» владеет проектом PAY
+- **WHEN** раннер PAY-7 зависает
+- **THEN** в мастер-чате «anna» видно сообщение о зависании PAY-7 со ссылкой на тред
+
+#### Scenario: Команда перемещения
+- **GIVEN** стори PAY-8 в бэклоге проекта «anna»
+- **WHEN** «anna» пишет в мастер-чат `/move PAY-8 in_progress`
+- **THEN** стори PAY-8 в работе, агент запущен, в мастер-чате ответ «PAY-8 → В работе»
+
+#### Scenario: Неизвестная команда
+- **WHEN** «anna» пишет в мастер-чат `/deploy всё`
+- **THEN** в ответ — «Не знаю такую команду» и список команд, ничего не выполнено
+
+### Requirement: Связка чата с Telegram-группой
+Чат проекта и мастер-чат SHALL связываться с обычной Telegram-группой по одноразовому коду
+(10 минут). Сообщения связанного чата SHALL дублироваться в группу, тред — цепочкой реплаев
+на первое сообщение треда. Реплай в группе SHALL попадать в тот же тред и обрабатываться как
+сообщение из веба; принимать его SHALL только от пользователя Пеппы с привязанным Telegram и
+доступом к проекту (в мастер-группе — от владельца мастер-чата).
+
+#### Scenario: Связать группу
+- **GIVEN** участник открыл чат PAY и нажал «Связать с Telegram»
+- **WHEN** в группе «PAY team» отправлено `/link <код>` до истечения кода
+- **THEN** чат PAY связан с «PAY team», бот подтверждает это в группе, веб показывает название группы
+
+#### Scenario: Просроченный код
+- **GIVEN** код связки выдан 11 минут назад
+- **WHEN** в группе отправлено `/link <код>`
+- **THEN** бот отвечает, что код неверный или истёк, чат не связан
+
+#### Scenario: Ответ реплаем из группы
+- **GIVEN** чат PAY связан с группой, вопрос PAY-7 пришёл в группу
+- **AND** «anna» привязала Telegram и участник PAY
+- **WHEN** «anna» отвечает реплаем на вопрос «точка с запятой»
+- **THEN** вопрос отвечен, в веб-треде PAY-7 видно её сообщение с пометкой Telegram
+
+#### Scenario: Посторонний в группе
+- **GIVEN** в группе PAY есть человек без привязки Telegram в Пеппе
+- **WHEN** он отвечает реплаем на вопрос PAY-7
+- **THEN** вопрос не отвечен, сообщения в чате нет, бот подсказывает привязать Telegram
+
+### Requirement: Короткое хранение переписки
+Сообщения чатов SHALL удаляться через `PEPPA_CHAT_TTL_DAYS` дней (по умолчанию 14); стори,
+вопросы, события, релизы и инциденты при этом SHALL оставаться.
+
+#### Scenario: Старые сообщения удалены
+- **GIVEN** сообщение в треде PAY-7 от 15 дней назад и вопрос PAY-7, к которому оно относится
+- **WHEN** вачдог чистит чаты
+- **THEN** сообщения в чате нет, вопрос PAY-7 остаётся в стори
--
2.45.2
From 82c003e2093d15859e4c6b5e1143277313a5a330 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 19:03:45 +0500
Subject: [PATCH 017/439] =?UTF-8?q?PEP-60:=20platform=20Telegram=20channel?=
=?UTF-8?q?=20=E2=80=94=20check,=20releases,=20outages/restarts,=20platfor?=
=?UTF-8?q?m=20digest?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/bot/src/bot.ts | 1 +
apps/web/app/(app)/platform/actions.ts | 57 +++
apps/web/app/(app)/platform/page.tsx | 114 ++++++
apps/web/app/(app)/settings/page.tsx | 3 +
apps/web/components/Sidebar.tsx | 3 +-
.../pep-60-platform-channel-digest/design.md | 66 ++++
.../pep-60-platform-channel-digest/tasks.md | 16 +-
packages/cli/src/index.ts | 41 ++
packages/core/src/index.ts | 1 +
packages/core/src/monitor.ts | 60 ++-
packages/core/src/notifications.ts | 5 +-
packages/core/src/platform-channel.ts | 371 ++++++++++++++++++
packages/runner/src/index.ts | 1 +
packages/runner/src/platform-build.ts | 57 +++
packages/runner/src/watchdog.ts | 8 +
packages/testkit/src/mock-telegram.ts | 24 ++
.../testkit/test/platform-channel.test.ts | 309 +++++++++++++++
17 files changed, 1123 insertions(+), 14 deletions(-)
create mode 100644 apps/web/app/(app)/platform/actions.ts
create mode 100644 apps/web/app/(app)/platform/page.tsx
create mode 100644 openspec/changes/pep-60-platform-channel-digest/design.md
create mode 100644 packages/core/src/platform-channel.ts
create mode 100644 packages/runner/src/platform-build.ts
create mode 100644 packages/testkit/test/platform-channel.test.ts
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 435ab96a..24d5de2f 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -94,6 +94,7 @@ const PUSH_TITLE: Record = {
incidents: "Ошибка в проде",
monitoring: "Мониторинг",
digest: "Сводка",
+ platform: "Обновления Пеппы",
};
/** Browser notification text for a question. */
diff --git a/apps/web/app/(app)/platform/actions.ts b/apps/web/app/(app)/platform/actions.ts
new file mode 100644
index 00000000..10b40ac9
--- /dev/null
+++ b/apps/web/app/(app)/platform/actions.ts
@@ -0,0 +1,57 @@
+"use server";
+// «Платформа» (PEP-60): the platform's Telegram channel and digest — superadmin only.
+
+import { checkPlatformChannel, parseChatId, PeppaError, platformDigestTick, PLATFORM_CHANNEL_EVENTS, requireSuperadmin, setPlatformChannel } from "@peppa/core";
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { asWebActor, requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+
+const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
+const BASE = "/platform";
+
+async function attempt(fn: () => Promise): Promise {
+ const user = asWebActor(await requireUser());
+ let target = BASE;
+ try {
+ await requireSuperadmin(db, user);
+ target = (await fn()) || target;
+ } catch (e) {
+ const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
+ target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
+ }
+ revalidatePath(BASE);
+ redirect(target);
+}
+
+/** Saves the Chat ID (and checks the channel right away). */
+export async function saveChannelAction(f: FormData) {
+ await attempt(async () => {
+ const raw = str(f, "chatId");
+ const c = await setPlatformChannel(db, { chatId: raw ? parseChatId(raw) : null });
+ if (c.chatId != null) await checkPlatformChannel(db);
+ });
+}
+
+export async function checkChannelAction() {
+ await attempt(async () => {
+ await checkPlatformChannel(db);
+ });
+}
+
+export async function saveChannelSettingsAction(f: FormData) {
+ await attempt(async () => {
+ const events = Object.fromEntries(PLATFORM_CHANNEL_EVENTS.map((e) => [e, f.get(`event.${e}`) === "on"]));
+ await setPlatformChannel(db, { events, digest: { time: str(f, "time"), timezone: str(f, "timezone"), users: f.get("users") === "on" } });
+ });
+}
+
+/** Sends the platform digest now (over the time since the previous one). */
+export async function sendDigestNowAction() {
+ await attempt(async () => {
+ const r = await platformDigestTick(db, { force: true });
+ if (!r) throw new PeppaError("Некуда отправлять: канал не подключён и дайджест пользователям выключен");
+ if (!r.channel && !r.users) return `${BASE}?sent=empty`;
+ return `${BASE}?sent=${r.channel ? "channel" : ""}${r.users ? `,users:${r.users}` : ""}`;
+ });
+}
diff --git a/apps/web/app/(app)/platform/page.tsx b/apps/web/app/(app)/platform/page.tsx
new file mode 100644
index 00000000..8865e0cf
--- /dev/null
+++ b/apps/web/app/(app)/platform/page.tsx
@@ -0,0 +1,114 @@
+import { notFound } from "next/navigation";
+import { Megaphone, RefreshCw, Send } from "lucide-react";
+import { buildPlatformDigest, getPlatformBuild, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
+import { ago, Flash, PageHeader, Section } from "@/components/common";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input, Label } from "@/components/ui/input";
+import { Workspace } from "@/components/Workspace";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions";
+
+export const metadata = { title: "Платформа — Пеппа" };
+
+/** Telegram HTML of the digest → plain text for the preview. */
+const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
+
+export default async function Platform({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
+ const user = await requireUser();
+ if (!(await isSuperadmin(db, user))) notFound();
+ const { error, sent } = await searchParams;
+ const [c, build] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db)]);
+ const digest = await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) });
+ return (
+
+
+
+ {sent &&
{sent === "empty" ? "Дайджест пуст — нечего отправлять." : `Дайджест отправлен: ${sent.replace("channel", "в канал").replace(",users:", " · пользователям: ")}`}
}
+
Платформа>}>
+ Telegram-канал Пеппы: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Пеппе и что происходит сейчас. Раздел видят только суперадмины.
+ {build && <> Сейчас: v{build.version} · {build.commit.slice(0, 7)} .>}
+
+
+
+
+
+ {c.chatId == null ? (
+ канал не задан
+ ) : !c.check ? (
+ не проверен
+ ) : c.check.ok ? (
+ канал подключён
+ ) : (
+ не работает
+ )}
+ {c.check?.ok && c.title && {c.title} }
+ {c.check && проверен {ago(new Date(c.check.at))} }
+
+ {c.check && !c.check.ok && {c.check.error}
}
+
+
+ Chat ID канала
+
+
+ Сохранить и проверить
+
+ {c.chatId != null && (
+
+ Проверить ещё раз
+
+ )}
+
+ Добавьте бота Пеппы в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Пеппа перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.
+
+
+
+
+
+
+
+ Отправить сейчас
+
+ }
+ >
+ {platformDigestEmpty(digest) ? (
+ За сутки ничего нового и ничего не происходит — дайджест не уйдёт.
+ ) : (
+ {plain(renderPlatformDigest(digest))}
+ )}
+
+
+
+ );
+}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 06389f30..b64fb563 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -82,6 +82,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
Журнал
+
+ Платформа
+
>
}
>
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 0cd5a95d..aade574d 100644
--- a/apps/web/components/Sidebar.tsx
+++ b/apps/web/components/Sidebar.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { Bot, Contact, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
+import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@@ -28,6 +28,7 @@ const ITEMS: Item[] = [
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
{ href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
{ href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
+ { href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true },
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },
];
diff --git a/openspec/changes/pep-60-platform-channel-digest/design.md b/openspec/changes/pep-60-platform-channel-digest/design.md
new file mode 100644
index 00000000..bb1a4d4c
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/design.md
@@ -0,0 +1,66 @@
+# Design: PEP-60 — канал платформы и дайджест Пеппы
+
+## Настройки (без миграций)
+
+`settings` `platform.telegram_channel` (ключ уже есть в боевой базе: `{chatId, setAt}`) —
+`PlatformChannel` в `core/platform-channel.ts`, поверх умолчаний:
+
+- `chatId`, `title`, `check: {ok, error, at}` — результат последней проверки;
+- `events: {releases, services, digest}` — всё включено;
+- `digest: {time "09:00", timezone (PEPPA_TZ/сервер), users: false}` — личные чаты включает
+ суперадмин (без сюрприза всем пользователям в первый же день).
+
+Менять может только суперадмин (`requireSuperadmin`): веб `/platform` и CLI
+`peppa platform channel chat= [releases=on|off …]` (отрицательный id — через `chat=`:
+`parseArgs` принимает `-100…` за флаг), `peppa platform channel check`, `peppa platform digest [now]`.
+
+## Проверка канала
+
+`checkPlatformChannel` — Bot API напрямую (как прямая доставка вачдога PEP-20):
+`getMe` → `getChat(chat_id)` → `getChatMember(chat_id, bot)`. `chat not found` / 403 →
+«бот не видит канал — добавьте его администратором»; не админ или `can_post_messages: false`
+(в канале) → «бот не может публиковать — дайте право «Публикация сообщений»». Удача —
+`title` канала. Проверка при сохранении, кнопкой и раз в час в вачдоге, пока не ок (PM
+добавит бота — канал заработает сам). Писать в канал только при `check.ok`.
+
+## Отправка
+
+`postToChannel(db, kind, dedupeKey, text)` → тот же `telegram_outbox` (повторы, 429). Ключи
+сервисных событий начинаются с `mon:` — их вачдог доставляет сам, когда упал бот. Канал не
+принимает ответов: кнопок нет, бот на сообщения канала не реагирует (updates `channel_post`
+он и так не обрабатывает).
+
+## События
+
+- **Сервисы** — в `checkServices` (PEP-20) рядом с алертом админам: одно сообщение о
+ падении (без напоминаний) и одно о восстановлении с длительностью простоя; ключи от
+ начала простоя, поэтому бот и вачдог вместе дают одно сообщение. **Перезапуск** — смена
+ `heartbeat.startedAt` без простоя: «🔄 вачдог перезапущен (v0.15.0 · abc1234)».
+- **Релиз**. В heartbeat добавлен `commit` (`peppaCommit()`: `PEPPA_COMMIT` /
+ `NEXT_PUBLIC_PEPPA_COMMIT_FULL` / `git rev-parse HEAD` корня). Вачдог раз в минуту
+ (`platformBuildTick`, runner) берёт HEAD корня Пеппы; если он отличается от
+ `platform.build` и входит в `main` (`git merge-base --is-ancestor HEAD main`) — это выкатка:
+ «🚀 Peppa v0.16.0 · b1c2d3e» и стори из сообщений коммитов `prev..HEAD`
+ (`PEP-N`, с названиями). Так работает и сейчас (dev из рабочей копии: ветка задачи не
+ объявляется, возврат на обновлённый main — объявляется), и в проде PEP-18 (`current` —
+ worktree релиза от `main`). Первый запуск только запоминает сборку.
+
+## Дайджест платформы
+
+`buildPlatformDigest(since, now)`: «Что нового» — стори проекта Пеппы (`PEPPA_PLATFORM_KEY`),
+ставшие `done` после `since`, и сборки, объявленные с тех пор; «Сейчас» — версия · коммит,
+сервисы, активные раннеры, открытые вопросы, лимиты подписок (`listAccountUsage`, ≥ 50% или
+«лимит до»). Пусто (нет нового, нет раннеров, нет вопросов, сервисы в порядке) — не
+отправляется. `platformDigestTick` в `tick` вачдога: в `digest.time` (окно 3 ч, раз в
+местные сутки, `platform.digest.last`), в канал и — если `digest.users` — каждому
+пользователю событием уведомлений `platform` («Обновления Пеппы»: Telegram вкл, push выкл).
+Отписка — «Настройки → Уведомления» (строка появляется сама из `NOTIFY_EVENTS`); личный
+дайджест по проектам (PEP-29, событие `digest`) не меняется.
+
+## Решения
+
+- Без миграций — всё в `settings`, как прочие настройки платформы.
+- Отдельная страница `/platform` для суперадмина (по образцу `/hosts`), пункт меню
+ «Платформа»; не суперадмину — 404.
+- Окно сервиса «упал» — общий порог мониторинга (`PEPPA_MONITOR_STALE_MIN`), отдельный
+ порог для канала не вводим.
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/pep-60-platform-channel-digest/tasks.md
index d84d35c4..7276743f 100644
--- a/openspec/changes/pep-60-platform-channel-digest/tasks.md
+++ b/openspec/changes/pep-60-platform-channel-digest/tasks.md
@@ -1,16 +1,18 @@
# Tasks: PEP-60
## 0. Перед стартом
-- [x] 0.1 Бот — админ канала (проверка `getChat`/тестовое сообщение по согласию PM); роль суперадмина из PEP-16 (иначе только CLI)
+- [x] 0.1 Проверка бота в канале: `getChat(-1004371018094)` → «chat not found» — бот ещё не админ; работаем, канал включится сам после проверки
## 1. Канал
-- [x] 1.1 core: настройки платформы (канал, события, расписание); CLI `peppa platform channel ` и `platform status`
-- [x] 1.2 Веб: «Настройки платформы» для суперадмина с проверкой канала
-- [x] 1.3 События: релиз (из деплоя/CI, PEP-57; до него — при старте веба с новым коммитом), рестарт и падение/восстановление сервисов (heartbeat, PEP-20)
+- [x] 1.1 core `platform-channel.ts`: настройки, проверка канала (Bot API), `postToChannel`; CLI `peppa platform channel`
+- [x] 1.2 Веб `/platform` для суперадмина: Chat ID, проверка, события, расписание; пункт меню
+- [x] 1.3 События сервисов в `checkServices`: падение/восстановление/перезапуск; `commit` в heartbeat
+- [x] 1.4 Релиз: `platformBuildTick` (runner) — новая сборка из `main` со списком стори
## 2. Дайджест
-- [x] 2.1 Сбор: смерженные PR/задачи PEP с прошлого дайджеста, версия, сервисы, раннеры, вопросы, лимиты; пропуск, если пусто
-- [x] 2.2 Расписание и отправка в канал; личный дайджест пользователям (после PEP-2) и отписка в Настройках
+- [x] 2.1 `buildPlatformDigest` + рендер; пропуск, если пусто
+- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
## 3. Проверка
-- [x] 3.1 Тесты на mock-telegram — по сценарию спецификации на каждый; весь e2e зелёный; `openspec validate`
+- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
+- [ ] 3.2 Документация: AGENTS.md, `/help`
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 7d3977cf..3b687e59 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -71,6 +71,7 @@ import {
import { createDb, migrateDb } from "@peppa/db";
import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
+import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
import { createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
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";
@@ -121,6 +122,9 @@ const USAGE = `peppa — Peppa software factory CLI
(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 channel [chat=|@name|check] [releases|services|digest=on|off time=HH:MM tz= users=on|off]
+ (PEP-60: Telegram channel of the platform — events and the platform digest)
+ peppa platform digest [now] (PEP-60: show the platform digest; now — send it to the channel/users)
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)
@@ -641,6 +645,7 @@ async function main(): Promise {
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
console.log(`админы: ${admins.join(", ") || "нет"}`);
+ console.log(`канал платформы: ${describeChannel(await getPlatformChannel(db))}`);
break;
}
case "telegram pair": {
@@ -674,6 +679,42 @@ async function main(): Promise {
console.log(`${u.login} (#${u.id})`);
break;
}
+ case "platform channel": {
+ // PEP-60: the platform's Telegram channel (superadmin's setting; the CLI is an admin tool).
+ const patch: PlatformChannelPatch = {};
+ let check = false;
+ for (const a of args) {
+ if (a === "check") check = true;
+ else if (a === "-") patch.chatId = null;
+ else if (!a.includes("=")) patch.chatId = parseChatId(a);
+ else {
+ const [k, v] = [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)];
+ const on = v === "on" ? true : v === "off" ? false : null;
+ if (k === "chat") patch.chatId = v === "-" ? null : parseChatId(v);
+ else if ((PLATFORM_CHANNEL_EVENTS as readonly string[]).includes(k) && on != null) patch.events = { ...patch.events, [k]: on };
+ else if (k === "users" && on != null) patch.digest = { ...patch.digest, users: on };
+ else if (k === "time") patch.digest = { ...patch.digest, time: v };
+ else if (k === "tz") patch.digest = { ...patch.digest, timezone: v };
+ else throw new PeppaError(`unknown setting ${a}: chat=, releases|services|digest|users=on|off, time=HH:MM, tz=`);
+ }
+ }
+ let c = Object.keys(patch).length ? await setPlatformChannel(db, patch) : await getPlatformChannel(db);
+ if (c.chatId != null && (check || patch.chatId !== undefined)) c = await checkPlatformChannel(db);
+ console.log(describeChannel(c));
+ console.log(`события: ${PLATFORM_CHANNEL_EVENTS.map((e) => `${e}=${c.events[e] ? "on" : "off"}`).join(" ")}`);
+ console.log(`дайджест: ${c.digest.time} ${c.digest.timezone}, пользователям ${c.digest.users ? "да" : "нет"}`);
+ break;
+ }
+ case "platform digest": {
+ if (args[0] === "now") {
+ const r = await platformDigestTick(db, { force: true, log: console.log });
+ if (!r) console.log("некуда отправлять: канал не подключён и дайджест пользователям выключен");
+ break;
+ }
+ const { buildPlatformDigest, renderPlatformDigest } = await import("@peppa/core");
+ console.log(renderPlatformDigest(await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) })).replace(/<[^>]+>/g, ""));
+ break;
+ }
case "platform release-offers": {
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f06b1ada..a7c6cda7 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -28,6 +28,7 @@ export * from "./reviews.ts";
export * from "./webpush.ts";
export * from "./notifications.ts";
export * from "./digest.ts";
+export * from "./platform-channel.ts";
export * from "./autonomy.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts
index 1f67aeb3..64f27ad3 100644
--- a/packages/core/src/monitor.ts
+++ b/packages/core/src/monitor.ts
@@ -1,6 +1,7 @@
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
// watchdog and the bot check each other (and the web) and alert the platform admins in
// Telegram through the outbox when a service goes quiet, without spamming.
+import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { hostname } from "node:os";
import { dirname, join } from "node:path";
@@ -9,6 +10,7 @@ import { telegramOutbox, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm";
import { allowedLogins } from "./access.ts";
import { deliverToUser } from "./notifications.ts";
+import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import type { User } from "./users.ts";
@@ -23,6 +25,8 @@ export interface Heartbeat {
pid: number;
host: string;
version: string;
+ /** Commit the process runs (PEP-60); absent in heartbeats of older processes. */
+ commit?: string | null;
}
export interface ServiceState {
@@ -38,6 +42,8 @@ interface AlertState {
alerted: boolean;
reminders: number;
lastAlertAt: string | null;
+ /** PEP-60: the outage was posted to the platform channel (then its recovery is too). */
+ channelPosted?: boolean;
}
export interface MonitorOptions {
@@ -60,14 +66,33 @@ const startedAt = new Date().toISOString();
export const defaultStaleMs = () => Number(process.env.PEPPA_MONITOR_STALE_MIN ?? 5) * MIN;
/** Peppa version from the root package.json (bot, watchdog, CLI run from the checkout). */
-export function peppaVersion(): string {
+export function peppaVersion(root = join(dirname(fileURLToPath(import.meta.url)), "../../..")): string {
try {
- return (JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../../package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
+ return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
} catch {
return "0.0.0";
}
}
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+
+/** HEAD of Peppa's checkout right now (null outside git). */
+export function headCommit(root = ROOT): string | null {
+ try {
+ return execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+let processCommit: string | null | undefined;
+
+/** Commit this process runs: PEPPA_COMMIT, the web's build-time commit, or HEAD at first call. */
+export function peppaCommit(): string | null {
+ if (processCommit === undefined) processCommit = process.env.PEPPA_COMMIT || process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL || headCommit();
+ return processCommit;
+}
+
/** "I'm alive": called every 30–60 s by each service. */
export async function beat(db: Db, service: Service, o: { now?: Date; version?: string } = {}): Promise {
const hb: Heartbeat = {
@@ -76,6 +101,7 @@ export async function beat(db: Db, service: Service, o: { now?: Date; version?:
pid: process.pid,
host: hostname(),
version: o.version ?? peppaVersion(),
+ commit: peppaCommit(),
};
await setSetting(db, hbKey(service), hb);
}
@@ -162,23 +188,39 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
const cooldownMs = o.cooldownMs ?? 15 * MIN;
const log = o.log ?? (() => {});
let queued = 0;
+ const channel = await getPlatformChannel(db);
for (const s of await serviceStatus(db, { now, staleMs: o.staleMs })) {
if (s.service === o.self || !s.heartbeat) continue;
const name = SERVICE_NAMES[s.service];
const st = await getSetting(db, alertKey(s.service));
if (s.ok) {
- if (!st?.since) continue;
+ const restarted = await noteProcess(db, s.service, s.heartbeat);
+ if (!st?.since) {
+ // PEP-60: a new process without an outage = a restart (an outage ends with «снова на связи»).
+ if (restarted) {
+ const build = `v${s.heartbeat.version}${s.heartbeat.commit ? ` · ${s.heartbeat.commit.slice(0, 7)}` : ""}`;
+ await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, `🔄 Пеппа: ${name} перезапущен (${build}).`, channel);
+ }
+ continue;
+ }
// lastAlertAt survives the recovery: it is what the cooldown against flapping counts from.
await setSetting(db, alertKey(s.service), { since: null, alerted: false, reminders: 0, lastAlertAt: st.lastAlertAt });
+ const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
if (st.alerted) {
- const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова на связи (молчал ${quiet} мин).`, log);
}
+ if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова работает — простой ${quiet} мин.`, channel))) queued++;
continue;
}
// Down. A new outage starts when the last heartbeat differs from the remembered one.
const cur: AlertState =
st?.since === s.heartbeat.at ? st : { since: s.heartbeat.at, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null };
+ // PEP-60: the channel hears about an outage once (no reminders, no cooldown games).
+ if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, `⚠️ Пеппа: ${name} не отвечает с ${hhmm(s.heartbeat.at)}.`, channel))) {
+ cur.channelPosted = true;
+ queued++;
+ if (cur === st) await setSetting(db, alertKey(s.service), cur);
+ }
const sinceLast = cur.lastAlertAt ? now.getTime() - Date.parse(cur.lastAlertAt) : Infinity;
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
if (due) {
@@ -192,6 +234,16 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
return queued;
}
+/** Remembers the service's process; true when it differs from a previously seen one. */
+async function noteProcess(db: Db, service: Service, hb: Heartbeat): Promise {
+ const key = `monitor.process:${service}`;
+ const id = `${hb.host}:${hb.pid}:${hb.startedAt}`;
+ const prev = await getSetting(db, key);
+ if (prev === id) return false;
+ await setSetting(db, key, id);
+ return prev != null;
+}
+
/** Monitor messages not delivered yet (the watchdog sends them itself when the bot is down). */
export async function pendingMonitorMessages(db: Db) {
return db
diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts
index 9774da6a..7812860a 100644
--- a/packages/core/src/notifications.ts
+++ b/packages/core/src/notifications.ts
@@ -8,7 +8,7 @@ import type { Question } from "./tasks.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
-export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
+export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest", "platform"] as const;
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
export const NOTIFY_EVENT_NAMES: Record = {
@@ -19,6 +19,7 @@ export const NOTIFY_EVENT_NAMES: Record = {
incidents: "Ошибки из прода",
monitoring: "Мониторинг Пеппы (админам)",
digest: "Ежедневный дайджест",
+ platform: "Дайджест обновлений Пеппы",
};
export interface Channels {
@@ -47,7 +48,7 @@ export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat(
export function defaultPrefs(): NotifyPrefs {
const on = { telegram: true, push: true };
return {
- events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false } },
+ events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } },
quiet: null,
timezone: serverTimezone(),
digestTime: "09:00",
diff --git a/packages/core/src/platform-channel.ts b/packages/core/src/platform-channel.ts
new file mode 100644
index 00000000..4624305a
--- /dev/null
+++ b/packages/core/src/platform-channel.ts
@@ -0,0 +1,371 @@
+// Platform channel and Peppa's own digest (PEP-60): a Telegram channel set by a superadmin
+// gets platform events (releases, service outages, restarts) and the daily platform digest;
+// paired users get the platform digest too (notification event «platform»). No migrations:
+// everything lives in `settings`; messages go through the Telegram outbox with retries.
+import { projects, questions, sessions, tasks, users, type Db } from "@peppa/db";
+import { formatTaskKey, loadEnv } from "@peppa/shared";
+import { and, asc, eq, gte, isNotNull, isNull, notInArray } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+import { deliverToUser, hhmmToMinutes, isValidTimezone, localClock, serverTimezone } from "./notifications.ts";
+import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
+import { getSetting, setSetting } from "./settings.ts";
+import { enqueueTelegram } from "./telegram.ts";
+import { describeAccount, listAccountUsage } from "./usage.ts";
+
+export const PLATFORM_CHANNEL_EVENTS = ["releases", "services", "digest"] as const;
+export type PlatformChannelEvent = (typeof PLATFORM_CHANNEL_EVENTS)[number];
+
+export const PLATFORM_CHANNEL_EVENT_NAMES: Record = {
+ releases: "Новые версии Пеппы",
+ services: "Падение, восстановление и перезапуск сервисов",
+ digest: "Ежедневный дайджест",
+};
+
+export interface ChannelCheck {
+ ok: boolean;
+ /** Human-readable reason when not ok. */
+ error: string | null;
+ at: string;
+}
+
+export interface PlatformChannel {
+ /** Telegram Chat ID of the channel («-100…» or «@name»); null = no channel. */
+ chatId: number | string | null;
+ /** Channel title from the last good check. */
+ title: string | null;
+ check: ChannelCheck | null;
+ events: Record;
+ digest: { time: string; timezone: string; users: boolean };
+ setAt?: string;
+}
+
+const KEY = "platform.telegram_channel";
+const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
+
+export function defaultPlatformChannel(): PlatformChannel {
+ return {
+ chatId: null,
+ title: null,
+ check: null,
+ events: { releases: true, services: true, digest: true },
+ digest: { time: "09:00", timezone: serverTimezone(), users: false },
+ };
+}
+
+/** Saved channel settings merged over the defaults. */
+export async function getPlatformChannel(db: Db): Promise {
+ const d = defaultPlatformChannel();
+ const s = (await getSetting>(db, KEY)) ?? {};
+ const events = { ...d.events };
+ for (const e of PLATFORM_CHANNEL_EVENTS) if (typeof s.events?.[e] === "boolean") events[e] = s.events[e];
+ return {
+ chatId: s.chatId ?? null,
+ title: s.title ?? null,
+ check: s.check ?? null,
+ events,
+ digest: {
+ time: s.digest?.time && HHMM.test(s.digest.time) ? s.digest.time : d.digest.time,
+ timezone: s.digest?.timezone && isValidTimezone(s.digest.timezone) ? s.digest.timezone : d.digest.timezone,
+ users: s.digest?.users ?? d.digest.users,
+ },
+ ...(s.setAt ? { setAt: s.setAt } : {}),
+ };
+}
+
+/** «-1004371018094» → number, «@name» stays a string; anything else is refused. */
+export function parseChatId(raw: string): number | string {
+ const s = raw.trim();
+ if (/^-?\d{5,20}$/.test(s)) return Number(s);
+ if (/^@[A-Za-z][A-Za-z0-9_]{3,}$/.test(s)) return s;
+ throw new PeppaError("Chat ID канала — число вида -100… или @имя_канала");
+}
+
+export interface PlatformChannelPatch {
+ chatId?: number | string | null;
+ events?: Partial>;
+ digest?: Partial;
+}
+
+/** Changes the settings; a new Chat ID drops the previous check result. */
+export async function setPlatformChannel(db: Db, patch: PlatformChannelPatch): Promise {
+ const cur = await getPlatformChannel(db);
+ const next: PlatformChannel = { ...cur, events: { ...cur.events, ...patch.events }, digest: { ...cur.digest, ...patch.digest } };
+ if (!HHMM.test(next.digest.time)) throw new PeppaError("Время дайджеста: формат ЧЧ:ММ");
+ if (!isValidTimezone(next.digest.timezone)) throw new PeppaError(`Неизвестная таймзона: ${next.digest.timezone}`);
+ if (patch.chatId !== undefined && String(patch.chatId) !== String(cur.chatId)) {
+ Object.assign(next, { chatId: patch.chatId, title: null, check: null, setAt: new Date().toISOString() });
+ }
+ await setSetting(db, KEY, next);
+ return next;
+}
+
+// ── check ──────────────────────────────────────────────────────────────────────────
+
+export interface BotApiAccess {
+ token?: string;
+ apiUrl?: string;
+}
+
+export const CHANNEL_NOT_VISIBLE = "бот не видит канал — добавьте его администратором";
+export const CHANNEL_NO_POST = "бот не может публиковать — дайте ему право «Публикация сообщений»";
+
+type ApiResult = { ok: true; result: T } | { ok: false; error_code?: number; description?: string };
+
+async function botApi(tg: BotApiAccess, method: string, params: Record): Promise> {
+ const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;
+ if (!token) return { ok: false, description: "TELEGRAM_BOT_TOKEN не задан" };
+ const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org";
+ try {
+ const res = await fetch(`${base}/bot${token}/${method}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(params),
+ signal: AbortSignal.timeout(15_000),
+ });
+ return (await res.json()) as ApiResult;
+ } catch (e) {
+ return { ok: false, description: (e as Error).message };
+ }
+}
+
+/**
+ * Whether the bot can post to the channel: getMe → getChat → getChatMember. Saves the result
+ * (and the channel title) into the settings and returns them.
+ */
+export async function checkPlatformChannel(db: Db, tg: BotApiAccess = {}, o: { now?: Date } = {}): Promise {
+ const cur = await getPlatformChannel(db);
+ if (cur.chatId == null) throw new PeppaError("Канал платформы не задан");
+ const at = (o.now ?? new Date()).toISOString();
+ const verdict = async (): Promise<{ ok: boolean; error: string | null; title: string | null }> => {
+ const me = await botApi<{ id: number }>(tg, "getMe", {});
+ if (!me.ok) return { ok: false, error: `Telegram: ${me.description ?? "нет ответа"}`, title: null };
+ const chat = await botApi<{ title?: string; type: string }>(tg, "getChat", { chat_id: cur.chatId });
+ if (!chat.ok) {
+ const gone = chat.error_code === 400 || chat.error_code === 403 || /chat not found|not a member|kicked/i.test(chat.description ?? "");
+ return { ok: false, error: gone ? CHANNEL_NOT_VISIBLE : `Telegram: ${chat.description ?? "нет ответа"}`, title: null };
+ }
+ const title = chat.result.title ?? null;
+ const member = await botApi<{ status: string; can_post_messages?: boolean }>(tg, "getChatMember", { chat_id: cur.chatId, user_id: me.result.id });
+ if (!member.ok) return { ok: false, error: `Telegram: ${member.description ?? "нет ответа"}`, title };
+ const m = member.result;
+ const canPost = chat.result.type === "channel" ? m.status === "creator" || (m.status === "administrator" && m.can_post_messages !== false) : m.status !== "left" && m.status !== "kicked";
+ return canPost ? { ok: true, error: null, title } : { ok: false, error: m.status === "left" || m.status === "kicked" ? CHANNEL_NOT_VISIBLE : CHANNEL_NO_POST, title };
+ };
+ const v = await verdict();
+ const next: PlatformChannel = { ...cur, title: v.title ?? cur.title, check: { ok: v.ok, error: v.error, at } };
+ await setSetting(db, KEY, next);
+ return next;
+}
+
+/** «канал подключён — Peppa News» / the reason / «не проверен». */
+export function describeChannel(c: PlatformChannel): string {
+ if (c.chatId == null) return "канал не задан";
+ if (!c.check) return `${c.chatId}: не проверен`;
+ return c.check.ok ? `канал подключён${c.title ? ` — ${c.title}` : ""}` : `${c.chatId}: ${c.check.error}`;
+}
+
+/** Watchdog: re-checks a channel that isn't working yet at most once an hour. */
+export async function recheckPlatformChannel(db: Db, o: { now?: Date; tg?: BotApiAccess; log?: (m: string) => void } = {}): Promise {
+ const c = await getPlatformChannel(db);
+ const now = o.now ?? new Date();
+ if (c.chatId == null || c.check?.ok) return false;
+ if (c.check && now.getTime() - Date.parse(c.check.at) < 3600_000) return false;
+ const r = await checkPlatformChannel(db, o.tg, { now });
+ if (r.check?.ok) o.log?.(`platform channel: ${describeChannel(r)}`);
+ return true;
+}
+
+// ── posting ────────────────────────────────────────────────────────────────────────
+
+const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">");
+
+/**
+ * Queues a message to the platform channel if it is connected and the event is on. Service
+ * events use `mon:` keys so the watchdog delivers them itself when the bot is down.
+ */
+export async function postToChannel(db: Db, event: PlatformChannelEvent, dedupeKey: string, html: string, channel?: PlatformChannel): Promise {
+ const c = channel ?? (await getPlatformChannel(db));
+ if (c.chatId == null || !c.check?.ok || !c.events[event]) return false;
+ return enqueueTelegram(db, {
+ dedupeKey,
+ method: "sendMessage",
+ params: { chat_id: c.chatId, text: html, parse_mode: "HTML", link_preview_options: { is_disabled: true } },
+ });
+}
+
+// ── builds and releases ────────────────────────────────────────────────────────────
+
+/** Key of the project that is Peppa itself. */
+export const platformProjectKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP";
+
+export interface PlatformBuild {
+ version: string;
+ commit: string;
+ at: string;
+ /** Platform stories found in the commits since the previous build. */
+ tasks: string[];
+}
+
+const BUILD = "platform.build";
+const BUILDS = "platform.builds";
+
+export const getPlatformBuild = (db: Db) => getSetting(db, BUILD);
+
+/** Announced builds, newest last (the digest lists the ones since its previous run). */
+export async function recentPlatformBuilds(db: Db): Promise {
+ return (await getSetting(db, BUILDS)) ?? [];
+}
+
+const short = (sha: string) => sha.slice(0, 7);
+
+/** Titles of the platform's stories by key (missing ones are left out). */
+async function storyTitles(db: Db, keys: string[]): Promise> {
+ const pk = platformProjectKey();
+ const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk));
+ const out = new Map();
+ if (!p || !keys.length) return out;
+ const rows = await db.select({ number: tasks.number, title: tasks.title }).from(tasks).where(eq(tasks.projectId, p.id));
+ for (const r of rows) out.set(formatTaskKey(pk, r.number), r.title);
+ return out;
+}
+
+function storyLine(webUrl: string, key: string, title: string | undefined): string {
+ return ` • ${esc(key)} ${title ? ` ${esc(title.length > 70 ? `${title.slice(0, 70)}…` : title)}` : ""}`;
+}
+
+/**
+ * A new build of Peppa is live (watchdog, runner/platform-build.ts). The first one is only
+ * remembered; later ones are posted to the channel: «🚀 Peppa v0.16.0 · b1c2d3e» + stories.
+ */
+export async function announcePlatformBuild(db: Db, b: Omit, o: { now?: Date } = {}): Promise {
+ const prev = await getPlatformBuild(db);
+ if (prev?.commit === b.commit) return false;
+ const build: PlatformBuild = { ...b, at: (o.now ?? new Date()).toISOString() };
+ await setSetting(db, BUILD, build);
+ if (!prev) return false;
+ await setSetting(db, BUILDS, [...(await recentPlatformBuilds(db)), build].slice(-20));
+ return postToChannel(db, "releases", `pch:release:${b.commit}`, renderBuild(build, await storyTitles(db, build.tasks)));
+}
+
+export function renderBuild(b: PlatformBuild, titles: Map = new Map()): string {
+ const webUrl = loadEnv().PEPPA_WEB_URL;
+ const lines = [`🚀 Peppa v${esc(b.version)} · ${esc(short(b.commit))} `];
+ if (b.tasks.length) lines.push(`Стори: ${b.tasks.map(esc).join(", ")}`, ...b.tasks.slice(0, 15).map((k) => storyLine(webUrl, k, titles.get(k))));
+ return lines.join("\n");
+}
+
+// ── platform digest ────────────────────────────────────────────────────────────────
+
+export interface PlatformDigest {
+ since: Date;
+ build: PlatformBuild | null;
+ /** Builds announced since the previous digest. */
+ builds: PlatformBuild[];
+ /** Platform stories finished since the previous digest. */
+ done: { key: string; title: string }[];
+ services: { name: string; ok: boolean; state: string }[];
+ runners: number;
+ questions: number;
+ rateLimited: number;
+ limits: string[];
+}
+
+/** Changes of Peppa since `since` and the current state of the platform. */
+export async function buildPlatformDigest(db: Db, o: { since: Date; now?: Date }): Promise {
+ const now = o.now ?? new Date();
+ const { serviceStatus, describeState, SERVICE_NAMES } = await import("./monitor.ts");
+ const pk = platformProjectKey();
+ const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk));
+ const done = p
+ ? (
+ await db
+ .select({ number: tasks.number, title: tasks.title })
+ .from(tasks)
+ .where(and(eq(tasks.projectId, p.id), eq(tasks.status, "done"), gte(tasks.updatedAt, o.since)))
+ .orderBy(asc(tasks.number))
+ ).map((t) => ({ key: formatTaskKey(pk, t.number), title: t.title }))
+ : [];
+ const live = await db.select({ status: sessions.status }).from(sessions).where(notInArray(sessions.status, FINISHED_SESSION_STATUSES));
+ const open = await db.select({ id: questions.id }).from(questions).where(isNull(questions.answeredAt));
+ const services = (await serviceStatus(db, { now })).filter((s) => s.heartbeat).map((s) => ({ name: SERVICE_NAMES[s.service], ok: s.ok, state: describeState(s) }));
+ const limits = (await listAccountUsage(db, { now: now.getTime() }))
+ .filter((a) => a.limitedUntil || (a.fiveHour?.pct ?? 0) >= 50 || (a.sevenDay?.pct ?? 0) >= 50)
+ .map(describeAccount);
+ return {
+ since: o.since,
+ build: await getPlatformBuild(db),
+ builds: (await recentPlatformBuilds(db)).filter((b) => Date.parse(b.at) >= o.since.getTime()),
+ done,
+ services,
+ runners: live.length,
+ questions: open.length,
+ rateLimited: live.filter((s) => s.status === "rate_limited").length,
+ limits,
+ };
+}
+
+/** Nothing new and nothing going on: the digest isn't sent. */
+export const platformDigestEmpty = (d: PlatformDigest) => !d.done.length && !d.builds.length && !d.runners && !d.questions && d.services.every((s) => s.ok);
+
+export function renderPlatformDigest(d: PlatformDigest): string {
+ const webUrl = loadEnv().PEPPA_WEB_URL;
+ const lines = ["🐷 Дайджест Пеппы "];
+ if (d.done.length || d.builds.length) {
+ lines.push("", "Что нового ");
+ for (const b of d.builds) lines.push(`🚀 v${esc(b.version)} · ${esc(short(b.commit))}`);
+ if (d.done.length) lines.push(`✅ Сделано: ${d.done.map((t) => esc(t.key)).join(", ")}`, ...d.done.slice(0, 12).map((t) => storyLine(webUrl, t.key, t.title)));
+ if (d.done.length > 12) lines.push(` …и ещё ${d.done.length - 12}`);
+ }
+ lines.push("", "Сейчас ");
+ if (d.build) lines.push(`Версия: v${esc(d.build.version)} · ${esc(short(d.build.commit))}`);
+ if (d.services.length) lines.push(`Сервисы: ${d.services.map((s) => `${s.ok ? "✅" : "⚠️"} ${esc(s.name)}${s.ok ? "" : ` (${esc(s.state)})`}`).join(", ")}`);
+ lines.push(`Раннеров: ${d.runners}${d.rateLimited ? ` (ждут сброса лимита: ${d.rateLimited})` : ""}`, `Вопросов: ${d.questions}`);
+ if (d.limits.length) lines.push(`Лимиты: ${d.limits.map(esc).join("; ")}`);
+ return lines.join("\n");
+}
+
+const LAST = "platform.digest.last";
+const WINDOW_MIN = 180;
+
+/**
+ * Watchdog tick: at the platform's digest time (once a local day) builds the digest over the
+ * time since the previous one and sends it to the channel and, when enabled, to every paired
+ * user who keeps the «platform» notification on. Returns where it went.
+ */
+export async function platformDigestTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise<{ channel: boolean; users: number } | null> {
+ const now = o.now ?? new Date();
+ const c = await getPlatformChannel(db);
+ const clock = localClock(now, c.digest.timezone);
+ const target = hhmmToMinutes(c.digest.time);
+ const last = await getSetting<{ date: string; at: string }>(db, LAST);
+ if (!o.force) {
+ if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) return null;
+ if (last?.date === clock.date) return null;
+ }
+ const toChannel = c.chatId != null && !!c.check?.ok && c.events.digest;
+ if (!toChannel && !c.digest.users) return null;
+ await setSetting(db, LAST, { date: clock.date, at: now.toISOString() });
+ const since = last ? new Date(last.at) : new Date(now.getTime() - 24 * 3600_000);
+ const d = await buildPlatformDigest(db, { since, now });
+ if (platformDigestEmpty(d)) {
+ o.log?.("platform digest: nothing to report");
+ return { channel: false, users: 0 };
+ }
+ const text = renderPlatformDigest(d);
+ const channel = toChannel && (await postToChannel(db, "digest", `pch:digest:${clock.date}`, text, c));
+ let sent = 0;
+ if (c.digest.users) {
+ const paired = (await db.select().from(users).where(isNotNull(users.telegramChatId))).filter((u) => !u.disabledAt);
+ for (const u of paired) {
+ const r = await deliverToUser(db, u, {
+ event: "platform",
+ dedupeKey: `pdigest:${clock.date}:${u.telegramChatId}`,
+ telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
+ now,
+ });
+ if (r.telegram) sent++;
+ }
+ }
+ o.log?.(`platform digest: channel ${channel ? "yes" : "no"}, users ${sent}`);
+ return { channel, users: sent };
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d8956b45..823093b6 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -17,6 +17,7 @@ export * from "./triage.ts";
export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./platform-release.ts";
+export * from "./platform-build.ts";
export * from "./code.ts";
export * from "./agents-md.ts";
export * from "./terminal.ts";
diff --git a/packages/runner/src/platform-build.ts b/packages/runner/src/platform-build.ts
new file mode 100644
index 00000000..c77b1aec
--- /dev/null
+++ b/packages/runner/src/platform-build.ts
@@ -0,0 +1,57 @@
+// New builds of Peppa (PEP-60). The watchdog looks at HEAD of Peppa's checkout about once a
+// minute; a commit that differs from the last announced one and belongs to `main` is a
+// release: posted to the platform channel with the stories from the commit messages. Works
+// now (dev from the working copy: a story branch isn't announced, returning to an updated
+// main is) and in prod (PEP-18: ~/peppa/current is a worktree of a `main` commit).
+import { execFileSync } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { announcePlatformBuild, getPlatformBuild, headCommit, peppaVersion, platformProjectKey } from "@peppa/core";
+import type { Db } from "@peppa/db";
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+
+const git = (root: string, args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+
+/** True when `commit` is reachable from the branch (default `main`). */
+export function onMainBranch(root: string, commit: string, branch = process.env.PEPPA_MAIN_BRANCH || "main"): boolean {
+ try {
+ git(root, ["merge-base", "--is-ancestor", commit, branch]);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Platform stories mentioned in the commits `prev..commit` (all of HEAD's history is too much: none then). */
+export function storiesBetween(root: string, prev: string | null, commit: string, key = platformProjectKey()): string[] {
+ if (!prev) return [];
+ let log = "";
+ try {
+ log = git(root, ["log", "--format=%s%n%b", `${prev}..${commit}`]);
+ } catch {
+ return [];
+ }
+ const re = new RegExp(`\\b${key}-(\\d+)\\b`, "gi");
+ const nums = new Set();
+ for (const m of log.matchAll(re)) nums.add(Number(m[1]));
+ return [...nums].sort((a, b) => a - b).map((n) => `${key}-${n}`);
+}
+
+let lastCheck = 0;
+
+/** Watchdog: announces a new build of Peppa once (first run only remembers it). */
+export async function platformBuildTick(db: Db, o: { root?: string; now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise {
+ const nowMs = (o.now ?? new Date()).getTime();
+ if (!o.force && Math.abs(nowMs - lastCheck) < 60_000) return false;
+ lastCheck = nowMs;
+ const root = o.root ?? process.env.PEPPA_ROOT ?? ROOT;
+ const commit = headCommit(root);
+ if (!commit) return false;
+ const prev = await getPlatformBuild(db);
+ if (prev?.commit === commit || !onMainBranch(root, commit)) return false;
+ const tasks = storiesBetween(root, prev?.commit ?? null, commit);
+ const posted = await announcePlatformBuild(db, { version: peppaVersion(root), commit, tasks }, { now: o.now });
+ o.log?.(`platform build ${commit.slice(0, 7)}${tasks.length ? ` (${tasks.join(", ")})` : ""}${posted ? " → channel" : ""}`);
+ return posted;
+}
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 3175e7a0..acc5b321 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
+ platformDigestTick,
+ recheckPlatformChannel,
getBudgetState,
runAsActor,
expireSessionQuestions,
@@ -23,6 +25,7 @@ import { hostTick } from "./hosts.ts";
import { getSubscription, isUsable } from "@peppa/core";
import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
import { monitorTick } from "./monitor.ts";
+import { platformBuildTick } from "./platform-build.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
@@ -83,6 +86,11 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise {
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
// Daily digest at each user's time (PEP-29); a no-op outside their window.
await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`));
+ // PEP-60: platform channel — re-check a channel that isn't working yet, new builds, the
+ // platform digest at its time.
+ await recheckPlatformChannel(db, { now: opts.now, log }).catch((e) => log(`platform channel: ${(e as Error).message}`));
+ await platformBuildTick(db, { now: opts.now, log }).catch((e) => log(`platform build: ${(e as Error).message}`));
+ await platformDigestTick(db, { now: opts.now, log }).catch((e) => log(`platform digest: ${(e as Error).message}`));
}
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 9b177f04..4bace09c 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -32,8 +32,15 @@ export class MockTelegram {
private server: Server | null = null;
/** PEP-45: uploaded voice files by file_id (served at /file/bot/). */
private files = new Map();
+ /** PEP-60: channels by chat id; the bot's membership decides what getChat/sendMessage do. */
+ readonly channels = new Map();
url = "";
+ /** A channel; by default the bot is its admin with the right to post. */
+ addChannel(chatId: number, title: string, o: { bot?: "administrator" | "member" | "left"; canPost?: boolean } = {}) {
+ this.channels.set(chatId, { title, bot: o.bot ?? "administrator", canPost: o.canPost ?? true });
+ }
+
async start(port = 0): Promise {
this.server = createServer((req, res) => {
let body = "";
@@ -94,7 +101,24 @@ export class MockTelegram {
}
return { ok: true, result: pending() };
}
+ case "getChat": {
+ const c = this.channels.get(Number(p.chat_id));
+ if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ return { ok: true, result: { id: Number(p.chat_id), type: "channel", title: c.title } };
+ }
+ case "getChatMember": {
+ const c = this.channels.get(Number(p.chat_id));
+ if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (Number(p.user_id) !== this.bot.id) return { ok: false, error_code: 400, description: "Bad Request: user not found" };
+ return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
+ }
case "sendMessage": {
+ // Channels (-100…): the bot must be an admin that may post.
+ if (String(p.chat_id).startsWith("-100")) {
+ const c = this.channels.get(Number(p.chat_id));
+ if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (c.bot !== "administrator" || !c.canPost) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
+ }
const m: MockTgMessage = {
message_id: this.nextMessageId++,
chat_id: Number(p.chat_id),
diff --git a/packages/testkit/test/platform-channel.test.ts b/packages/testkit/test/platform-channel.test.ts
new file mode 100644
index 00000000..716b6cdf
--- /dev/null
+++ b/packages/testkit/test/platform-channel.test.ts
@@ -0,0 +1,309 @@
+// PEP-60, spec platform-notifications: the platform channel (check through the Bot API),
+// platform events (new build, outage/recovery, restart) and the platform digest to the
+// channel and to users — mock-telegram as the Bot API, the real bot delivers the outbox,
+// a temp git repo as Peppa's checkout for builds.
+import assert from "node:assert/strict";
+import { execFile, execFileSync } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, before, beforeEach, describe, test } from "node:test";
+// helpers must load first: it sets the isolated test env that runner modules read on load.
+import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
+import { MockTelegram } from "../src/mock-telegram.ts";
+import { questions, sessions, tasks, telegramOutbox, users } from "@peppa/db";
+import { eq, like, sql } from "drizzle-orm";
+
+const { createBot } = await import("@peppa/bot");
+const { TelegramApi } = await import("@peppa/bot/telegram");
+
+const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
+const MIN = 60_000;
+const CHANNEL = -1004371018094;
+const tg = await new MockTelegram().start();
+const TG = { token: tg.token, apiUrl: tg.url };
+process.env.TELEGRAM_BOT_TOKEN = tg.token;
+process.env.TELEGRAM_API_URL = tg.url;
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+process.env.PEPPA_TZ = "UTC";
+
+const ANNA = { login: "mock-anna", chatId: 9301 };
+const BEK = { login: "mock-bek", chatId: 9302 };
+let pep: Awaited>;
+let pepId = 0;
+
+async function pair(login: string, chatId: number, giteaId: number) {
+ const u = await core.upsertUserFromGitea(db, { id: giteaId, login }, { access_token: "x" });
+ await db.update(users).set({ telegramChatId: chatId, telegramUserId: chatId }).where(eq(users.id, u.id));
+ return u;
+}
+
+/** Texts queued for a chat, oldest first. */
+async function queued(chatId: number, keyLike = "%"): Promise {
+ const rows = await db
+ .select()
+ .from(telegramOutbox)
+ .where(sql`${telegramOutbox.dedupeKey} like ${keyLike} and cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`)
+ .orderBy(telegramOutbox.id);
+ return rows.map((r) => String(r.params.text));
+}
+
+async function connectChannel() {
+ tg.addChannel(CHANNEL, "Peppa News");
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ return core.checkPlatformChannel(db, TG);
+}
+
+before(async () => {
+ pep = await project({ steps: [] });
+ process.env.PEPPA_PLATFORM_KEY = pep.key;
+ pepId = (await core.getProject(db, pep.key)).id;
+ await pair(ANNA.login, ANNA.chatId, 9401);
+ await pair(BEK.login, BEK.chatId, 9402);
+});
+beforeEach(async () => {
+ db.run(sql`delete from settings where key like 'platform.%' or key like 'heartbeat:%' or key like 'monitor.%' or key like 'notify.prefs:%'`);
+ await db.delete(telegramOutbox);
+ await db.delete(sessions);
+ tg.channels.clear();
+});
+after(async () => {
+ await tg.stop();
+ await teardown();
+});
+
+describe("Канал платформы", () => {
+ test("Бот — админ канала", async () => {
+ const c = await connectChannel();
+ assert.equal(c.check?.ok, true);
+ assert.equal(core.describeChannel(c), "канал подключён — Peppa News");
+ assert.equal((await core.getPlatformChannel(db)).title, "Peppa News");
+ });
+
+ test("Бот не добавлен в канал", async () => {
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ const c = await core.checkPlatformChannel(db, TG);
+ assert.equal(c.check?.ok, false);
+ assert.equal(c.check?.error, "бот не видит канал — добавьте его администратором");
+ // Not posting while the channel doesn't work.
+ assert.equal(await core.postToChannel(db, "releases", "pch:test", "x"), false);
+ });
+
+ test("Бот в канале без права публикации", async () => {
+ tg.addChannel(CHANNEL, "Peppa News", { canPost: false });
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ const c = await core.checkPlatformChannel(db, TG);
+ assert.equal(c.check?.error, core.CHANNEL_NO_POST);
+ });
+
+ test("Пеппа перепроверяет неработающий канал раз в час и включает его", async () => {
+ await core.setPlatformChannel(db, { chatId: CHANNEL });
+ const t0 = new Date("2026-03-01T10:00:00Z");
+ assert.equal(await core.recheckPlatformChannel(db, { now: t0, tg: TG }), true);
+ assert.equal((await core.getPlatformChannel(db)).check?.ok, false);
+ tg.addChannel(CHANNEL, "Peppa News");
+ assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 30 * MIN), tg: TG }), false, "не раньше часа");
+ assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 61 * MIN), tg: TG }), true);
+ assert.equal((await core.getPlatformChannel(db)).check?.ok, true);
+ });
+
+ test("Неверный Chat ID и сброс проверки при смене канала", async () => {
+ assert.throws(() => core.parseChatId("канал"), /Chat ID/);
+ assert.equal(core.parseChatId("@peppa_news"), "@peppa_news");
+ await connectChannel();
+ const c = await core.setPlatformChannel(db, { chatId: -1009999999999 });
+ assert.equal(c.check, null);
+ });
+
+ test("Не суперадмин", async () => {
+ await core.setPlatformAdmins(db, [ANNA.login]);
+ await assert.rejects(core.requireSuperadmin(db, { login: BEK.login }));
+ await core.requireSuperadmin(db, { login: ANNA.login });
+ });
+
+ test("CLI: peppa platform channel", async () => {
+ tg.addChannel(CHANNEL, "Peppa News");
+ // Async: the mock Bot API lives in this process.
+ const { stdout: out } = await promisify(execFile)(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), "platform", "channel", `chat=${CHANNEL}`, "services=off", "time=08:30"], { encoding: "utf8", env: process.env });
+ assert.match(out, /канал подключён — Peppa News/);
+ assert.match(out, /services=off/);
+ assert.match(out, /дайджест: 08:30/);
+ });
+});
+
+describe("События платформы в канал", () => {
+ test("Новый релиз", async () => {
+ await connectChannel();
+ await db.insert(tasks).values([
+ { projectId: pepId, number: 59, title: "Версия и коммит в футере веба" },
+ { projectId: pepId, number: 61, title: "Меню сверху" },
+ ]);
+ const k = (n: number) => `${pep.key}-${n}`;
+ assert.equal(await core.announcePlatformBuild(db, { version: "0.15.0", commit: "aa8796a".padEnd(40, "0"), tasks: [] }), false, "первая сборка только запоминается");
+ assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [k(59), k(61)] }), true);
+ const [msg] = await queued(CHANNEL);
+ assert.match(msg!, /Peppa v0\.16\.0 · b1c2d3e/);
+ assert.match(msg!, new RegExp(`Стори: ${k(59)}, ${k(61)}`));
+ assert.match(msg!, /Версия и коммит в футере веба/);
+ // The same commit again — nothing new.
+ assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [] }), false);
+ assert.equal((await queued(CHANNEL)).length, 1);
+ });
+
+ test("Сборка из ветки стори не объявляется, из main — со стори из коммитов", async () => {
+ await connectChannel();
+ const repo = mkdtempSync(join(tmpdir(), "peppa-build-"));
+ const git = (...a: string[]) => execFileSync("git", ["-C", repo, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim();
+ git("init", "-q", "-b", "main");
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.15.0" }));
+ git("add", "-A");
+ git("commit", "-qm", "base");
+ const now = new Date("2026-03-02T10:00:00Z");
+ await runner.platformBuildTick(db, { root: repo, force: true, now });
+ assert.equal((await core.getPlatformBuild(db))?.version, "0.15.0");
+ // A story branch checked out: not a release.
+ git("checkout", "-qb", `task/${pep.key.toLowerCase()}-70`);
+ mkdirSync(join(repo, "src"));
+ writeFileSync(join(repo, "src/a.txt"), "a");
+ git("add", "-A");
+ git("commit", "-qm", `${pep.key}-70: work in progress`);
+ assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), false);
+ // Merged into main with a version bump: announced with the stories of the merged commits.
+ git("checkout", "-q", "main");
+ git("merge", "-q", "--no-ff", "-m", `Merge pull request '${pep.key}-70: канал' (#9) from task/${pep.key.toLowerCase()}-70 into main`, `task/${pep.key.toLowerCase()}-70`);
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.16.0" }));
+ git("commit", "-qam", `${pep.key}-72: bump`);
+ assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), true);
+ const [msg] = await queued(CHANNEL);
+ assert.match(msg!, new RegExp(`Peppa v0\\.16\\.0 · ${git("rev-parse", "--short=7", "HEAD")}`));
+ assert.match(msg!, new RegExp(`Стори: ${pep.key}-70, ${pep.key}-72`));
+ });
+
+ test("Сервис упал и поднялся", async () => {
+ await connectChannel();
+ const T0 = Date.parse("2026-03-03T12:00:00Z");
+ const at = (m: number) => new Date(T0 + m * MIN);
+ const staleMs = 2 * MIN;
+ await core.beat(db, "bot", { now: at(0) });
+ for (const m of [1, 3, 4, 10]) {
+ await core.checkServices(db, { self: "watchdog", now: at(m), staleMs });
+ await core.checkServices(db, { self: "web", now: at(m), staleMs });
+ }
+ await core.beat(db, "bot", { now: at(12) });
+ await core.checkServices(db, { self: "watchdog", now: at(12), staleMs });
+ await core.checkServices(db, { self: "web", now: at(12.5), staleMs });
+ const msgs = await queued(CHANNEL, "mon:ch:%");
+ assert.equal(msgs.length, 2, msgs.join("\n"));
+ assert.match(msgs[0]!, /бот не отвечает с/);
+ assert.match(msgs[1]!, /бот снова работает — простой 12 мин/);
+ });
+
+ test("Перезапуск сервиса без простоя", async () => {
+ await connectChannel();
+ const now = new Date();
+ const hb = (pid: number) => ({ at: now.toISOString(), startedAt: new Date(now.getTime() - pid).toISOString(), pid, host: "mac", version: "0.15.0", commit: "abc1234".padEnd(40, "0") });
+ await core.setSetting(db, "heartbeat:web", hb(100));
+ await core.checkServices(db, { self: "watchdog", now });
+ assert.equal((await queued(CHANNEL)).length, 0, "первый процесс только запоминается");
+ await core.setSetting(db, "heartbeat:web", hb(200));
+ await core.checkServices(db, { self: "watchdog", now });
+ await core.checkServices(db, { self: "bot", now });
+ const msgs = await queued(CHANNEL);
+ assert.deepEqual(msgs, ["🔄 Пеппа: веб перезапущен (v0.15.0 · abc1234)."]);
+ });
+
+ test("Выключенные события сервисов в канал не идут", async () => {
+ await connectChannel();
+ await core.setPlatformChannel(db, { events: { services: false } });
+ const T0 = Date.parse("2026-03-04T12:00:00Z");
+ await core.beat(db, "bot", { now: new Date(T0) });
+ await core.checkServices(db, { self: "watchdog", now: new Date(T0 + 10 * MIN), staleMs: 2 * MIN });
+ assert.equal((await queued(CHANNEL, "mon:ch:%")).length, 0);
+ });
+});
+
+describe("Дайджест", () => {
+ const day = (h: number, d = 5) => new Date(`2026-03-${String(d).padStart(2, "0")}T${String(h).padStart(2, "0")}:05:00Z`);
+
+ async function activity() {
+ // Stories finished after the previous digest, two live runners and one open question.
+ await db.insert(tasks).values([
+ { projectId: pepId, number: 159, title: "Футер с версией", status: "done", updatedAt: day(6) },
+ { projectId: pepId, number: 161, title: "Меню сверху", status: "done", updatedAt: day(7) },
+ ]);
+ await db.insert(sessions).values([
+ { projectId: pepId, tmuxName: "mock-digest-1", status: "running" },
+ { projectId: pepId, tmuxName: "mock-digest-2", status: "idle" },
+ ]);
+ await db.insert(questions).values({ projectId: pepId, kind: "question", text: "Какой цвет?" });
+ }
+
+ async function cleanActivity() {
+ await db.delete(questions);
+ await db.delete(tasks).where(sql`${tasks.number} in (159, 161)`);
+ }
+
+ test("Ежедневный дайджест", async () => {
+ await connectChannel();
+ await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
+ await activity();
+ try {
+ assert.equal(await core.platformDigestTick(db, { now: day(8) }), null, "до времени дайджеста — ничего");
+ const r = await core.platformDigestTick(db, { now: day(9) });
+ assert.deepEqual(r, { channel: true, users: 0 });
+ const [msg] = await queued(CHANNEL, "pch:digest:%");
+ assert.match(msg!, /Что нового<\/b>/);
+ assert.match(msg!, new RegExp(`Сделано: ${pep.key}-159, ${pep.key}-161`));
+ assert.match(msg!, /Сейчас<\/b>/);
+ assert.match(msg!, /Раннеров: 2/);
+ assert.match(msg!, /Вопросов: 1/);
+ assert.equal(await core.platformDigestTick(db, { now: day(10) }), null, "раз в сутки");
+ } finally {
+ await cleanActivity();
+ }
+ });
+
+ test("Нечего сообщить", async () => {
+ await connectChannel();
+ await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
+ const r = await core.platformDigestTick(db, { now: day(9) });
+ assert.deepEqual(r, { channel: false, users: 0 });
+ assert.equal((await queued(CHANNEL)).length, 0);
+ });
+
+ test("Отписка", async () => {
+ await connectChannel();
+ await core.setPlatformChannel(db, { digest: { users: true } });
+ const anna = (await core.getUserByLogin(db, ANNA.login))!;
+ const prefs = await core.getNotifyPrefs(db, anna.id);
+ await core.setNotifyPrefs(db, anna.id, { ...prefs, events: { ...prefs.events, platform: { telegram: false, push: false } } });
+ await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
+ await activity();
+ try {
+ const r = await core.platformDigestTick(db, { now: day(9) });
+ assert.equal(r?.channel, true);
+ assert.equal((await queued(ANNA.chatId, "pdigest:%")).length, 0, "отписавшийся не получает");
+ assert.equal((await queued(BEK.chatId, "pdigest:%")).length, 1);
+ assert.equal((await queued(CHANNEL, "pch:digest:%")).length, 1, "канал получает");
+ } finally {
+ await cleanActivity();
+ }
+ });
+
+ test("Бот доставляет сообщения канала из outbox", async () => {
+ await connectChannel();
+ await core.setPlatformChannel(db, { digest: { users: false } });
+ await core.postToChannel(db, "releases", "pch:release:mock", "🚀 Peppa v9.9.9 · mock000 ");
+ const bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 5000, heartbeatIntervalMs: 60_000 });
+ await bot.start();
+ try {
+ await waitFor("channel message delivered", async () => tg.botMessages(CHANNEL).some((m) => /Peppa v9\.9\.9/.test(m.text)));
+ const [row] = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "pch:release:mock"));
+ assert.equal(row?.status, "sent");
+ } finally {
+ await bot.stop();
+ }
+ });
+});
--
2.45.2
From fbe4336d20ea0e28296c246e7924d3f1e4a85514 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 19:04:21 +0500
Subject: [PATCH 018/439] =?UTF-8?q?PEP-60:=20docs=20=E2=80=94=20AGENTS.md,?=
=?UTF-8?q?=20/help;=20project=20memory?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.peppa/memory.md | 6 ++++++
AGENTS.md | 1 +
apps/web/app/(app)/help/page.tsx | 6 ++++++
3 files changed, 13 insertions(+)
create mode 100644 .peppa/memory.md
diff --git a/.peppa/memory.md b/.peppa/memory.md
new file mode 100644
index 00000000..53b342f6
--- /dev/null
+++ b/.peppa/memory.md
@@ -0,0 +1,6 @@
+# Память проекта
+
+Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.
+
+## Грабли
+- Один файл e2e: `env -u NODE_TEST_CONTEXT node --test --test-reporter=spec test/.test.ts` (внутри сессии Claude без этого вывод бинарный); CLI из теста с моком в том же процессе — только async execFile, execFileSync вешает мок.
diff --git a/AGENTS.md b/AGENTS.md
index 6ba94b29..33a99983 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,6 +43,7 @@
- **Секреты (PEP-54/19)**: секреты проекта — таблица `project_secrets` (имя env, `value_enc` = `encrypt`, кто менял, `last_used_at`), `core/secrets.ts` (`setProjectSecret`/`deleteProjectSecret` через `projectForUser`, имена `^[A-Z][A-Z0-9_]*$` без зарезервированных `PATH`/`PEPPA_*`/`CLAUDE_*`…, `projectSecretEnv`, `projectSecretMasker`); веб «⋯ Настройки проекта → Секреты» (значение только на запись). Раннер (`launch` в runner/sessions.ts) пишет `secrets.env` (0600) в каталог поколения, `launch.sh` его читает и сразу удаляет — значений нет в argv tmux; событие `secrets_issued {names}`. Маскировка `••••` — `TerminalFeed` (`mask`, из `terminalSse`) и `recordStep`. MCP `list_secrets` (агент — проект своей сессии; PM — доступный проект), только имена. Ревизия (core/secrets-audit.ts `secretsAudit`): секреты платформы `PLATFORM_SECRETS` (задан ли, возраст от `settings` `secrets.rotated:`, кто использует, шаги ротации), шифрование по колонкам, MCP-токены по клиентам, подписки, секреты проектов — `/secrets` (суперадмин) и `peppa secrets audit|new-key|reencrypt|rotated|revoke-client|check-gitea|list`. Ротация `PEPPA_SECRET` двумя ключами: `PEPPA_SECRET_PREVIOUS` принимается для `decrypt`/`verify`/хэшей OAuth (`hashTokenCandidates`)/подписей вебхуков, пишется только текущим; `reencryptAll` переводит все `*_enc`. Новые зашифрованные колонки — добавлять в `encryptedColumns` (secrets-audit.ts), иначе ротация их потеряет
- **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. **Ротация (PEP-39)**: лимит (StopFailure/баннер) помечает подписку «лимит до …» (`markSubscriptionLimited`), `recordLimit` при свободной подписке того же провайдера в пуле (`rotationCandidate`: пул проекта, иначе пулы текущей подписки; наименее занятая) ставит `sessions.rotate_reason=limit` вместо пинга PM, вачдог (runner/rotation.ts `tryRotate`/`rotateSession`) убивает tmux и `resumeSession` на новой подписке — Claude/OpenCode тот же разговор, Codex заново (`conversation_id` сбрасывается, история в `CODEX_HOME` аккаунта не переносится); событие `subscription_switched` + сообщение в Telegram (`sendProjectMessage`). Порог: баннер «N% of your … limit» (≥ `PEPPA_ROTATE_THRESHOLD_PCT`, 85) → `rotate_reason=threshold`, Stop-хук не подталкивает, после хода — на подписку без сессий. Свободных нет — ждёт сброса (PEP-56); освободилась раньше — переключит. Предел `PEPPA_ROTATE_MAX_PER_HOUR` (3), выключение `PEPPA_ROTATE=off`. Справедливость: проект с ≥ `PEPPA_POOL_PROJECT_MAX` (2) подписками пула не получает свободную, пока сессия другого проекта ждёт сброса на этом пуле (`poolRestricted`). Мок: `limit.credential` в сценарии — лимит только на входе с этой подстрокой, `{warn: N}` — баннер порога. Провайдер OpenCode (`providers.ts`): `opencode --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — » и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode`
- **Уведомления (PEP-29/35/55)**: события `questions`/`review`/`failures`/`releases`/`incidents`/`monitoring`/`digest` × каналы Telegram/push на пользователя — `notify.prefs:` в `settings` (`getNotifyPrefs` с умолчаниями, всё включено, кроме дайджеста в браузер), тихие часы (Telegram с `disable_notification`, push пропускается), таймзона (по умолчанию сервера или `PEPPA_TZ`), выключенные проекты. Всё идёт через `deliverToUser` (core/notifications.ts): вопросы (бот `reconcile`, категория — `questionEvent`, получатели — `projectAudience`; ключи Telegram `q::` прежние), ошибки из прода, алерты мониторинга. Web Push — свой на `node:crypto` (core/webpush.ts: VAPID в `settings` `push.vapid`, aes128gcm), таблицы `push_subscriptions` + `push_outbox` (разбирает бот вместе с Telegram-outbox, 404/410 удаляют подписку; push только для вопросов моложе 30 мин). Веб: «Настройки → Уведомления», `public/sw.js`, `app/manifest.ts` (PWA), `AttentionBadge` (счётчик в заголовке и значке, звук; `/api/attention`). Дайджест (core/digest.ts): `digestTick` в `tick` вачдога — в выбранное время (окно 3 ч, `digest.last:`), пустой не шлётся; `/digest` в боте. Мок — `mock-push` (testkit: проверяет VAPID и расшифровывает)
+- **Канал платформы и дайджест Пеппы (PEP-60)**: `core/platform-channel.ts`, настройки в `settings` `platform.telegram_channel` (Chat ID, `check` — результат `checkPlatformChannel`: Bot API `getMe`→`getChat`→`getChatMember`, «бот не видит канал — добавьте его администратором» / нет права публикации; события releases/services/digest; `digest.time/timezone/users`, личные чаты по умолчанию выкл). В канал пишет только при `check.ok` (`postToChannel`, outbox; сервисные ключи `mon:ch:*` — вачдог доставит сам, если упал бот); неработающий канал вачдог перепроверяет раз в час (`recheckPlatformChannel`). События: `checkServices` — одно «не отвечает» и одно «снова работает — простой N мин» на простой, «перезапущен» при смене процесса без простоя (`monitor.process:`, heartbeat несёт `commit`); `platformBuildTick` (runner/platform-build.ts) — HEAD корня ≠ `platform.build` и входит в `main` → «🚀 Peppa vX · sha» + стори из коммитов (первый раз только запоминает). `platformDigestTick` (вачдог): «Что нового» (done-стори `PEPPA_PLATFORM_KEY`, сборки) + «Сейчас» (версия, сервисы, раннеры, вопросы, лимиты), пустой не шлётся, в канал и пользователям событием уведомлений `platform`. Веб `/platform` (суперадмин), CLI `peppa platform channel chat= [k=v…]|check`, `peppa platform digest [now]`. Мок — каналы в `mock-telegram` (`addChannel`)
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]`
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)
- Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью)
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 049e478e..fb1bad36 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -227,6 +227,12 @@ export default async function Help() {
при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию
09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит.
+
+ Новости самой Пеппы — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Пеппы» (что нового и
+ что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа».
+ Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест
+ обновлений Пеппы» в Настройках → Уведомления.
+
--
2.45.2
From 3b23bbad2409a82bb8dfe1c6f24b7c0c07c6a1d9 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 19:04:49 +0500
Subject: [PATCH 019/439] PEP-60: test scenario type
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/platform-channel.test.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/testkit/test/platform-channel.test.ts b/packages/testkit/test/platform-channel.test.ts
index 716b6cdf..42a66e22 100644
--- a/packages/testkit/test/platform-channel.test.ts
+++ b/packages/testkit/test/platform-channel.test.ts
@@ -57,7 +57,7 @@ async function connectChannel() {
}
before(async () => {
- pep = await project({ steps: [] });
+ pep = await project({ turns: [] });
process.env.PEPPA_PLATFORM_KEY = pep.key;
pepId = (await core.getProject(db, pep.key)).id;
await pair(ANNA.login, ANNA.chatId, 9401);
--
2.45.2
From b13b87d38d8657e90eed049d8fb7afbfdf192985 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 19:11:13 +0500
Subject: [PATCH 020/439] =?UTF-8?q?PEP-60:=20archive=20change=20=E2=80=94?=
=?UTF-8?q?=20platform-notifications=20spec?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.../.openspec.yaml | 0
.../design.md | 0
.../proposal.md | 0
.../specs/platform-notifications/spec.md | 0
.../tasks.md | 4 +-
openspec/specs/platform-notifications/spec.md | 55 +++++++++++++++++++
6 files changed, 57 insertions(+), 2 deletions(-)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/.openspec.yaml (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/design.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/proposal.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/specs/platform-notifications/spec.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/tasks.md (91%)
create mode 100644 openspec/specs/platform-notifications/spec.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/.openspec.yaml b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/.openspec.yaml
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/.openspec.yaml
diff --git a/openspec/changes/pep-60-platform-channel-digest/design.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/design.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/design.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/design.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/proposal.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/proposal.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/proposal.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/specs/platform-notifications/spec.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/specs/platform-notifications/spec.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
similarity index 91%
rename from openspec/changes/pep-60-platform-channel-digest/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
index 7276743f..2ea66040 100644
--- a/openspec/changes/pep-60-platform-channel-digest/tasks.md
+++ b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
@@ -14,5 +14,5 @@
- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
## 3. Проверка
-- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
-- [ ] 3.2 Документация: AGENTS.md, `/help`
+- [x] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
+- [x] 3.2 Документация: AGENTS.md, `/help`
diff --git a/openspec/specs/platform-notifications/spec.md b/openspec/specs/platform-notifications/spec.md
new file mode 100644
index 00000000..3da90d2a
--- /dev/null
+++ b/openspec/specs/platform-notifications/spec.md
@@ -0,0 +1,55 @@
+# platform-notifications Specification
+
+## Purpose
+Определяет, как Пеппа сообщает о себе: события платформы в Telegram-канал, заданный суперадмином, и дайджесты обновлений и состояния.
+
+## Requirements
+
+### Requirement: Канал платформы
+Суперадмин SHALL задавать Telegram-канал платформы по Chat ID в настройках платформы; Пеппа SHALL проверять, что бот может писать в канал, и показывать результат.
+
+#### Scenario: Бот — админ канала
+- **GIVEN** бот добавлен администратором канала с Chat ID «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** в настройках видно «канал подключён» с названием канала
+
+#### Scenario: Бот не добавлен в канал
+- **GIVEN** бот не состоит в канале «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** настройки показывают «бот не видит канал — добавьте его администратором»
+
+#### Scenario: Не суперадмин
+- **GIVEN** пользователь без роли суперадмина
+- **WHEN** он открывает настройки платформы
+- **THEN** он получает «не найдено»
+
+### Requirement: События платформы в канал
+Пеппа SHALL публиковать в канал платформы новые релизы, перезапуски и падения сервисов и их восстановление.
+
+#### Scenario: Новый релиз
+- **GIVEN** канал платформы подключён и в проде версия «0.15.0» коммит «aa8796a»
+- **WHEN** выкачена версия «0.16.0» коммит «b1c2d3e» с задачами PEP-59 и PEP-61
+- **THEN** в канале появляется сообщение «Peppa v0.16.0 · b1c2d3e» со списком «PEP-59, PEP-61»
+
+#### Scenario: Сервис упал и поднялся
+- **GIVEN** канал платформы подключён
+- **WHEN** бот Пеппы перестал отвечать дольше 2 минут, а затем восстановился
+- **THEN** в канале одно сообщение о падении и одно о восстановлении с длительностью простоя
+
+### Requirement: Дайджест
+Пеппа SHALL по расписанию отправлять в канал дайджест: изменения Пеппы с прошлого дайджеста и текущее состояние платформы; пользователи с привязанным Telegram SHALL получать личный дайджест по своим проектам, если не отписались.
+
+#### Scenario: Ежедневный дайджест
+- **GIVEN** с прошлого дайджеста смержены задачи PEP-59 и PEP-61, сейчас 2 активных раннера и 1 открытый вопрос
+- **WHEN** наступает время дайджеста
+- **THEN** в канале сообщение с разделами «Что нового» (PEP-59, PEP-61), «Сейчас»: раннеров 2, вопросов 1
+
+#### Scenario: Нечего сообщить
+- **GIVEN** с прошлого дайджеста не было изменений и активности
+- **WHEN** наступает время дайджеста
+- **THEN** дайджест не отправляется
+
+#### Scenario: Отписка
+- **GIVEN** пользователь отключил личный дайджест в Настройках
+- **WHEN** наступает время дайджеста
+- **THEN** он личный дайджест не получает, канал — получает
--
2.45.2
From b4b31ea88c89a8f649aa658e1d95443c43f9f1e0 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 19:21:23 +0500
Subject: [PATCH 021/439] PEP-62: write chat cursors only when they move
Co-Authored-By: Claude Opus 5.5
---
packages/core/src/chats.ts | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 1422ed20..282248e9 100644
--- a/packages/core/src/chats.ts
+++ b/packages/core/src/chats.ts
@@ -326,7 +326,9 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
};
// events
- let cursor = (await getSetting(db, CURSOR_EVENTS)) ?? (await initialCursor(db, events, now));
+ // Cursors are written only when they move: a no-op sync doesn't wake the other processes.
+ const savedEvents = await getSetting(db, CURSOR_EVENTS);
+ let cursor = savedEvents ?? (await initialCursor(db, events, now));
for (;;) {
// Read the newest id first: a row committed after it is picked up by the next call.
const [top] = await db.select({ max: sql`max(${events.id})` }).from(events);
@@ -355,10 +357,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo);
if (rows.length < BATCH) break;
}
- await setSetting(db, CURSOR_EVENTS, cursor);
+ if (cursor !== savedEvents) await setSetting(db, CURSOR_EVENTS, cursor);
// questions
- let qCursor = (await getSetting(db, CURSOR_QUESTIONS)) ?? (await initialCursor(db, questions, now));
+ const savedQuestions = await getSetting(db, CURSOR_QUESTIONS);
+ let qCursor = savedQuestions ?? (await initialCursor(db, questions, now));
for (;;) {
const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH);
for (const q of rows) {
@@ -379,10 +382,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
}
if (rows.length < BATCH) break;
}
- await setSetting(db, CURSOR_QUESTIONS, qCursor);
+ if (qCursor !== savedQuestions) await setSetting(db, CURSOR_QUESTIONS, qCursor);
// releases and incidents: one message per (id, status); the window overlaps a little.
- const since = new Date(((await getSetting(db, CURSOR_OBJECTS)) ?? now.getTime() - DAY) - 60_000);
+ const savedObjects = await getSetting(db, CURSOR_OBJECTS);
+ const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000);
for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
await add({
@@ -407,7 +411,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise
dedupeKey: `incident:${i.id}:${i.status}`,
});
}
- await setSetting(db, CURSOR_OBJECTS, now.getTime());
+ // Moved at most every 30 s (the window overlaps by a minute, so nothing is lost).
+ if (savedObjects == null || now.getTime() - savedObjects >= 30_000) await setSetting(db, CURSOR_OBJECTS, now.getTime());
if (added) await notify(db, { type: "chat_message", messageId: 0 });
return added;
}
--
2.45.2
From f00076c575d749ae7c3fcb68b7caefcab4e7b837 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 19:35:52 +0500
Subject: [PATCH 022/439] =?UTF-8?q?PEP-76:=20the=20project=20owner=20picks?=
=?UTF-8?q?=20the=20subscription=20=E2=80=94=20the=20shared=20pool=20or=20?=
=?UTF-8?q?their=20own=20Claude=20token?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 17 ++++++-
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/p/[key]/page.tsx | 41 +++++++++++++----
.../proposal.md | 16 +++++++
.../specs/agent-credentials/spec.md | 24 ++++++++++
.../tasks.md | 4 ++
openspec/specs/agent-credentials/spec.md | 23 ++++++++++
packages/cli/src/index.ts | 11 ++++-
packages/core/src/onboarding.ts | 7 ++-
packages/core/src/subscriptions.ts | 25 +++++++++++
packages/runner/src/index.ts | 1 +
packages/runner/src/project-subscription.ts | 45 +++++++++++++++++++
packages/runner/src/sessions.ts | 2 +-
packages/testkit/test/subscriptions.test.ts | 41 +++++++++++++++++
15 files changed, 247 insertions(+), 12 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md
create mode 100644 packages/runner/src/project-subscription.ts
diff --git a/AGENTS.md b/AGENTS.md
index 6ba94b29..fc2081e4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,6 +34,7 @@
- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
+- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 96ae9a2a..ec2e9d6c 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -660,3 +660,18 @@ export async function saveAgentsMdAction(f: FormData) {
return `/p/${p.key}?tab=agents&saved=1`;
});
}
+
+// ── PEP-76: what the project's agents run on ───────────────────────────────────────
+export async function chooseSharedSubscriptionAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await chooseSharedSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))));
+ });
+}
+
+export async function connectOwnSubscriptionAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await connectOwnSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), String(f.get("token") ?? ""));
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 049e478e..256b4aea 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,6 +70,7 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
+ Подписка проекта — на чём работают агенты, выбирает владелец в «⋯ Настройки проекта → Подписки»: «Общая подписка Пеппы» или своя подписка Claude (токен команды claude setup-token на своём компьютере). Пока выбор не сделан, проект нового пользователя агентов не запускает.
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 624b3c19..16ce033c 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, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-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, taskAgentNames, 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, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -21,7 +21,7 @@ import { requireUser } from "@/lib/auth";
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 { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
import { AgentsMdTab, CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
@@ -100,7 +100,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const isOwner = p.ownerId === user.id;
// PEP-67: default subscription pool; only a superadmin changes it.
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)]);
+ const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
// PEP-10/27: runner settings of the project over the system ones.
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.
@@ -291,7 +291,34 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
- {superadmin ? (
+
+ {pool ? (
+ <>Агенты работают на пуле «{pool.name}»{shared?.id === pool.id ? " — общая подписка Пеппы" : ""}.>
+ ) : agentWarning ? (
+ Подписка не выбрана — агенты не запустятся.
+ ) : (
+ "Пул не назначен — агенты работают на входе машины."
+ )}
+
+ {(isOwner || superadmin) && (
+ <>
+ {shared && shared.id !== pool?.id && (
+
+
+ Общая подписка Пеппы
+
+ )}
+
+
+
+ Своя подписка Claude
+
+ Токен выдаёт команда claude setup-token на вашем компьютере. Хранится зашифрованным, показать его нельзя. Уже подключали — оставьте поле пустым.
+
+
+ >
+ )}
+ {superadmin && (
@@ -302,10 +329,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Сохранить
- ) : (
- {pool ? <>Пул «{pool.name}»> : "Пул не назначен — агенты работают на входе машины"}
)}
- Раннеры проекта стартуют на свободной подписке пула по умолчанию. {superadmin ? Пулы и подписки : "Меняет суперадмин."}
+ Раннеры проекта стартуют на свободной подписке пула. {superadmin ? Пулы и подписки : "Выбирает владелец проекта."}
);
@@ -362,7 +387,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{agentWarning && (
Агенты не запустятся: {agentWarning}.
- {superadmin ? Подписки → : Попроси суперадмина проверить подписки или сменить пул в «⋯ Настройки проекта». }
+ {pool ? (superadmin ? Подписки → : Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её. ) : null}
)}
diff --git a/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md
new file mode 100644
index 00000000..342448d4
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/proposal.md
@@ -0,0 +1,16 @@
+# PEP-76: выбор подписки для проекта — общая или своя
+
+## Why
+После PEP-71 зарегистрироваться может любой человек с eGov, а его проект без пула подписок агентов не запускает: пул назначал
+только суперадмин. PM решил: новый пользователь сам выбирает — подключить свою подписку или работать на подписке PM.
+
+## What Changes
+- Общий пул платформы: настройка `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`).
+- Панель «Подписки» в настройках проекта для владельца (и суперадмина): «Общая подписка Пеппы» (`chooseSharedSubscription`) и
+ «Своя подписка Claude» (`connectOwnSubscription`): токен `claude setup-token` → подписка пользователя в его личном пуле
+ «Claude — <логин>»; пул уже есть и поле пустое — проект просто переходит на него. Токен хранится зашифрованным, только на запись.
+- `projectAgentWarning`: проект без пула, владелец которого не получает вход машины, — «подписка не выбрана» со ссылкой на выбор;
+ тот же текст в отказе запуска.
+- Событие `project_subscription` в журнале.
+
+Вне scope: свои подписки Codex/OpenCode, вход `claude setup-token` через браузер, лимиты на общую подписку. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..5dfed336
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/specs/agent-credentials/spec.md
@@ -0,0 +1,24 @@
+## ADDED Requirements
+
+### Requirement: Владелец выбирает подписку проекта
+Владелец проекта SHALL выбирать, на чём работают агенты проекта: на общем пуле платформы
+(«Общая подписка Пеппы», задаёт суперадмин) или на своей подписке Claude, подключённой
+токеном. Проект без пула, владельцу которого не положен вход машины, SHALL показывать, что
+подписка не выбрана, и не запускать агентов.
+
+#### Scenario: Общая подписка
+- **GIVEN** суперадмин задал общий пул, у проекта нового пользователя пула нет
+- **WHEN** владелец нажимает «Общая подписка Пеппы»
+- **THEN** проект работает на общем пуле, предупреждение «Агенты не запустятся» исчезает
+
+#### Scenario: Своя подписка
+- **WHEN** владелец вставляет токен своей подписки Claude и нажимает «Своя подписка Claude»
+- **THEN** создаются его подписка и пул «Claude — <логин>», проект работает на нём, токен нигде не показывается
+
+#### Scenario: Неверный токен
+- **WHEN** владелец вставляет строку, не похожую на токен Claude
+- **THEN** выбор отклонён, подписка не создаётся, пул проекта не меняется
+
+#### Scenario: Не владелец
+- **WHEN** участник проекта, не владелец и не суперадмин, пытается сменить подписку
+- **THEN** действие отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md
new file mode 100644
index 00000000..d9158adc
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-76-project-subscription-choice/tasks.md
@@ -0,0 +1,4 @@
+- [x] 1 `sharedPool`/`setSharedPool`/`ownPool`, CLI `peppa platform shared-pool`
+- [x] 2 `chooseSharedSubscription`/`connectOwnSubscription`, предупреждение «подписка не выбрана»
+- [x] 3 Панель «Подписки» в проекте
+- [x] 4 Тест в `subscriptions.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md
index 532df4b8..5531053c 100644
--- a/openspec/specs/agent-credentials/spec.md
+++ b/openspec/specs/agent-credentials/spec.md
@@ -98,3 +98,26 @@ Claude и делать пул с этой подпиской пулом по у
- **GIVEN** у «asel» в настройках был подключён Claude и он владелец проекта PEP
- **WHEN** применяется миграция
- **THEN** есть активная подписка «Claude — asel» с тем же токеном, у PEP пул «Claude — asel», а у пользователя токена больше нет
+
+### Requirement: Владелец выбирает подписку проекта
+Владелец проекта SHALL выбирать, на чём работают агенты проекта: на общем пуле платформы
+(«Общая подписка Пеппы», задаёт суперадмин) или на своей подписке Claude, подключённой
+токеном. Проект без пула, владельцу которого не положен вход машины, SHALL показывать, что
+подписка не выбрана, и не запускать агентов.
+
+#### Scenario: Общая подписка
+- **GIVEN** суперадмин задал общий пул, у проекта нового пользователя пула нет
+- **WHEN** владелец нажимает «Общая подписка Пеппы»
+- **THEN** проект работает на общем пуле, предупреждение «Агенты не запустятся» исчезает
+
+#### Scenario: Своя подписка
+- **WHEN** владелец вставляет токен своей подписки Claude и нажимает «Своя подписка Claude»
+- **THEN** создаются его подписка и пул «Claude — <логин>», проект работает на нём, токен нигде не показывается
+
+#### Scenario: Неверный токен
+- **WHEN** владелец вставляет строку, не похожую на токен Claude
+- **THEN** выбор отклонён, подписка не создаётся, пул проекта не меняется
+
+#### Scenario: Не владелец
+- **WHEN** участник проекта, не владелец и не суперадмин, пытается сменить подписку
+- **THEN** действие отклонено
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 7d3977cf..759c72e0 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -71,7 +71,7 @@ import {
import { createDb, migrateDb } from "@peppa/db";
import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
-import { createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
+import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
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";
@@ -120,6 +120,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa host check|disable|enable|rm|push-image
(PEP-10/27: system → project → story; a story overrides mode/context only)
peppa platform allowlist | allow | deny (who may log into Peppa)
+ peppa platform shared-pool [poolId|-] (the pool any project owner may pick as the shared subscription)
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
@@ -674,6 +675,14 @@ async function main(): Promise {
console.log(`${u.login} (#${u.id})`);
break;
}
+ case "platform shared-pool": {
+ // PEP-76: the pool project owners may pick as «Общая подписка Пеппы».
+ if (args[0] === "-") await setSharedPool(db, null);
+ else if (args[0]) await setSharedPool(db, Number(args[0]));
+ const sp = await sharedPool(db);
+ console.log(sp ? `общий пул: #${sp.id} «${sp.name}»` : "общий пул не задан");
+ break;
+ }
case "platform release-offers": {
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index 02c9c759..dcf895e1 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -1,6 +1,7 @@
// 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 { mayUseMachineLogin } from "./access.ts";
import { isSuperadmin } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { isUsable, poolSubscriptions } from "./subscriptions.ts";
@@ -78,7 +79,11 @@ const STATUS_RU: Record = { pending: "не подключена"
*/
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;
+ if (p?.poolId == null) {
+ // PEP-71/76: a self-registered owner has no machine login — a subscription must be chosen.
+ const [o] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
+ return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не выбрана — владелец выбирает общую или подключает свою в «⋯ Настройки проекта → Подписки»";
+ }
const subs = await poolSubscriptions(db, p.poolId);
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
if (subs.some((s) => isUsable(s, now))) return null;
diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts
index 00da7e5c..afe86721 100644
--- a/packages/core/src/subscriptions.ts
+++ b/packages/core/src/subscriptions.ts
@@ -9,6 +9,7 @@ import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { isSuperadmin } from "./monitor.ts";
import type { Project } from "./projects.ts";
+import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
import type { User } from "./users.ts";
@@ -377,3 +378,27 @@ export async function projectPoolExhausted(db: Db, projectId: number, now = new
if (p?.poolId == null) return false;
return !(await poolSubscriptions(db, p.poolId)).some((s) => isUsable(s, now));
}
+
+// ── PEP-76: the platform's shared pool and the owner's choice ───────────────────────
+const SHARED_POOL = "platform.shared_pool";
+
+/** The pool any project owner may pick as «Общая подписка Пеппы» (set by a superadmin), or null. */
+export async function sharedPool(db: Db): Promise {
+ const id = await getSetting(db, SHARED_POOL);
+ if (id == null) return null;
+ const [p] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id));
+ return p ?? null;
+}
+
+export async function setSharedPool(db: Db, poolId: number | null): Promise {
+ if (poolId == null) return deleteSetting(db, SHARED_POOL);
+ await getPool(db, poolId);
+ await setSetting(db, SHARED_POOL, poolId);
+}
+
+/** The user's own pool (the first one they created that is not the shared pool), or null. */
+export async function ownPool(db: Db, userId: number): Promise {
+ const shared = await sharedPool(db);
+ const rows = await db.select().from(subscriptionPools).where(eq(subscriptionPools.createdBy, userId)).orderBy(asc(subscriptionPools.id));
+ return rows.find((p) => p.id !== shared?.id) ?? null;
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d8956b45..d67c661c 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -19,6 +19,7 @@ export * from "./deploy.ts";
export * from "./platform-release.ts";
export * from "./code.ts";
export * from "./agents-md.ts";
+export * from "./project-subscription.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts
new file mode 100644
index 00000000..3e9f892f
--- /dev/null
+++ b/packages/runner/src/project-subscription.ts
@@ -0,0 +1,45 @@
+// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
+// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
+// kept encrypted like every subscription, in the owner's personal pool).
+import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, type Project, type User } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { addSubscription } from "./subscriptions.ts";
+
+async function requireOwner(db: Db, user: User, project: Project): Promise {
+ if (project.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError("Подписку проекта выбирает его владелец");
+}
+
+/** «Общая подписка Пеппы»: the project runs on the platform's shared pool. */
+export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise {
+ await requireOwner(db, user, project);
+ const pool = await sharedPool(db);
+ if (!pool) throw new PeppaError("Общая подписка не настроена — подключите свою или попросите администратора");
+ await setProjectPool(db, project.id, pool.id);
+ await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
+}
+
+/**
+ * «Своя подписка»: with a token — a new Claude subscription of the user goes into their own
+ * pool (created on first use); without one — the project just moves to the pool they already have.
+ */
+export async function connectOwnSubscription(db: Db, user: User, project: Project, token: string): Promise {
+ await requireOwner(db, user, project);
+ let pool = await ownPool(db, user.id);
+ if (token.trim()) {
+ const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
+ let name = `Claude — ${user.login}`;
+ for (let n = 2; taken.has(name); n++) name = `Claude — ${user.login} ${n}`;
+ const sub = await addSubscription(db, { provider: "claude", name, method: "token", secret: token, createdBy: user.id });
+ if (pool) {
+ const cur = (await listPools(db)).find((p) => p.id === pool!.id);
+ await updatePool(db, pool.id, { subscriptionIds: [...(cur?.subscriptionIds ?? []), sub.id] });
+ } else {
+ pool = await createPool(db, { name: `Claude — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
+ }
+ } else if (!pool) {
+ throw new PeppaError("Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат");
+ }
+ await getPool(db, pool.id);
+ await setProjectPool(db, project.id, pool.id);
+ await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", poolId: pool.id } });
+}
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 86aaf6ad..18ab2521 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -146,7 +146,7 @@ export async function startRunner(
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
// PEP-71: self-registered (eGov) users don't get this machine's login for free.
if (!sub && !sandboxed && !(await mayUseMachineLogin(db, project.ownerId))) {
- throw new PeppaError("У проекта нет пула подписок — агенты не запустятся. Попросите администратора назначить пул в «⋯ Настройки проекта»");
+ throw new PeppaError("Подписка проекта не выбрана — агенты не запустятся. Владелец выбирает общую подписку Пеппы или подключает свою в «⋯ Настройки проекта → Подписки»");
}
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError("Для запуска агента в контейнере нужна подписка: добавьте её в пул проекта (раздел «Подписки»)");
diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts
index 102d1a3c..cb624bf1 100644
--- a/packages/testkit/test/subscriptions.test.ts
+++ b/packages/testkit/test/subscriptions.test.ts
@@ -251,3 +251,44 @@ describe("Перенос токена Claude из настроек", () => {
await runner.stopSession(db, sid);
});
});
+
+describe("PEP-76: владелец выбирает подписку проекта", () => {
+ test("Scenario: общая подписка или своя; без выбора агенты самозарегистрированного не запускаются", async () => {
+ const admin = await core.upsertUserFromGitea(db, { id: 7601, login: "mock-p76-admin" }, { access_token: "x" });
+ const owner = await core.registerEgovUser(db, { iin: "850505400008", name: "ВЫБОРОВ ТЕСТ" });
+ const stranger = await core.registerEgovUser(db, { iin: "850505400018", name: "ЧУЖОЙ ТЕСТ" });
+ const p = await core.createProject(db, { slug: "mock-p76", key: "MPSUB", name: "P76", giteaOwner: "x", workspacePath: "/tmp/mock-p76", ownerId: owner.id });
+ assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не выбрана/);
+
+ // No shared pool yet → only the own one is possible.
+ await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не настроена/);
+ const sub = await runner.addSubscription(db, { provider: "claude", name: "mock-p76 общая", method: "token", secret: "sk-ant-oat01-" + "a".repeat(40), createdBy: admin.id });
+ const pool = await core.createPool(db, { name: "mock-p76 общий", subscriptionIds: [sub.id], createdBy: admin.id });
+ await core.setSharedPool(db, pool.id);
+ try {
+ await assert.rejects(runner.chooseSharedSubscription(db, stranger, p), /владелец/);
+ await runner.chooseSharedSubscription(db, owner, p);
+ assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
+ assert.equal(await core.projectAgentWarning(db, p.id), null);
+
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, ""), /Вставьте токен/);
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "не токен"), /не похоже на токен/);
+ assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 0, "a bad token leaves nothing behind");
+ await runner.connectOwnSubscription(db, owner, p, "sk-ant-oat01-" + "b".repeat(40));
+ const own = (await core.ownPool(db, owner.id))!;
+ assert.equal((await core.projectPool(db, p.id))!.id, own.id);
+ assert.equal(own.name, `Claude — ${owner.login}`);
+ const mine = (await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id);
+ assert.equal(mine.length, 1);
+ assert.equal(core.subscriptionSecret(mine[0]!), "sk-ant-oat01-" + "b".repeat(40));
+
+ // Back to shared and to own again without a token: the existing pool is reused.
+ await runner.chooseSharedSubscription(db, owner, p);
+ await runner.connectOwnSubscription(db, owner, p, "");
+ assert.equal((await core.projectPool(db, p.id))!.id, own.id);
+ assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 1);
+ } finally {
+ await core.setSharedPool(db, null);
+ }
+ });
+});
--
2.45.2
From 4729300a10d7e917967bbeb8ce270c05343d644c 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 19:50:59 +0500
Subject: [PATCH 023/439] PEP-77: progress of all stories and projects on the
Home page
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/page.tsx | 8 +-
apps/web/components/ProgressOverview.tsx | 122 ++++++++++++++++++
.../proposal.md | 14 ++
.../specs/web-workspace/spec.md | 21 +++
.../2026-11-14-pep-77-home-progress/tasks.md | 3 +
openspec/specs/web-workspace/spec.md | 20 +++
packages/core/src/index.ts | 1 +
packages/core/src/progress.ts | 77 +++++++++++
packages/testkit/test/web.test.ts | 39 ++++++
10 files changed, 304 insertions(+), 2 deletions(-)
create mode 100644 apps/web/components/ProgressOverview.tsx
create mode 100644 openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md
create mode 100644 packages/core/src/progress.ts
diff --git a/AGENTS.md b/AGENTS.md
index 3eeaba4b..0206372e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -36,6 +36,7 @@
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
- **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts`
+- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 81f7fc99..454e7bd9 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -1,4 +1,5 @@
-import { listUserProjects, onboardingChecklist } from "@peppa/core";
+import { listUserProjects, onboardingChecklist, progressOverview } from "@peppa/core";
+import { ProgressOverview } from "@/components/ProgressOverview";
import { OnboardingChecklist } from "@/components/Onboarding";
import { PugBanner } from "@/components/PugMascot";
import { LiveRefresh } from "@/components/LiveRefresh";
@@ -13,7 +14,7 @@ import { activeSessions, inbox } from "@/lib/queries";
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { error } = await searchParams;
- const [items, sessions, projects, onboarding] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user)]);
+ const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
return (
}>
@@ -24,6 +25,9 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
{items.map((q) => )}
+
все раннеры}>
{sessions.length === 0 ? Сейчас ничего не запущено. : sessions.map((s) => )}
diff --git a/apps/web/components/ProgressOverview.tsx b/apps/web/components/ProgressOverview.tsx
new file mode 100644
index 00000000..88eddb60
--- /dev/null
+++ b/apps/web/components/ProgressOverview.tsx
@@ -0,0 +1,122 @@
+import Link from "next/link";
+import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
+import { AgentBadge } from "@/components/AgentBadge";
+import { Disclosure, Empty, Key } from "@/components/common";
+import { cn } from "@/lib/utils";
+
+const PARTS = [
+ { k: "done", label: "готово", bar: "bg-ok" },
+ { k: "review", label: "ревью", bar: "bg-primary" },
+ { k: "inProgress", label: "в работе", bar: "bg-info" },
+ { k: "backlog", label: "бэклог", bar: "bg-muted-foreground/40" },
+] as const;
+
+type Counts = Pick;
+
+/** One bar split by board column: done · review · in work · backlog. */
+function StackedBar({ c, className }: { c: Counts; className?: string }) {
+ const label = PARTS.map((p) => `${p.label} ${c[p.k]}`).join(", ");
+ return (
+
+ {c.total > 0 && PARTS.map((p) => (c[p.k] ? : null))}
+
+ );
+}
+
+const pct = (c: Counts) => (c.total ? Math.round((c.done / c.total) * 100) : 0);
+
+function Legend({ c }: { c: Counts }) {
+ return (
+
+ {PARTS.map((p) => (
+
+
+ {p.label} {c[p.k]}
+
+ ))}
+
+ );
+}
+
+function ProjectRow({ p }: { p: ProjectProgress }) {
+ return (
+
+
+ {p.key}
+ {p.name}
+ {p.ownerLogin && {p.ownerLogin} }
+
+ {p.total ? (
+ <>
+ готово {p.done} из {p.total} · {pct(p)}%
+ >
+ ) : (
+ "стори пока нет"
+ )}
+
+
+
+ {p.working.length > 0 && (
+
+ {p.working.map((s) => (
+
+ {s.key}
+ {s.title}
+ {s.agent && }
+ {s.total ? (
+
+ {s.done}/{s.total}
+
+ ) : null}
+
+ ))}
+
+ )}
+ {p.reviewKeys.length > 0 && (
+
+ Ждут «Принять»:
+ {p.reviewKeys.slice(0, 8).map((k) => (
+ {k}
+ ))}
+ {p.reviewKeys.length > 8 && и ещё {p.reviewKeys.length - 8} }
+
+ )}
+
+ );
+}
+
+/** PEP-77: progress of all stories and projects on the Home page. */
+export function ProgressOverview({ data }: { data: Overview }) {
+ if (!data.mine.length && !data.others.length) return Проектов пока нет — прогресс появится с первой стори. ;
+ const t = data.totals;
+ return (
+
+ {data.mine.length > 0 && (
+
+
+ {pct(t)}%
+
+ готово {t.done} из {t.total} стори в {data.mine.length} {data.mine.length === 1 ? "проекте" : "проектах"}
+
+
+
+
+
+ )}
+
+ {data.mine.map((p) => (
+
+ ))}
+
+ {data.others.length > 0 && (
+
+
+ {data.others.map((p) => (
+
+ ))}
+
+
+ )}
+
+ );
+}
diff --git a/openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md b/openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md
new file mode 100644
index 00000000..1c315820
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-77-home-progress/proposal.md
@@ -0,0 +1,14 @@
+# PEP-77: прогресс по всем проектам на Главной
+
+## Why
+На Главной видны вопросы агентов и раннеры, но не видно, как идут дела в целом. Чтобы понять, сколько сделано и что в работе,
+приходится открывать доску каждого проекта.
+
+## What Changes
+- `progressOverview` (core/progress.ts): по проектам пользователя — число стори в колонках доски (бэклог / в работе / ревью / готово,
+ без архивных), стори в работе с агентом и прогрессом tasks.md, ключи стори, ждущих «Принять»; общий итог по своим проектам.
+ Суперадмину — отдельно проекты других (в итог не входят).
+- Раздел «Прогресс» на Главной (`components/ProgressOverview.tsx`): итог с процентом и полосой, строка на проект, «Проекты других»
+ свёрнуты.
+
+Вне scope: графики по времени (они во вкладке «Метрики» проекта). Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md
new file mode 100644
index 00000000..29292228
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-77-home-progress/specs/web-workspace/spec.md
@@ -0,0 +1,21 @@
+## ADDED Requirements
+
+### Requirement: Прогресс на Главной
+Главная SHALL показывать раздел «Прогресс»: общий итог по стори своих проектов и по каждому
+проекту — сколько стори в бэклоге, в работе, в ревью и готово, какие стори в работе (агент,
+прогресс tasks.md) и какие ждут «Принять». Архивные стори не считаются. Суперадмин SHALL
+видеть отдельно проекты других, не входящие в общий итог.
+
+#### Scenario: Свои проекты
+- **GIVEN** в проекте «PAY» 1 стори в бэклоге, 1 в работе, 1 в ревью, 1 готова и 1 в архиве
+- **WHEN** владелец открывает Главную
+- **THEN** итог — «готово 1 из 4», у «PAY» показаны стори в работе и стори, ждущая «Принять»
+
+#### Scenario: Суперадмин
+- **GIVEN** проект «TZK» другого пользователя
+- **WHEN** суперадмин открывает Главную
+- **THEN** «TZK» показан в свёрнутом блоке «Проекты других» с логином владельца, в общий итог он не входит
+
+#### Scenario: Обычный пользователь
+- **WHEN** Главную открывает пользователь без прав суперадмина
+- **THEN** блока «Проекты других» нет
diff --git a/openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md b/openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md
new file mode 100644
index 00000000..47d928df
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-77-home-progress/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `progressOverview` в core
+- [x] 2 Раздел «Прогресс» на Главной
+- [x] 3 Тест в `web.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 476bfab6..34794b34 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -381,3 +381,23 @@ PM SHALL уметь убрать стори в архив и вернуть её
- **GIVEN** участник открыл редактор, а коллега тем временем закоммитил другой `AGENTS.md`
- **WHEN** участник сохраняет свою версию
- **THEN** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
+
+### Requirement: Прогресс на Главной
+Главная SHALL показывать раздел «Прогресс»: общий итог по стори своих проектов и по каждому
+проекту — сколько стори в бэклоге, в работе, в ревью и готово, какие стори в работе (агент,
+прогресс tasks.md) и какие ждут «Принять». Архивные стори не считаются. Суперадмин SHALL
+видеть отдельно проекты других, не входящие в общий итог.
+
+#### Scenario: Свои проекты
+- **GIVEN** в проекте «PAY» 1 стори в бэклоге, 1 в работе, 1 в ревью, 1 готова и 1 в архиве
+- **WHEN** владелец открывает Главную
+- **THEN** итог — «готово 1 из 4», у «PAY» показаны стори в работе и стори, ждущая «Принять»
+
+#### Scenario: Суперадмин
+- **GIVEN** проект «TZK» другого пользователя
+- **WHEN** суперадмин открывает Главную
+- **THEN** «TZK» показан в свёрнутом блоке «Проекты других» с логином владельца, в общий итог он не входит
+
+#### Scenario: Обычный пользователь
+- **WHEN** Главную открывает пользователь без прав суперадмина
+- **THEN** блока «Проекты других» нет
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a7e18ba0..0a0ededf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -21,6 +21,7 @@ export * from "./incidents.ts";
export * from "./ci.ts";
export * from "./egov.ts";
export * from "./team.ts";
+export * from "./progress.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";
diff --git a/packages/core/src/progress.ts b/packages/core/src/progress.ts
new file mode 100644
index 00000000..63a9a75c
--- /dev/null
+++ b/packages/core/src/progress.ts
@@ -0,0 +1,77 @@
+// PEP-77: progress of every project on the Home page — stories per board column and what is
+// in work right now (agent, tasks.md progress).
+import { projects, tasks, users, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, asc, eq, inArray, isNull } from "drizzle-orm";
+import { taskProgress } from "./openspec.ts";
+import { taskAgentNames } from "./team.ts";
+import { listOtherProjects, userProjectIds } from "./users.ts";
+
+export interface StoryInWork {
+ key: string;
+ title: string;
+ status: string;
+ agent: string | null;
+ /** tasks.md of the story's change: done/total and the current item. */
+ done: number | null;
+ total: number | null;
+ current: string | null;
+}
+
+export interface ProjectProgress {
+ key: string;
+ name: string;
+ /** Set for a project of somebody else (a superadmin's view). */
+ ownerLogin: string | null;
+ backlog: number;
+ inProgress: number;
+ review: number;
+ done: number;
+ total: number;
+ working: StoryInWork[];
+ /** Stories waiting for the PM's «Принять». */
+ reviewKeys: string[];
+}
+
+export interface ProgressOverview {
+ mine: ProjectProgress[];
+ /** Other people's projects — for a superadmin only. */
+ others: ProjectProgress[];
+ totals: { backlog: number; inProgress: number; review: number; done: number; total: number };
+}
+
+/** Board column of a story status (the same split as the board). */
+const column = (status: string) => (status === "backlog" ? "backlog" : status === "review" ? "review" : status === "done" ? "done" : "inProgress");
+
+export async function progressOverview(db: Db, userId: number): Promise {
+ const mineIds = await userProjectIds(db, userId);
+ const otherRows = await listOtherProjects(db, userId);
+ const ids = [...mineIds, ...otherRows.map((p) => p.id)];
+ const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 } };
+ if (!ids.length) return empty;
+ const ps = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).where(inArray(projects.id, ids)).orderBy(asc(projects.key));
+ const ts = await db.select().from(tasks).where(and(inArray(tasks.projectId, ids), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number));
+ const mine = new Set(mineIds);
+ const out = empty;
+ for (const { p, ownerLogin } of ps) {
+ const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? "без владельца"), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [] };
+ const own = ts.filter((t) => t.projectId === p.id);
+ const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map();
+ for (const t of own) {
+ const c = column(t.status);
+ row[c]++;
+ row.total++;
+ const key = formatTaskKey(p.key, t.number);
+ if (c === "review") row.reviewKeys.push(key);
+ if (c === "inProgress") {
+ const pr = taskProgress(p, t.openspecChange);
+ row.working.push({ key, title: t.title, status: t.status, agent: agentsOf.get(t.id) ?? null, done: pr?.done ?? null, total: pr?.total ?? null, current: pr?.current ?? null });
+ }
+ }
+ if (mine.has(p.id)) {
+ out.mine.push(row);
+ for (const k of ["backlog", "inProgress", "review", "done", "total"] as const) out.totals[k] += row[k];
+ } else out.others.push(row);
+ }
+ return out;
+}
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 137ad7a4..9b710bff 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -163,3 +163,42 @@ describe("PEP-74: суперадмин видит все проекты", () =>
}
});
});
+
+describe("PEP-77: прогресс по всем проектам", () => {
+ test("колонки, стори в работе, ждущие «Принять»; чужие проекты — только суперадмину", async () => {
+ const me = await core.upsertUserFromGitea(db, { id: 7701, login: "mock-p77-me" }, { access_token: "x" });
+ const other = await core.upsertUserFromGitea(db, { id: 7702, login: "mock-p77-other" }, { access_token: "x" });
+ const a = await core.createProject(db, { slug: "mock-p77a", key: "MPRA", name: "A", giteaOwner: "x", workspacePath: "/tmp/mock-p77a", ownerId: me.id });
+ const b = await core.createProject(db, { slug: "mock-p77b", key: "MPRB", name: "B", giteaOwner: "x", workspacePath: "/tmp/mock-p77b", ownerId: other.id });
+ const mk = async (projectId: number, title: string, status?: "in_progress" | "review" | "done") => {
+ const t = await core.createTask(db, { projectId, title });
+ if (status) await core.updateTask(db, t, { status });
+ return t;
+ };
+ await mk(a.id, "бэклог");
+ const w = await mk(a.id, "в работе", "in_progress");
+ const r = await mk(a.id, "ревью", "review");
+ await mk(a.id, "готово", "done");
+ const archived = await mk(a.id, "в архиве", "done");
+ await core.setTaskArchived(db, archived, true);
+ await mk(b.id, "чужая", "done");
+
+ const mine = await core.progressOverview(db, me.id);
+ assert.deepEqual(mine.totals, { backlog: 1, inProgress: 1, review: 1, done: 1, total: 4 }, "archived stories are not counted");
+ assert.deepEqual(mine.mine.map((p) => p.key), ["MPRA"]);
+ assert.deepEqual(mine.others, []);
+ assert.deepEqual(mine.mine[0]!.working.map((s) => s.key), [w.key]);
+ assert.deepEqual(mine.mine[0]!.reviewKeys, [r.key]);
+
+ await core.setPlatformAdmins(db, ["mock-p77-me"]);
+ try {
+ const boss = await core.progressOverview(db, me.id);
+ const row = boss.others.find((p) => p.key === "MPRB")!;
+ assert.equal(row.ownerLogin, "mock-p77-other");
+ assert.equal(row.done, 1);
+ assert.equal(boss.totals.total, 4, "totals — own projects only");
+ } finally {
+ await core.setPlatformAdmins(db, null);
+ }
+ });
+});
--
2.45.2
From 335b8b159ed760b295f0557eced19ec14af2a5f0 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 20:02:16 +0500
Subject: [PATCH 024/439] PEP-78: the action error stays in view while the page
is scrolled
Co-Authored-By: Claude Fable 5.2
---
apps/web/components/common.tsx | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx
index ace2ab0a..bcfc1be4 100644
--- a/apps/web/components/common.tsx
+++ b/apps/web/components/common.tsx
@@ -62,7 +62,8 @@ export function StatusBadge({ status, kind = "task" }: { status: string; kind?:
export function Flash({ error }: { error?: string }) {
return error ? (
-
+ // Sticky: an action far down the page (a board card, «Принять») must not fail silently above the fold.
+
{error}
--
2.45.2
From 6066ce8763107cd4dc437a90a3f0cb0082e8d26c 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 20:14:40 +0500
Subject: [PATCH 025/439] PEP-60: mock-telegram rejects posts only to channels
added with addChannel (supergroups of PEP-62 keep working)
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/src/mock-telegram.ts | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 27d12638..61a7bb33 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -116,12 +116,11 @@ export class MockTelegram {
return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
}
case "sendMessage": {
- // Channels (-100…): the bot must be an admin that may post.
- if (String(p.chat_id).startsWith("-100")) {
- const c = this.channels.get(Number(p.chat_id));
- if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
- if (c.bot !== "administrator" || !c.canPost) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
- }
+ // Channels added with addChannel: the bot must be an admin that may post. Other «-100…»
+ // ids are supergroups (PEP-62) and accept messages as before.
+ const ch = this.channels.get(Number(p.chat_id));
+ if (ch && ch.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (ch && (ch.bot !== "administrator" || !ch.canPost)) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
const m: MockTgMessage = {
message_id: this.nextMessageId++,
chat_id: Number(p.chat_id),
--
2.45.2
From e9526c9329e48c6610c17e1b5634c98cca2bbffa 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 20:15:22 +0500
Subject: [PATCH 026/439] =?UTF-8?q?PEP-79,=20PEP-80:=20new=20projects=20pi?=
=?UTF-8?q?ck=20stories=20themselves;=20own=20subscription=20=E2=80=94=20C?=
=?UTF-8?q?laude=20or=20ChatGPT?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 2 +
apps/web/app/(app)/actions.ts | 8 ++-
apps/web/app/(app)/help/page.tsx | 3 +-
apps/web/app/(app)/p/[key]/page.tsx | 34 +++++++++--
.../proposal.md | 15 +++++
.../specs/agent-credentials/spec.md | 19 ++++++
.../specs/project-autonomy/spec.md | 16 +++++
.../tasks.md | 3 +
openspec/specs/agent-credentials/spec.md | 18 ++++++
openspec/specs/project-autonomy/spec.md | 15 +++++
packages/core/src/autonomy.ts | 10 ++-
packages/core/src/onboarding.ts | 2 +-
packages/runner/src/autonomy.ts | 3 +
packages/runner/src/project-subscription.ts | 61 +++++++++++++++----
packages/runner/src/provision.ts | 4 +-
packages/runner/src/sessions.ts | 2 +-
packages/testkit/test/subscriptions.test.ts | 35 +++++++++--
17 files changed, 220 insertions(+), 30 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index 0206372e..5d5861c5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -37,6 +37,8 @@
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
- **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts`
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
+- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
+- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index ec2e9d6c..39782563 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, chooseSharedSubscription } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -672,6 +672,10 @@ export async function chooseSharedSubscriptionAction(f: FormData) {
export async function connectOwnSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
- await connectOwnSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), String(f.get("token") ?? ""));
+ const kind = str(f, "kind") as OwnSubscriptionKind;
+ if (!["claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
+ return `/p/${p.key}?settings=subscription`;
});
}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 64f0a746..223f267c 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,7 +70,8 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
- Подписка проекта — на чём работают агенты, выбирает владелец в «⋯ Настройки проекта → Подписки»: «Общая подписка Пеппы» или своя подписка Claude (токен команды claude setup-token на своём компьютере). Пока выбор не сделан, проект нового пользователя агентов не запускает.
+ Подписка проекта — на чём работают агенты. Владелец подключает свою в «⋯ Настройки проекта → Подписки»: Claude (токен команды claude setup-token ), ChatGPT (вход по ссылке и коду) или ключ OpenAI API. Пока подписки нет, агенты проекта не запускаются.
+ Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 16ce033c..8119e0a9 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, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-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, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
+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, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -107,6 +107,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
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);
+ // PEP-80: the owner's own subscriptions — a ChatGPT device login in progress, and whether a pool exists already.
+ const mayChoose = isOwner || superadmin;
+ const [ownLogins, hasOwnPool] = await Promise.all([mayChoose && pool ? ownPendingLogins(db, pool.id) : Promise.resolve([]), mayChoose ? ownPool(db, user.id).then((x) => !!x) : Promise.resolve(false)]);
// 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}`);
@@ -308,12 +311,33 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Общая подписка Пеппы
)}
+ {ownLogins.map((l) => (
+
+
Вход в ChatGPT не завершён
+
+ 1. Откройте {l.url} и войдите в свой ChatGPT.
+
+ {l.code && (
+
+ 2. Введите код {l.code}
+
+ )}
+
Потом обновите эту страницу — подписка станет активной.
+
+ ))}
-
- Своя подписка Claude
+
+ Claude — токен (claude setup-token)
+ ChatGPT — вход по ссылке и коду
+ Codex — ключ OpenAI API
+ {hasOwnPool && Моя уже подключённая подписка }
+
+
+ Подключить свою подписку
- Токен выдаёт команда claude setup-token на вашем компьютере. Хранится зашифрованным, показать его нельзя. Уже подключали — оставьте поле пустым.
+ Claude: выполните claude setup-token на своём компьютере и вставьте токен. ChatGPT: поле оставьте пустым — появится ссылка и код для входа. Токены и ключи
+ хранятся зашифрованными, показать их нельзя.
>
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md
new file mode 100644
index 00000000..dcea9824
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/proposal.md
@@ -0,0 +1,15 @@
+# PEP-79 / PEP-80: стори берутся сами; своя подписка Claude или ChatGPT
+
+## Why
+PM: пользователь-непрограммист не должен перетаскивать карточки, чтобы агент начал работать. И новые пользователи должны
+работать на своих подписках (Claude или ChatGPT), а не на подписке PM.
+
+## What Changes
+- PEP-79: уровень автономности «Сам берёт» (`self`: pick=auto, мерж и приёмка за PM). Новый проект создаётся с ним
+ (`NEW_PROJECT_AUTONOMY` в `provisionProject`); существующие проекты не меняются. Диспетчер ничего не запускает и никого не
+ пингует, пока у проекта есть предупреждение «Агенты не запустятся» (подписка не подключена или не работает).
+- PEP-80: `connectOwnSubscription(kind)`: `claude` (токен), `codex_login` (ChatGPT — device-вход Codex; ссылку и код показывает
+ панель «Подписки» проекта, `ownPendingLogins`), `codex_key` (ключ OpenAI API), `existing` (уже подключённый пул). Личный пул —
+ «Подписки — <логин>». Общая подписка остаётся возможностью суперадмина (`platform.shared_pool`), на живой системе выключена.
+
+Вне scope: подписки OpenCode у пользователей. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..7205c721
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/agent-credentials/spec.md
@@ -0,0 +1,19 @@
+## ADDED Requirements
+
+### Requirement: Своя подписка Claude или ChatGPT
+Владелец проекта SHALL подключать свою подписку: Claude по токену, ChatGPT входом по ссылке
+и одноразовому коду, либо Codex по ключу OpenAI API. Подписки пользователя SHALL собираться
+в его личный пул, который можно назначить и другим его проектам.
+
+#### Scenario: ChatGPT
+- **WHEN** владелец выбирает «ChatGPT — вход по ссылке и коду» и нажимает «Подключить свою подписку»
+- **THEN** панель «Подписки» показывает ссылку и код; после входа и обновления страницы подписка активна
+
+#### Scenario: Уже подключённая
+- **GIVEN** у владельца есть личный пул
+- **WHEN** в другом своём проекте он выбирает «Моя уже подключённая подписка»
+- **THEN** проект работает на этом пуле, новая подписка не создаётся
+
+#### Scenario: Пустой токен Claude
+- **WHEN** владелец выбирает Claude и не вставляет токен
+- **THEN** подключение отклонено с подсказкой про `claude setup-token`
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md
new file mode 100644
index 00000000..0f5274a6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/specs/project-autonomy/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Новый проект берёт стори сам
+Новый проект SHALL создаваться с уровнем автономности «Сам берёт»: диспетчер берёт стори из
+бэклога по порядку доски, результат принимает PM. Пока у проекта нет рабочей подписки,
+диспетчер SHALL NOT запускать стори и беспокоить PM.
+
+#### Scenario: Стори без перетаскивания
+- **GIVEN** новый проект с подключённой подпиской
+- **WHEN** пользователь создаёт стори
+- **THEN** агент берёт её из бэклога сам, карточка переходит «В работу»
+
+#### Scenario: Подписка не подключена
+- **GIVEN** новый проект без подписки и стори в бэклоге
+- **WHEN** проходит тик диспетчера
+- **THEN** стори остаётся в бэклоге, вопросов PM не появляется
diff --git a/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md
new file mode 100644
index 00000000..98865924
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-79-self-pick-own-subscription/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 Уровень `self`, `NEW_PROJECT_AUTONOMY`, новый проект создаётся с ним; диспетчер молчит без подписки
+- [x] 2 `connectOwnSubscription` с видами подписки, `ownPendingLogins`, панель «Подписки»
+- [x] 3 Тесты `subscriptions.test.ts`, `openspec validate`
diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md
index 5531053c..c586dae1 100644
--- a/openspec/specs/agent-credentials/spec.md
+++ b/openspec/specs/agent-credentials/spec.md
@@ -121,3 +121,21 @@ Claude и делать пул с этой подпиской пулом по у
#### Scenario: Не владелец
- **WHEN** участник проекта, не владелец и не суперадмин, пытается сменить подписку
- **THEN** действие отклонено
+
+### Requirement: Своя подписка Claude или ChatGPT
+Владелец проекта SHALL подключать свою подписку: Claude по токену, ChatGPT входом по ссылке
+и одноразовому коду, либо Codex по ключу OpenAI API. Подписки пользователя SHALL собираться
+в его личный пул, который можно назначить и другим его проектам.
+
+#### Scenario: ChatGPT
+- **WHEN** владелец выбирает «ChatGPT — вход по ссылке и коду» и нажимает «Подключить свою подписку»
+- **THEN** панель «Подписки» показывает ссылку и код; после входа и обновления страницы подписка активна
+
+#### Scenario: Уже подключённая
+- **GIVEN** у владельца есть личный пул
+- **WHEN** в другом своём проекте он выбирает «Моя уже подключённая подписка»
+- **THEN** проект работает на этом пуле, новая подписка не создаётся
+
+#### Scenario: Пустой токен Claude
+- **WHEN** владелец выбирает Claude и не вставляет токен
+- **THEN** подключение отклонено с подсказкой про `claude setup-token`
diff --git a/openspec/specs/project-autonomy/spec.md b/openspec/specs/project-autonomy/spec.md
index 28582511..3266f29d 100644
--- a/openspec/specs/project-autonomy/spec.md
+++ b/openspec/specs/project-autonomy/spec.md
@@ -110,3 +110,18 @@ PM SHALL получить один вопрос «Агенты простаив
- **GIVEN** автономность «авто», WIP 1, PAY-1 ждёт PAY-2, PAY-1 выше в бэклоге
- **WHEN** вачдог запускает диспетчер
- **THEN** агент запускается на PAY-2, PAY-1 остаётся в бэклоге до ревью PAY-2
+
+### Requirement: Новый проект берёт стори сам
+Новый проект SHALL создаваться с уровнем автономности «Сам берёт»: диспетчер берёт стори из
+бэклога по порядку доски, результат принимает PM. Пока у проекта нет рабочей подписки,
+диспетчер SHALL NOT запускать стори и беспокоить PM.
+
+#### Scenario: Стори без перетаскивания
+- **GIVEN** новый проект с подключённой подпиской
+- **WHEN** пользователь создаёт стори
+- **THEN** агент берёт её из бэклога сам, карточка переходит «В работу»
+
+#### Scenario: Подписка не подключена
+- **GIVEN** новый проект без подписки и стори в бэклоге
+- **WHEN** проходит тик диспетчера
+- **THEN** стори остаётся в бэклоге, вопросов PM не появляется
diff --git a/packages/core/src/autonomy.ts b/packages/core/src/autonomy.ts
index 48427d8a..ccf3b59a 100644
--- a/packages/core/src/autonomy.ts
+++ b/packages/core/src/autonomy.ts
@@ -32,7 +32,7 @@ export interface AutonomySettings {
quietTo: number | null;
}
-export type AutonomyLevel = "manual" | "assisted" | "auto";
+export type AutonomyLevel = "manual" | "assisted" | "self" | "auto";
const BASE: AutonomySettings = {
pick: "pm",
@@ -53,6 +53,9 @@ export const AUTONOMY_LEVELS: Record = {
manual: BASE,
// The PM still decides, but Peppa pushes when agents idle with a non-empty backlog.
assisted: { ...BASE, idlePush: true },
+ // PEP-79: nobody drags cards — the dispatcher takes stories from the backlog; the PM still
+ // accepts the result. The default of a new project.
+ self: { ...BASE, pick: "auto" },
// Backlog → Done without a human: dispatcher, auto-merge, closing after the merge.
auto: { ...BASE, pick: "auto", merge: "auto", close: "after_merge", idlePush: true },
};
@@ -60,6 +63,7 @@ export const AUTONOMY_LEVELS: Record = {
export const AUTONOMY_LEVEL_RU: Record = {
manual: "Ручной",
assisted: "С подсказками",
+ self: "Сам берёт",
auto: "Автомат",
custom: "Свой",
};
@@ -67,9 +71,13 @@ export const AUTONOMY_LEVEL_RU: Record = {
export const AUTONOMY_LEVEL_HINT: Record = {
manual: "PM двигает карточки и принимает стори; при простое Пеппа молчит.",
assisted: "PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас».",
+ self: "Стори берутся из бэклога сами, по порядку на доске; результат принимаете вы («Принять» в ревью).",
auto: "Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера.",
};
+/** PEP-79: what a newly created project starts with (existing projects keep their settings). */
+export const NEW_PROJECT_AUTONOMY: AutonomySettings = AUTONOMY_LEVELS.self;
+
const key = (projectId: number) => `project.autonomy:${projectId}`;
export function autonomyLevel(s: AutonomySettings): AutonomyLevel | "custom" {
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index dcf895e1..6acd1c38 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -82,7 +82,7 @@ export async function projectAgentWarning(db: Db, projectId: number, now = new D
if (p?.poolId == null) {
// PEP-71/76: a self-registered owner has no machine login — a subscription must be chosen.
const [o] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
- return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не выбрана — владелец выбирает общую или подключает свою в «⋯ Настройки проекта → Подписки»";
+ return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не подключена — владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»";
}
const subs = await poolSubscriptions(db, p.poolId);
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts
index 02823dad..dcb8b267 100644
--- a/packages/runner/src/autonomy.ts
+++ b/packages/runner/src/autonomy.ts
@@ -31,6 +31,7 @@ import {
type SessionView,
type Task,
type TaskRef,
+ projectAgentWarning,
} from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -243,6 +244,8 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
const limited = sessions.some((s) => s.status === "rate_limited") || (await projectPoolExhausted(db, project.id, now));
if (a.pick === "auto") {
+ // PEP-79: no subscription chosen (or none works) — the project page says so; no retries, no pings.
+ if (await projectAgentWarning(db, project.id, now)) return;
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
// PEP-10: stories waiting in runner queues count as taken.
let slots = a.wipLimit - working.length - (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length;
diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts
index 3e9f892f..3e85f600 100644
--- a/packages/runner/src/project-subscription.ts
+++ b/packages/runner/src/project-subscription.ts
@@ -1,8 +1,9 @@
// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
// kept encrypted like every subscription, in the owner's personal pool).
-import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, type Project, type User } from "@peppa/core";
+import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, type Project, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
+import { pendingLogin, pollCodexLogin } from "./subscription-login.ts";
import { addSubscription } from "./subscriptions.ts";
async function requireOwner(db: Db, user: User, project: Project): Promise {
@@ -18,28 +19,64 @@ export async function chooseSharedSubscription(db: Db, user: User, project: Proj
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
}
+export type OwnSubscriptionKind = "claude" | "codex_login" | "codex_key" | "existing";
+
+const OWN_NAMES: Record, string> = { claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
+
/**
- * «Своя подписка»: with a token — a new Claude subscription of the user goes into their own
- * pool (created on first use); without one — the project just moves to the pool they already have.
+ * «Своя подписка» (PEP-76/80): a new subscription of the user goes into their own pool (created on
+ * first use) — Claude by a `claude setup-token` token, ChatGPT by the Codex device login (the
+ * page then shows the link and the one-time code), Codex by an OpenAI API key; "existing" just
+ * moves the project to the pool the user already has.
*/
-export async function connectOwnSubscription(db: Db, user: User, project: Project, token: string): Promise {
+export async function connectOwnSubscription(db: Db, user: User, project: Project, kind: OwnSubscriptionKind, secret = ""): Promise<{ subscriptionId: number | null }> {
await requireOwner(db, user, project);
let pool = await ownPool(db, user.id);
- if (token.trim()) {
+ let subscriptionId: number | null = null;
+ if (kind === "existing") {
+ if (!pool) throw new PeppaError("Своей подписки ещё нет — подключите Claude или ChatGPT");
+ } else {
+ if (kind !== "codex_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API");
const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
- let name = `Claude — ${user.login}`;
- for (let n = 2; taken.has(name); n++) name = `Claude — ${user.login} ${n}`;
- const sub = await addSubscription(db, { provider: "claude", name, method: "token", secret: token, createdBy: user.id });
+ const base = `${OWN_NAMES[kind]} — ${user.login}`;
+ let name = base;
+ for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
+ const sub =
+ kind === "claude"
+ ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id })
+ : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id });
+ subscriptionId = sub.id;
if (pool) {
const cur = (await listPools(db)).find((p) => p.id === pool!.id);
await updatePool(db, pool.id, { subscriptionIds: [...(cur?.subscriptionIds ?? []), sub.id] });
} else {
- pool = await createPool(db, { name: `Claude — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
+ pool = await createPool(db, { name: `Подписки — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
}
- } else if (!pool) {
- throw new PeppaError("Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат");
}
await getPool(db, pool.id);
await setProjectPool(db, project.id, pool.id);
- await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", poolId: pool.id } });
+ await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", kind, poolId: pool.id } });
+ return { subscriptionId };
+}
+
+export interface OwnLogin {
+ subscriptionId: number;
+ name: string;
+ url: string;
+ code: string | null;
+}
+
+/**
+ * Device logins of the pool's subscriptions still waiting for the user (ChatGPT: open the link,
+ * enter the code). Polls Codex first, so a finished login turns the subscription active.
+ */
+export async function ownPendingLogins(db: Db, poolId: number): Promise {
+ const out: OwnLogin[] = [];
+ for (const s of await poolSubscriptions(db, poolId)) {
+ if (s.provider !== "codex" || s.status !== "pending") continue;
+ if ((await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue;
+ const l = await pendingLogin(db, s.id);
+ if (l) out.push({ subscriptionId: s.id, name: s.name, url: l.url, code: l.code ?? null });
+ }
+ return out;
}
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index 741e3d48..c8e511de 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -4,7 +4,7 @@
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { createProject, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
+import { createProject, NEW_PROJECT_AUTONOMY, setAutonomy, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { eq, or } from "drizzle-orm";
@@ -129,6 +129,8 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise log(`ci: ${(e as Error).message}`));
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 18ab2521..c4539939 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -146,7 +146,7 @@ export async function startRunner(
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
// PEP-71: self-registered (eGov) users don't get this machine's login for free.
if (!sub && !sandboxed && !(await mayUseMachineLogin(db, project.ownerId))) {
- throw new PeppaError("Подписка проекта не выбрана — агенты не запустятся. Владелец выбирает общую подписку Пеппы или подключает свою в «⋯ Настройки проекта → Подписки»");
+ throw new PeppaError("Подписка проекта не подключена — агенты не запустятся. Владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»");
}
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError("Для запуска агента в контейнере нужна подписка: добавьте её в пул проекта (раздел «Подписки»)");
diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts
index cb624bf1..0084dc47 100644
--- a/packages/testkit/test/subscriptions.test.ts
+++ b/packages/testkit/test/subscriptions.test.ts
@@ -258,7 +258,7 @@ describe("PEP-76: владелец выбирает подписку проек
const owner = await core.registerEgovUser(db, { iin: "850505400008", name: "ВЫБОРОВ ТЕСТ" });
const stranger = await core.registerEgovUser(db, { iin: "850505400018", name: "ЧУЖОЙ ТЕСТ" });
const p = await core.createProject(db, { slug: "mock-p76", key: "MPSUB", name: "P76", giteaOwner: "x", workspacePath: "/tmp/mock-p76", ownerId: owner.id });
- assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не выбрана/);
+ assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не подключена/);
// No shared pool yet → only the own one is possible.
await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не настроена/);
@@ -271,24 +271,47 @@ describe("PEP-76: владелец выбирает подписку проек
assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
assert.equal(await core.projectAgentWarning(db, p.id), null);
- await assert.rejects(runner.connectOwnSubscription(db, owner, p, ""), /Вставьте токен/);
- await assert.rejects(runner.connectOwnSubscription(db, owner, p, "не токен"), /не похоже на токен/);
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", ""), /Вставьте токен/);
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", "не токен"), /не похоже на токен/);
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 0, "a bad token leaves nothing behind");
- await runner.connectOwnSubscription(db, owner, p, "sk-ant-oat01-" + "b".repeat(40));
+ await assert.rejects(runner.connectOwnSubscription(db, owner, p, "existing"), /ещё нет/);
+ await runner.connectOwnSubscription(db, owner, p, "claude", "sk-ant-oat01-" + "b".repeat(40));
const own = (await core.ownPool(db, owner.id))!;
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
- assert.equal(own.name, `Claude — ${owner.login}`);
+ assert.equal(own.name, `Подписки — ${owner.login}`);
const mine = (await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id);
assert.equal(mine.length, 1);
assert.equal(core.subscriptionSecret(mine[0]!), "sk-ant-oat01-" + "b".repeat(40));
// Back to shared and to own again without a token: the existing pool is reused.
await runner.chooseSharedSubscription(db, owner, p);
- await runner.connectOwnSubscription(db, owner, p, "");
+ await runner.connectOwnSubscription(db, owner, p, "existing");
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 1);
+
+ // PEP-80: ChatGPT by the Codex device login — the subscription waits, the page gets the link and the code.
+ const { subscriptionId } = await runner.connectOwnSubscription(db, owner, p, "codex_login");
+ const logins = await runner.ownPendingLogins(db, own.id);
+ assert.equal(logins.length, 1);
+ assert.equal(logins[0]!.subscriptionId, subscriptionId);
+ assert.match(logins[0]!.url, /^https:\/\//);
+ assert.ok(logins[0]!.code);
+ await runner.cancelLogin(db, subscriptionId!);
} finally {
await core.setSharedPool(db, null);
}
});
+
+ test("PEP-79: «Сам берёт» — диспетчер молчит, пока подписка не подключена", async () => {
+ assert.equal(core.autonomyLevel(core.NEW_PROJECT_AUTONOMY), "self");
+ assert.equal(core.NEW_PROJECT_AUTONOMY.pick, "auto");
+ assert.equal(core.NEW_PROJECT_AUTONOMY.merge, "manual");
+ const owner = await core.registerEgovUser(db, { iin: "850505400028", name: "САМОВ БЕРЁТ" });
+ const p = await core.createProject(db, { slug: "mock-p79", key: "MPSLF", name: "P79", giteaOwner: "x", workspacePath: "/tmp/mock-p79", ownerId: owner.id });
+ await core.setAutonomy(db, p.id, core.NEW_PROJECT_AUTONOMY);
+ const t = await core.createTask(db, { projectId: p.id, title: "первая" });
+ await runner.autonomyTick(db, { log: () => {} });
+ assert.equal((await core.resolveTask(db, t.key)).task.status, "backlog", "not started without a subscription");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "and nobody is pinged about it");
+ });
});
--
2.45.2
From 63576a9845a86df5015dd812dc9b7b4b53bc3bfe 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 21:06:36 +0500
Subject: [PATCH 027/439] PEP-81: epics tab and the epic label on board cards
(WIP, not verified in the browser)
Co-Authored-By: Claude Fable 5.2
---
apps/web/app/(app)/p/[key]/page.tsx | 18 +++++--
apps/web/app/(app)/p/[key]/tabs.tsx | 75 +++++++++++++++++++++++++++++
apps/web/components/Board.tsx | 1 +
3 files changed, 91 insertions(+), 3 deletions(-)
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 16ce033c..006bd07c 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -22,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, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
-import { AgentsMdTab, CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
+import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
import { saveProjectBudgetAction } from "../../actions";
@@ -37,6 +37,7 @@ const RELEASE_STATUS: RecordСоздать стори
);
- const tabCount: Partial> = { board: tasks.length, bugs: incidents.length, sessions: sessions.length };
+ const tabCount: Partial> = { board: tasks.length, epics: epics.length, bugs: incidents.length, sessions: sessions.length };
return (
@@ -412,7 +413,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<>
{epics.length > 0 && (
- Эпик:
+ Эпики:
{[{ id: 0, title: "все" }, ...epics].map((e) => {
const active = (epicFilter?.id ?? 0) === e.id;
return (
@@ -443,6 +444,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
>
)}
+ {tab === "epics" && (
+ ({ key: `${p.key}-${t.number}`, title: t.title, status: t.status, goalId: t.goalId }))}
+ progress={progress}
+ back={back}
+ />
+ )}
+
{tab === "code" && code && }
{tab === "specs" && (
diff --git a/apps/web/app/(app)/p/[key]/tabs.tsx b/apps/web/app/(app)/p/[key]/tabs.tsx
index 24bcc62b..bcf057be 100644
--- a/apps/web/app/(app)/p/[key]/tabs.tsx
+++ b/apps/web/app/(app)/p/[key]/tabs.tsx
@@ -312,3 +312,78 @@ const AGENTS_MD_STARTER = `# AGENTS.md
- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
`;
+
+interface EpicStory {
+ key: string;
+ title: string;
+ status: string;
+ goalId: number | null;
+}
+
+/** PEP-81: epics in plain sight — each epic (a big goal) with its stories (the steps agents do). */
+export function EpicsTab({ projectId, projectKey, epics, stories, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; stories: EpicStory[]; progress: Map; back: string }) {
+ const loose = stories.filter((s) => !s.goalId || !epics.some((e) => e.id === s.goalId));
+ const list = (items: EpicStory[]) =>
+ items.length ? (
+
+ {items.map((s) => (
+
+ {s.key}
+ {s.title}
+
+
+ ))}
+
+ ) : (
+ Стори пока нет.
+ );
+ return (
+
+ );
+}
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index 248c244b..de1fc025 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -198,6 +198,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
)}
{card.epic && (
+ эпик
{card.epic}
)}
--
2.45.2
From 1afc95117dea6694fcb879eaaf23dbf0f943028b 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 21:09:42 +0500
Subject: [PATCH 028/439] =?UTF-8?q?PEP-82:=20connect=20your=20own=20Claude?=
=?UTF-8?q?=20or=20ChatGPT=20on=20the=20project=20page=20=E2=80=94=20a=20l?=
=?UTF-8?q?ink=20and=20a=20code,=20no=20terminal?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 22 ++++-
apps/web/app/(app)/help/page.tsx | 2 +-
apps/web/app/(app)/p/[key]/page.tsx | 27 ++----
apps/web/components/SubscriptionSetup.tsx | 90 +++++++++++++++++++
.../proposal.md | 15 ++++
.../specs/agent-credentials/spec.md | 20 +++++
.../tasks.md | 3 +
openspec/specs/agent-credentials/spec.md | 19 ++++
packages/runner/src/project-subscription.ts | 57 +++++++++---
packages/testkit/test/subscriptions.test.ts | 27 ++++++
11 files changed, 247 insertions(+), 36 deletions(-)
create mode 100644 apps/web/components/SubscriptionSetup.tsx
create mode 100644 openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index f813325a..7b2facdf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -39,6 +39,7 @@
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
+- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 39782563..a3c00ac2 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -56,7 +56,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -673,9 +673,25 @@ export async function connectOwnSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const kind = str(f, "kind") as OwnSubscriptionKind;
- if (!["claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
+ if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
- return `/p/${p.key}?settings=subscription`;
+ });
+}
+
+/** PEP-82: step 3 of the Claude sign-in on the project page. */
+export async function finishOwnClaudeLoginAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"));
+ });
+}
+
+export async function cancelOwnLoginAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await cancelOwnLogin(db, user, p, Number(str(f, "subscriptionId")));
});
}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 5763b9d9..32b54396 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -70,7 +70,7 @@ export default async function Help() {
Клавиатура — ⌘K (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — Горячие клавиши (или ? ).
Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
- Подписка проекта — на чём работают агенты. Владелец подключает свою в «⋯ Настройки проекта → Подписки»: Claude (токен команды claude setup-token ), ChatGPT (вход по ссылке и коду) или ключ OpenAI API. Пока подписки нет, агенты проекта не запускаются.
+ Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 8119e0a9..7b5dfc47 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -17,6 +17,7 @@ import { Input, NativeSelect, Textarea } from "@/components/ui/input";
import { SettingsDialog } from "@/components/SettingsDialog";
import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
import { Workspace } from "@/components/Workspace";
+import { SubscriptionSetup } from "@/components/SubscriptionSetup";
import { requireUser } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
@@ -311,32 +312,19 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Общая подписка Пеппы
)}
- {ownLogins.map((l) => (
-
-
Вход в ChatGPT не завершён
-
- 1. Откройте {l.url} и войдите в свой ChatGPT.
-
- {l.code && (
-
- 2. Введите код {l.code}
-
- )}
-
Потом обновите эту страницу — подписка станет активной.
-
- ))}
-
- Claude — токен (claude setup-token)
+
+ Claude — вход по ссылке
ChatGPT — вход по ссылке и коду
+ Claude — готовый токен (claude setup-token)
Codex — ключ OpenAI API
{hasOwnPool && Моя уже подключённая подписка }
-
+
Подключить свою подписку
- Claude: выполните claude setup-token на своём компьютере и вставьте токен. ChatGPT: поле оставьте пустым — появится ссылка и код для входа. Токены и ключи
+ Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт claude setup-token на вашем компьютере. Токены и ключи
хранятся зашифрованными, показать их нельзя.
@@ -408,7 +396,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{repo.fullName} · {repoVisibilityLabel(repo.private)}
- {agentWarning && (
+ {mayChoose && (ownLogins.length > 0 || (!pool && agentWarning)) && }
+ {agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool)) && (
Агенты не запустятся: {agentWarning}.
{pool ? (superadmin ? Подписки → : Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её. ) : null}
diff --git a/apps/web/components/SubscriptionSetup.tsx b/apps/web/components/SubscriptionSetup.tsx
new file mode 100644
index 00000000..39db9d06
--- /dev/null
+++ b/apps/web/components/SubscriptionSetup.tsx
@@ -0,0 +1,90 @@
+import { ExternalLink } from "lucide-react";
+import type { OwnLogin } from "@peppa/runner";
+import { cancelOwnLoginAction, connectOwnSubscriptionAction, finishOwnClaudeLoginAction } from "@/app/(app)/actions";
+import { Hidden } from "@/components/cards";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+
+const step = "flex gap-2.5";
+const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary";
+
+/**
+ * PEP-82: connecting the owner's own subscription without a terminal, in plain steps, right on
+ * the project page — «Подключить Claude» / «Подключить ChatGPT», then the link and the code.
+ */
+export function SubscriptionSetup({ projectId, back, logins }: { projectId: number; back: string; logins: OwnLogin[] }) {
+ if (logins.length) {
+ return (
+
+ {logins.map((l) => (
+
+ Подключаем {l.provider === "claude" ? "Claude" : "ChatGPT"} — осталось {l.provider === "claude" ? "три шага" : "два шага"}
+
+
1
+
+
Откройте страницу входа и войдите в свой аккаунт {l.provider === "claude" ? "Claude" : "ChatGPT"}{l.provider === "claude" ? ", затем нажмите «Authorize»" : ""}.
+
+
+ Открыть страницу входа
+
+
+
+
+ {l.provider === "claude" ? (
+ <>
+
+ 2
+ Claude покажет длинный код — нажмите «Copy code».
+
+
+ 3
+
+
+
+ Готово
+
+
+ >
+ ) : (
+
+ )}
+
+
+ Отменить и начать заново
+
+
+ ))}
+
+ );
+ }
+ return (
+
+ Подключите подписку — и агенты начнут работать
+
+ Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Это одна минута: вы входите в свой аккаунт, как на любом сайте. Пароль
+ Пеппа не видит.
+
+
+
+
+ Подключить Claude
+
+
+
+ Подключить ChatGPT
+
+
+ Нет подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) — в «⋯ Настройки проекта → Подписки».
+
+ );
+}
diff --git a/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md
new file mode 100644
index 00000000..8141c478
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/proposal.md
@@ -0,0 +1,15 @@
+# PEP-82: подключение своей подписки понятно непрограммисту
+
+## Why
+Новый пользователь не понимает, как подключить свою подписку Claude: форма спрятана в настройках проекта и просит токен
+команды `claude setup-token`, то есть требует терминал и установленный Claude Code.
+
+## What Changes
+- Вход в Claude без терминала: вид подписки `claude_login` — Пеппа сама запускает `claude setup-token` на сервере и даёт
+ ссылку; пользователь входит в свой Claude, копирует код и вставляет его (`finishOwnClaudeLogin`). «Отменить и начать заново» —
+ `cancelOwnLogin` (последняя ожидающая подписка ушла — проект снова без пула).
+- Мастер `SubscriptionSetup` прямо на странице проекта вместо предупреждения «Агенты не запустятся», когда подписки нет:
+ «Подключить Claude» / «Подключить ChatGPT», затем шаги со ссылкой и кодом. Видят владелец и суперадмин.
+- `ownPendingLogins` отдаёт и входы Claude; форма в «⋯ Настройки проекта → Подписки» остаётся для готового токена и ключа API.
+
+Вне scope: вставка кода за пользователя, подписки OpenCode. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..ff0bfe66
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/specs/agent-credentials/spec.md
@@ -0,0 +1,20 @@
+## ADDED Requirements
+
+### Requirement: Подключение подписки без терминала
+Страница проекта без подписки SHALL показывать владельцу мастер подключения: кнопки
+«Подключить Claude» и «Подключить ChatGPT» и дальше шаги со ссылкой на вход. Для Claude
+пользователь SHALL завершать вход кодом, который Claude показывает после входа.
+
+#### Scenario: Claude по ссылке
+- **GIVEN** проект нового пользователя без подписки
+- **WHEN** владелец нажимает «Подключить Claude», открывает ссылку, входит и вставляет код в мастер
+- **THEN** подписка активна, мастер исчезает, агенты проекта могут запускаться
+
+#### Scenario: Отмена
+- **GIVEN** вход начат, код ещё не введён
+- **WHEN** владелец нажимает «Отменить и начать заново»
+- **THEN** ожидающая подписка удалена, мастер снова предлагает подключить Claude или ChatGPT
+
+#### Scenario: Чужой код
+- **WHEN** код для входа пытается ввести не владелец проекта и не суперадмин
+- **THEN** действие отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md
new file mode 100644
index 00000000..42dc77e9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-82-subscription-setup-wizard/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `claude_login`, `finishOwnClaudeLogin`, `cancelOwnLogin`, входы Claude в `ownPendingLogins`
+- [x] 2 Мастер `SubscriptionSetup` на странице проекта
+- [x] 3 Тест в `subscriptions.test.ts`, проверка в браузере и первого шага с настоящим Claude, `openspec validate`
diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md
index c586dae1..585bd2ec 100644
--- a/openspec/specs/agent-credentials/spec.md
+++ b/openspec/specs/agent-credentials/spec.md
@@ -139,3 +139,22 @@ Claude и делать пул с этой подпиской пулом по у
#### Scenario: Пустой токен Claude
- **WHEN** владелец выбирает Claude и не вставляет токен
- **THEN** подключение отклонено с подсказкой про `claude setup-token`
+
+### Requirement: Подключение подписки без терминала
+Страница проекта без подписки SHALL показывать владельцу мастер подключения: кнопки
+«Подключить Claude» и «Подключить ChatGPT» и дальше шаги со ссылкой на вход. Для Claude
+пользователь SHALL завершать вход кодом, который Claude показывает после входа.
+
+#### Scenario: Claude по ссылке
+- **GIVEN** проект нового пользователя без подписки
+- **WHEN** владелец нажимает «Подключить Claude», открывает ссылку, входит и вставляет код в мастер
+- **THEN** подписка активна, мастер исчезает, агенты проекта могут запускаться
+
+#### Scenario: Отмена
+- **GIVEN** вход начат, код ещё не введён
+- **WHEN** владелец нажимает «Отменить и начать заново»
+- **THEN** ожидающая подписка удалена, мастер снова предлагает подключить Claude или ChatGPT
+
+#### Scenario: Чужой код
+- **WHEN** код для входа пытается ввести не владелец проекта и не суперадмин
+- **THEN** действие отклонено
diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts
index 3e85f600..f223a111 100644
--- a/packages/runner/src/project-subscription.ts
+++ b/packages/runner/src/project-subscription.ts
@@ -1,9 +1,9 @@
// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
// kept encrypted like every subscription, in the owner's personal pool).
-import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, type Project, type User } from "@peppa/core";
+import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, projectPool, type Project, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
-import { pendingLogin, pollCodexLogin } from "./subscription-login.ts";
+import { finishClaudeLogin, pendingLogin, pollCodexLogin, removeSubscription } from "./subscription-login.ts";
import { addSubscription } from "./subscriptions.ts";
async function requireOwner(db: Db, user: User, project: Project): Promise {
@@ -19,9 +19,9 @@ export async function chooseSharedSubscription(db: Db, user: User, project: Proj
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
}
-export type OwnSubscriptionKind = "claude" | "codex_login" | "codex_key" | "existing";
+export type OwnSubscriptionKind = "claude_login" | "claude" | "codex_login" | "codex_key" | "existing";
-const OWN_NAMES: Record, string> = { claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
+const OWN_NAMES: Record, string> = { claude_login: "Claude", claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
/**
* «Своя подписка» (PEP-76/80): a new subscription of the user goes into their own pool (created on
@@ -36,15 +36,17 @@ export async function connectOwnSubscription(db: Db, user: User, project: Projec
if (kind === "existing") {
if (!pool) throw new PeppaError("Своей подписки ещё нет — подключите Claude или ChatGPT");
} else {
- if (kind !== "codex_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API");
+ if (kind !== "codex_login" && kind !== "claude_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API");
const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
const base = `${OWN_NAMES[kind]} — ${user.login}`;
let name = base;
for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
const sub =
- kind === "claude"
- ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id })
- : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id });
+ kind === "claude_login"
+ ? await addSubscription(db, { provider: "claude", name, method: "login", createdBy: user.id })
+ : kind === "claude"
+ ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id })
+ : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id });
subscriptionId = sub.id;
if (pool) {
const cur = (await listPools(db)).find((p) => p.id === pool!.id);
@@ -61,22 +63,51 @@ export async function connectOwnSubscription(db: Db, user: User, project: Projec
export interface OwnLogin {
subscriptionId: number;
+ provider: "claude" | "codex";
name: string;
url: string;
+ /** ChatGPT: the one-time code to enter on the page behind the link. */
code: string | null;
}
/**
- * Device logins of the pool's subscriptions still waiting for the user (ChatGPT: open the link,
- * enter the code). Polls Codex first, so a finished login turns the subscription active.
+ * Sign-ins of the pool's subscriptions still waiting for the user. Claude: open the link, sign
+ * in, paste the code Claude shows (`finishOwnClaudeLogin`). ChatGPT: open the link and enter the
+ * code — Codex is polled first, so a finished login turns the subscription active.
*/
export async function ownPendingLogins(db: Db, poolId: number): Promise {
const out: OwnLogin[] = [];
for (const s of await poolSubscriptions(db, poolId)) {
- if (s.provider !== "codex" || s.status !== "pending") continue;
- if ((await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue;
+ if (s.status !== "pending" || s.provider === "opencode") continue;
+ if (s.provider === "codex" && (await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue;
const l = await pendingLogin(db, s.id);
- if (l) out.push({ subscriptionId: s.id, name: s.name, url: l.url, code: l.code ?? null });
+ if (l) out.push({ subscriptionId: s.id, provider: s.provider, name: s.name, url: l.url, code: l.code ?? null });
}
return out;
}
+
+/** The user's own pending subscription of the project's pool, or an error. */
+async function ownPendingSubscription(db: Db, user: User, project: Project, subscriptionId: number) {
+ await requireOwner(db, user, project);
+ const pool = await projectPool(db, project.id);
+ const sub = pool ? (await poolSubscriptions(db, pool.id)).find((s) => s.id === subscriptionId) : undefined;
+ if (!sub || (sub.createdBy !== user.id && !(await isSuperadmin(db, user)))) throw new PeppaError("Подписка не найдена");
+ return sub;
+}
+
+/** Step 3 of the Claude sign-in: the code Claude showed after the user signed in. */
+export async function finishOwnClaudeLogin(db: Db, user: User, project: Project, subscriptionId: number, code: string): Promise {
+ const sub = await ownPendingSubscription(db, user, project, subscriptionId);
+ if (sub.provider !== "claude") throw new PeppaError("Код нужен только для Claude");
+ await finishClaudeLogin(db, sub.id, code);
+}
+
+/** «Отмена» of a sign-in that was not finished: the pending subscription goes away. */
+export async function cancelOwnLogin(db: Db, user: User, project: Project, subscriptionId: number): Promise {
+ const sub = await ownPendingSubscription(db, user, project, subscriptionId);
+ if (sub.status !== "pending") throw new PeppaError("Эта подписка уже подключена");
+ await removeSubscription(db, sub.id);
+ const pool = await projectPool(db, project.id);
+ // The last one is gone: back to "no subscription", so the page offers to connect again.
+ if (pool && !(await poolSubscriptions(db, pool.id)).length && pool.createdBy === user.id) await setProjectPool(db, project.id, null);
+}
diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts
index 0084dc47..c57ce0a8 100644
--- a/packages/testkit/test/subscriptions.test.ts
+++ b/packages/testkit/test/subscriptions.test.ts
@@ -302,6 +302,33 @@ describe("PEP-76: владелец выбирает подписку проек
}
});
+ test("PEP-82: вход в Claude по ссылке и коду на странице проекта, без терминала", async () => {
+ const owner = await core.registerEgovUser(db, { iin: "850505400038", name: "ССЫЛКИН ВХОД" });
+ const stranger = await core.registerEgovUser(db, { iin: "850505400048", name: "ПОСТОРОННИЙ ВХОД" });
+ const p = await core.createProject(db, { slug: "mock-p82", key: "MPLNK", name: "P82", giteaOwner: "x", workspacePath: "/tmp/mock-p82", ownerId: owner.id });
+ const { subscriptionId } = await runner.connectOwnSubscription(db, owner, p, "claude_login");
+ const pool = (await core.projectPool(db, p.id))!;
+ const [l] = await runner.ownPendingLogins(db, pool.id);
+ assert.equal(l!.subscriptionId, subscriptionId);
+ assert.equal(l!.provider, "claude");
+ assert.match(l!.url, /^https:\/\//);
+ assert.match((await core.projectAgentWarning(db, p.id))!, /не подключена/, "pending is not working yet");
+
+ await assert.rejects(runner.finishOwnClaudeLogin(db, stranger, p, subscriptionId!, "mock-good-1"), /владелец/);
+ await runner.finishOwnClaudeLogin(db, owner, p, subscriptionId!, "mock-good-1");
+ assert.equal((await core.getSubscription(db, subscriptionId!)).status, "active");
+ assert.equal(await core.projectAgentWarning(db, p.id), null);
+ assert.deepEqual(await runner.ownPendingLogins(db, pool.id), []);
+ await assert.rejects(runner.cancelOwnLogin(db, owner, p, subscriptionId!), /уже подключена/);
+
+ // «Отменить и начать заново»: a pending sign-in goes away; with nothing left the project is unassigned.
+ const p2 = await core.createProject(db, { slug: "mock-p82b", key: "MPLNB", name: "P82b", giteaOwner: "x", workspacePath: "/tmp/mock-p82b", ownerId: stranger.id });
+ const second = await runner.connectOwnSubscription(db, stranger, p2, "claude_login");
+ await runner.cancelOwnLogin(db, stranger, p2, second.subscriptionId!);
+ assert.equal(await core.projectPool(db, p2.id), null);
+ assert.equal((await core.listSubscriptions(db)).some((s) => s.id === second.subscriptionId), false);
+ });
+
test("PEP-79: «Сам берёт» — диспетчер молчит, пока подписка не подключена", async () => {
assert.equal(core.autonomyLevel(core.NEW_PROJECT_AUTONOMY), "self");
assert.equal(core.NEW_PROJECT_AUTONOMY.pick, "auto");
--
2.45.2
From efe411f94ea34b916354905b6105a3ea038e2485 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 21:17:07 +0500
Subject: [PATCH 029/439] PEP-81: archive the change; epics tab verified in the
browser
Co-Authored-By: Claude Fable 5.2
---
.../2026-11-14-pep-81-epics-in-sight/proposal.md | 11 +++++++++++
.../specs/web-workspace/spec.md | 16 ++++++++++++++++
.../2026-11-14-pep-81-epics-in-sight/tasks.md | 3 +++
openspec/specs/web-workspace/spec.md | 15 +++++++++++++++
4 files changed, 45 insertions(+)
create mode 100644 openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md
diff --git a/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md
new file mode 100644
index 00000000..5a7fea30
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/proposal.md
@@ -0,0 +1,11 @@
+# PEP-81: эпики на виду
+
+## Why
+Пользователи не понимают, где эпик, а где стори: эпики были видны только строкой фильтра над доской и в «⋯ Настройки проекта».
+
+## What Changes
+- Вкладка «Эпики» в проекте (`EpicsTab`): пояснение «эпик — большая цель, стори — шаг к ней», форма «Добавить эпик»,
+ по карточке на эпик (описание, прогресс «готово N из M», его стори со статусами, «На доске», «Спланировать стори»), блок «Стори без эпика».
+- На карточке доски метка эпика подписана «эпик»; «Эпики:» над доской ведёт на вкладку.
+
+Вне scope: группировка доски по эпикам. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md
new file mode 100644
index 00000000..53a84ce2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/specs/web-workspace/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Вкладка «Эпики»
+Страница проекта SHALL иметь вкладку «Эпики»: объяснение, чем эпик отличается от стори,
+и каждый открытый эпик с описанием, прогрессом и списком его стори; стори без эпика
+показаны отдельным блоком. На карточке доски эпик стори SHALL быть подписан словом «эпик».
+
+#### Scenario: Эпик и его стори
+- **GIVEN** эпик «Оплата» с тремя стори, одна из них готова
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** он видит «Оплата», «готово 1 из 3» и три стори со статусами
+
+#### Scenario: Стори без эпика
+- **GIVEN** стори, не привязанная к эпику
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** стори показана в блоке «Стори без эпика»
diff --git a/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md
new file mode 100644
index 00000000..5db5adc0
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-81-epics-in-sight/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 Вкладка «Эпики» со стори каждого эпика
+- [x] 2 Подпись «эпик» на карточках доски, ссылка «Эпики:»
+- [x] 3 Проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 34794b34..12bfb664 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -401,3 +401,18 @@ PM SHALL уметь убрать стори в архив и вернуть её
#### Scenario: Обычный пользователь
- **WHEN** Главную открывает пользователь без прав суперадмина
- **THEN** блока «Проекты других» нет
+
+### Requirement: Вкладка «Эпики»
+Страница проекта SHALL иметь вкладку «Эпики»: объяснение, чем эпик отличается от стори,
+и каждый открытый эпик с описанием, прогрессом и списком его стори; стори без эпика
+показаны отдельным блоком. На карточке доски эпик стори SHALL быть подписан словом «эпик».
+
+#### Scenario: Эпик и его стори
+- **GIVEN** эпик «Оплата» с тремя стори, одна из них готова
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** он видит «Оплата», «готово 1 из 3» и три стори со статусами
+
+#### Scenario: Стори без эпика
+- **GIVEN** стори, не привязанная к эпику
+- **WHEN** участник открывает вкладку «Эпики»
+- **THEN** стори показана в блоке «Стори без эпика»
--
2.45.2
From 27e43b1ea6a5741e597c7f93334a841d78173bd4 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 22:21:54 +0500
Subject: [PATCH 030/439] PEP-83: the login page says why the factory; first
steps for a product manager
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/login/page.tsx | 90 +++++++++++++++++--
apps/web/components/Onboarding.tsx | 80 ++++++++++-------
.../proposal.md | 14 +++
.../specs/onboarding/spec.md | 26 ++++++
.../tasks.md | 4 +
openspec/specs/onboarding/spec.md | 25 ++++++
packages/core/src/onboarding.ts | 86 +++++++++++++++---
packages/testkit/test/agent-smarts.test.ts | 15 ++--
9 files changed, 286 insertions(+), 55 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index 7b2facdf..b847bbb2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -62,6 +62,7 @@
- **Расход, бюджеты, метрики, журнал (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` сверен с 2.1.323 (PEP-3: `context_window.total_*_tokens` — последний запрос, не сумма; токены только из transcript), `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; у клиентов 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-83)**: `/login` — зачем фабрика, пять шагов, что понадобится, вход справа (на телефоне: заголовок → вход → подробности); шаги `onboardingChecklist` для обычного пользователя: telegram → project → subscription (нет `projectAgentWarning` хотя бы у одного проекта) → story → started → accepted (первая `done`), у шага `action` — подпись кнопки; суперадмину subscription первым; тексты для непрограммиста
- **Онбординг (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/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index 58bccf1f..9020612e 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -1,26 +1,104 @@
import { redirect } from "next/navigation";
+import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
import { currentUser, safeNext } from "@/lib/auth";
import { Brand } from "@/components/Brand";
import { Flash } from "@/components/common";
import { EgovSign } from "@/components/EgovSign";
import { Footer } from "@/components/Footer";
+import { PugMascot } from "@/components/PugMascot";
export const dynamic = "force-dynamic";
-/** PEP-71: eGov QR is the only way in; the first login registers the account. */
+const WHY = [
+ { title: "Программировать не нужно", text: "Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты." },
+ { title: "Всё на виду", text: "Доска показывает, что в работе, что готово и какой агент чем занят. Никаких «спросите у разработчиков»." },
+ { title: "Последнее слово за вами", text: "Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять»." },
+];
+
+const STEPS = [
+ { title: "Войдите с ноутбука", text: "Через eGov QR — учётка создаётся сама, пароль не нужен." },
+ { title: "Привяжите Telegram-бота", text: "Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова." },
+ { title: "Создайте проект и подключите подписку", text: "Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута." },
+ { title: "Опишите задачу словами", text: "«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам." },
+ { title: "Примите результат", text: "Придёт сообщение «готово». Посмотрите и нажмите «Принять» — или напишите, что поправить." },
+];
+
+const NEED = [
+ { icon: Laptop, text: "Ноутбук — управлять фабрикой удобнее с большого экрана" },
+ { icon: ShieldCheck, text: "eGov Mobile на телефоне — для входа" },
+ { icon: MessageCircle, text: "Telegram — туда приходят вопросы агентов и «готово»" },
+ { icon: Sparkles, text: "Платная подписка Claude или ChatGPT — на ней работают агенты" },
+];
+
+/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) {
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
return (
-
-
-
-
Софтвейр-фабрика: проекты в Gitea, стори по OpenSpec, агенты Claude Code и Codex.
+
+ {/* Phone: headline → sign-in → details. Laptop: text on the left, sign-in sticks on the right. */}
+
+
+ Опишите идею словами — команда ИИ-агентов сделает продукт
+
+ Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.
+
+
+
+
+
+ Начать — одна минута
+ Вход через eGov. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.
- Первый вход сразу создаёт учётку по вашему ИИН. На телефоне вход открывает eGov Mobile, QR не нужен.
+ Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.
+
+
+
+
+ Зачем это вам
+
+ {WHY.map((w) => (
+
+
+ {w.title}
+
+ {w.text}
+
+ ))}
+
+
+
+
+ Как это работает — пять шагов
+
+ {STEPS.map((s, i) => (
+
+
+ {i + 1}
+
+
+ {s.title}
+ {s.text}
+
+
+ ))}
+
+
+
+
+ Что понадобится
+
+ {NEED.map((n) => (
+
+ {n.text}
+
+ ))}
+
+
+
);
}
diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx
index 03179740..e9959ceb 100644
--- a/apps/web/components/Onboarding.tsx
+++ b/apps/web/components/Onboarding.tsx
@@ -1,5 +1,6 @@
-// PEP-31: first-run checklist on the home page.
-import { CircleCheck, Circle, X } from "lucide-react";
+// PEP-31/83: the first steps on the home page — for a product manager: what to do and why, in
+// order, with one button on the current step.
+import { ArrowRight, Check, X } from "lucide-react";
import type { Onboarding } from "@peppa/core";
import { dismissOnboardingAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
@@ -8,44 +9,61 @@ import { cn } from "@/lib/utils";
export function OnboardingChecklist({ data }: { data: Onboarding }) {
const next = data.steps.find((s) => !s.done && !s.optional);
+ const fresh = data.done === 0;
return (
-
-
-
Первый запуск
-
- {data.done} из {data.total}
-
-
-
+
);
diff --git a/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md
new file mode 100644
index 00000000..466b3e6b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/proposal.md
@@ -0,0 +1,14 @@
+# PEP-83: вход и первый запуск для продактов
+
+## Why
+Пеппой пользуются продакт-менеджеры, которые не знают, что такое софтвер-фабрика. Страница входа не объясняла, зачем она нужна,
+а чек-лист «Первый запуск» был написан для программиста и не вёл по шагам. Управляют они с ноутбука, а отвечают агентам через Telegram.
+
+## What Changes
+- Страница входа: заголовок-обещание, «Зачем это вам» (3 причины), «Как это работает — пять шагов», «Что понадобится» (ноутбук,
+ eGov Mobile, Telegram, подписка Claude или ChatGPT), блок входа с мопсом. На телефоне порядок: заголовок → вход → подробности.
+- Первый запуск на Главной: шесть шагов для продакта — Telegram → проект → своя подписка → первая задача → агент взял в работу →
+ принять результат. У шага — объяснение «зачем» и кнопка на текущем шаге (`OnboardingStep.action`). Шаг eGov убран (вход и так
+ через eGov); новый шаг `accepted`; шаг `subscription` у обычного пользователя — «проект готов запускать агентов».
+
+Вне scope: обучающее видео, тур по интерфейсу. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md
new file mode 100644
index 00000000..9fb53bf6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/specs/onboarding/spec.md
@@ -0,0 +1,26 @@
+## ADDED Requirements
+
+### Requirement: Страница входа объясняет фабрику
+Страница входа SHALL до входа объяснять простым языком, зачем нужна фабрика, как она
+работает по шагам и что понадобится (ноутбук, eGov Mobile, Telegram, подписка Claude или
+ChatGPT). На телефоне заголовок SHALL идти перед блоком входа.
+
+#### Scenario: Новый человек
+- **WHEN** человек без сессии открывает Пеппу
+- **THEN** он видит обещание продукта, три причины «зачем», пять шагов «как» и кнопку «Войти через eGov»
+
+### Requirement: Пошаговый старт для продакта
+Главная нового пользователя SHALL показывать шаги: привязать Telegram, создать проект,
+подключить свою подписку, описать первую задачу, агент взял задачу, принять результат —
+с объяснением каждого шага и кнопкой действия на текущем. Блок скрывается после первой
+принятой стори или по кнопке «Скрыть».
+
+#### Scenario: Первый вход
+- **GIVEN** пользователь только что зарегистрировался
+- **WHEN** он открывает Главную
+- **THEN** текущий шаг — «Привяжите Telegram» с кнопкой «Привязать Telegram», сделано 0 из 6
+
+#### Scenario: Первая принятая стори
+- **GIVEN** пользователь прошёл пять шагов
+- **WHEN** он принимает первую стори
+- **THEN** блок шагов больше не показывается
diff --git a/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md
new file mode 100644
index 00000000..43c3d628
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-83-product-manager-entry/tasks.md
@@ -0,0 +1,4 @@
+- [x] 1 Шаги онбординга в core: порядок, тексты, `action`, `accepted`, подписка обычного пользователя
+- [x] 2 Компонент шагов на Главной
+- [x] 3 Страница входа
+- [x] 4 Тест `agent-smarts.test.ts`, проверка в браузере (ноутбук и телефон), `openspec validate`
diff --git a/openspec/specs/onboarding/spec.md b/openspec/specs/onboarding/spec.md
index e5e31cca..807ea738 100644
--- a/openspec/specs/onboarding/spec.md
+++ b/openspec/specs/onboarding/spec.md
@@ -28,3 +28,28 @@
- **GIVEN** у проекта PAY пул с одной подпиской в статусе `auth_error`
- **WHEN** участник открывает проект
- **THEN** над вкладками плашка «Агенты не запустятся» с причиной
+
+### Requirement: Страница входа объясняет фабрику
+Страница входа SHALL до входа объяснять простым языком, зачем нужна фабрика, как она
+работает по шагам и что понадобится (ноутбук, eGov Mobile, Telegram, подписка Claude или
+ChatGPT). На телефоне заголовок SHALL идти перед блоком входа.
+
+#### Scenario: Новый человек
+- **WHEN** человек без сессии открывает Пеппу
+- **THEN** он видит обещание продукта, три причины «зачем», пять шагов «как» и кнопку «Войти через eGov»
+
+### Requirement: Пошаговый старт для продакта
+Главная нового пользователя SHALL показывать шаги: привязать Telegram, создать проект,
+подключить свою подписку, описать первую задачу, агент взял задачу, принять результат —
+с объяснением каждого шага и кнопкой действия на текущем. Блок скрывается после первой
+принятой стори или по кнопке «Скрыть».
+
+#### Scenario: Первый вход
+- **GIVEN** пользователь только что зарегистрировался
+- **WHEN** он открывает Главную
+- **THEN** текущий шаг — «Привяжите Telegram» с кнопкой «Привязать Telegram», сделано 0 из 6
+
+#### Scenario: Первая принятая стори
+- **GIVEN** пользователь прошёл пять шагов
+- **WHEN** он принимает первую стори
+- **THEN** блок шагов больше не показывается
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index 6acd1c38..d92056f6 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -7,12 +7,14 @@ 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 type OnboardingStepId = "subscription" | "telegram" | "project" | "story" | "started" | "accepted";
export interface OnboardingStep {
id: OnboardingStepId;
title: string;
hint: string;
+ /** Button label of the step while it is the current one (PEP-83). */
+ action: string;
href: string;
done: boolean;
optional: boolean;
@@ -45,25 +47,83 @@ export async function onboardingChecklist(db: Db, user: Pick
0,
+ optional: false,
+ };
+ let subscription: OnboardingStep;
if (admin) {
const subs = await db.select({ status: subscriptions.status, limitedUntil: subscriptions.limitedUntil }).from(subscriptions);
- steps.push({
+ subscription = {
id: "subscription",
- title: "Подключить подписку агента",
- hint: "Claude, Codex или OpenCode — на ней работают агенты; добавь её в пул проекта.",
+ title: "Подключите подписку агента",
+ hint: "Claude, Codex или OpenCode — на ней работают агенты; добавьте её в пул проекта.",
+ action: "Открыть подписки",
href: "/subscriptions",
done: subs.some((s) => s.status === "active" || s.status === "limited"),
optional: false,
- });
+ };
+ } else {
+ let ready = false;
+ for (const id of ids) if (!(await projectAgentWarning(db, id))) ready = true;
+ subscription = {
+ id: "subscription",
+ title: "Подключите свою подписку Claude или ChatGPT",
+ hint: "На ней агенты пишут код. Подойдёт обычная платная подписка; подключение — одна минута, кнопка на странице проекта.",
+ action: "Подключить подписку",
+ href: projectHref,
+ done: ready,
+ 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 rest: OnboardingStep[] = [
+ {
+ id: "story",
+ title: "Опишите первую задачу",
+ hint: "Кнопка «+ Стори» в проекте. Напишите обычными словами, что должно получиться, — как объяснили бы человеку.",
+ action: "Написать задачу",
+ href: projectHref,
+ done: storyCount > 0,
+ optional: false,
+ },
+ {
+ id: "started",
+ title: "Агент берёт задачу в работу",
+ hint: "В новом проекте это происходит само за минуту; на карточке появятся имя агента и прогресс. Ничего перетаскивать не нужно.",
+ action: "Открыть доску",
+ href: projectHref,
+ done: started > 0,
+ optional: false,
+ },
+ {
+ id: "accepted",
+ title: "Посмотрите результат и нажмите «Принять»",
+ hint: "Когда агент закончит, придёт сообщение, а карточка перейдёт в «Ревью». Что-то не так — напишите комментарий, агент переделает.",
+ action: "Открыть доску",
+ href: projectHref,
+ done: accepted > 0,
+ optional: false,
+ },
+ ];
+ const steps: OnboardingStep[] = admin ? [subscription, telegram, project, ...rest] : [telegram, project, subscription, ...rest];
const required = steps.filter((s) => !s.optional);
const done = required.filter((s) => s.done).length;
const complete = done === required.length;
diff --git a/packages/testkit/test/agent-smarts.test.ts b/packages/testkit/test/agent-smarts.test.ts
index 51bedc13..2edb0669 100644
--- a/packages/testkit/test/agent-smarts.test.ts
+++ b/packages/testkit/test/agent-smarts.test.ts
@@ -173,27 +173,32 @@ 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 });
+ assert.deepEqual(ob.steps.map((s) => s.id), ["telegram", "project", "subscription", "story", "started", "accepted"], "PEP-83: a product manager's path");
+ assert.deepEqual({ done: ob.done, total: ob.total, visible: ob.visible }, { done: 0, total: 6, visible: true });
+ assert.ok(ob.steps.every((s) => s.action && s.hint), "every step says what to do");
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.deepEqual(ob.steps.filter((s) => s.done).map((s) => s.id), ["telegram", "project", "subscription", "story"], "a Gitea-era owner may run without a pool");
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 });
+ assert.deepEqual({ done: ob.done, complete: ob.complete, visible: ob.visible }, { done: 5, complete: false, visible: true });
await runner.stopSession(db, sid);
+ // The last step — the first accepted story.
+ await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "done" });
+ ob = await core.onboardingChecklist(db, u);
+ assert.deepEqual({ done: ob.done, complete: ob.complete, visible: ob.visible }, { done: 6, complete: true, visible: false });
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);
+ assert.equal(ob.total, 6);
await core.dismissOnboarding(db, admin.id);
ob = await core.onboardingChecklist(db, admin);
assert.deepEqual({ dismissed: ob.dismissed, visible: ob.visible }, { dismissed: true, visible: false });
--
2.45.2
From ee4a3130747041f0be7e2e230ab75e75e54e47f3 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 22:39:07 +0500
Subject: [PATCH 031/439] =?UTF-8?q?PEP-84:=20=C2=AB=D0=BF=D1=80=D0=BE?=
=?UTF-8?q?=D0=B4=D0=B0=D0=BA=D1=82=C2=BB=20and=20=C2=AB=D0=B0=D0=BD=D0=B0?=
=?UTF-8?q?=D0=BB=D0=B8=D1=82=D0=B8=D0=BA=C2=BB=20refine=20a=20story=20bef?=
=?UTF-8?q?ore=20any=20developer=20agent=20takes=20it?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Also: a subscription the owner connected once is assigned to their new projects; claudePrint never
falls back to the machine login for a self-registered owner.
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 10 +
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/p/[key]/page.tsx | 25 +-
apps/web/app/(app)/t/[key]/page.tsx | 22 +-
apps/web/app/(app)/t/[key]/tabs.tsx | 7 +-
apps/web/components/Board.tsx | 7 +
.../proposal.md | 24 ++
.../specs/story-planning/spec.md | 36 ++
.../tasks.md | 5 +
openspec/specs/story-planning/spec.md | 35 ++
packages/core/src/chats.ts | 2 +
packages/core/src/index.ts | 1 +
packages/core/src/intake.ts | 310 ++++++++++++++++++
packages/core/src/tasks.ts | 7 +-
packages/runner/src/autonomy.ts | 5 +-
packages/runner/src/claude-print.ts | 11 +-
packages/runner/src/flow.ts | 3 +
packages/runner/src/index.ts | 1 +
packages/runner/src/intake.ts | 180 ++++++++++
packages/runner/src/provision.ts | 7 +-
packages/runner/src/watchdog.ts | 3 +
packages/testkit/bin/mock-intake | 3 +
packages/testkit/src/mock-intake.ts | 44 +++
packages/testkit/test/intake.test.ts | 165 ++++++++++
packages/testkit/test/web.test.ts | 14 +
26 files changed, 917 insertions(+), 12 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md
create mode 100644 packages/core/src/intake.ts
create mode 100644 packages/runner/src/intake.ts
create mode 100755 packages/testkit/bin/mock-intake
create mode 100644 packages/testkit/src/mock-intake.ts
create mode 100644 packages/testkit/test/intake.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index b847bbb2..a87fd48f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -40,6 +40,7 @@
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
+- **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:` {enabled, waitMin, since}, состояние `intake.task:`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`)
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index a3c00ac2..815c0d41 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -20,6 +20,7 @@ import {
getProject as getProjectByKey,
updateIncidentSettings,
setReviewSettings,
+ setIntakeSettings,
type IncidentPolicy,
getUser,
isSuperadmin,
@@ -695,3 +696,12 @@ export async function cancelOwnLoginAction(f: FormData) {
await cancelOwnLogin(db, user, p, Number(str(f, "subscriptionId")));
});
}
+
+// ── PEP-84: «продакт» and «аналитик» ───────────────────────────────────────────────
+export async function saveIntakeSettingsAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 32b54396..5917c083 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -72,6 +72,7 @@ export default async function Help() {
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
+ Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал : экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 622d94ec..b8121705 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, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
-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, taskAgentNames, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, 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, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -22,7 +22,7 @@ import { requireUser } from "@/lib/auth";
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, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
+import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, saveIntakeSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
@@ -118,6 +118,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
const agentNames = await taskAgentNames(db, p.id);
+ const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
const cards: Card[] = tasks
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
.map((t) => {
@@ -132,6 +133,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
agent: agentNames.get(t.id) ?? null,
+ refining: refining.has(t.id) ? (refining.get(t.id) === "waiting" ? "ждёт ваших ответов" : "уточняется") : null,
};
});
// Gitea and the working copy are read only for the open tab.
@@ -208,6 +210,25 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
+
+
+
+
+
+ Новые стори сначала уточняют продакт и аналитик
+
+
+ Ждать ответа на вопросы, минут
+
+
+ Сохранить
+
+
+ Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). Стори, созданные
+ до включения, не трогает.
+
+
+
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index 14a957cb..e7e36cb7 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -1,5 +1,6 @@
// Story page (PEP-32): header with the story, the agent and its live session; tabs by the
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
+import { Markdown } from "@/components/Markdown";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Archive, ArchiveRestore, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
@@ -31,6 +32,9 @@ import {
reviewPreview,
sessionSteps,
storyComments,
+ getIntakeSettings,
+ getIntakeState,
+ intakePending,
taskCiSummary,
type GateResult,
} from "@peppa/core";
@@ -96,6 +100,9 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
// Only the open tab reads the rest (Gitea for the merge request).
const comments = tab === "comments" ? await storyComments(db, task.id) : [];
+ // PEP-84: is the story still with «продакт» and «аналитик»?
+ const intake = task.status === "backlog" ? await getIntakeState(db, task.id) : null;
+ const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "product") : null;
const runs: CheckRunRow[] =
tab === "tests" && ci.sha
? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt))).filter((r) => r.sha === ci.sha).sort((a, b) => a.check.localeCompare(b.check))
@@ -256,6 +263,14 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
+ {refining && (
+
+ {refining === "waiting" ? "Аналитик ждёт ваших ответов" : "Продакт и аналитик уточняют задачу"}
+
+ {refining === "waiting" ? "— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу." : "— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого."}
+
+
+ )}
{sp.edit ? (
@@ -287,7 +302,12 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
) : (
Описание}>
- {task.description || Без описания }
+ {/* PEP-84: the analyst writes the story in Markdown (criteria, out of scope, assumptions). */}
+ {task.description && /^## /m.test(task.description) ? (
+
+ ) : (
+ {task.description || Без описания }
+ )}
)}
diff --git a/apps/web/app/(app)/t/[key]/tabs.tsx b/apps/web/app/(app)/t/[key]/tabs.tsx
index db58d529..54758365 100644
--- a/apps/web/app/(app)/t/[key]/tabs.tsx
+++ b/apps/web/app/(app)/t/[key]/tabs.tsx
@@ -1,5 +1,6 @@
// Story page tabs (PEP-32): OpenSpec artifacts of the change, comments, checks, the PR and
// the activity log. Server components; each tab reads only what it shows.
+import { AgentBadge } from "@/components/AgentBadge";
import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass, MessageSquare, Send } from "lucide-react";
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
import { reviewLabel } from "@peppa/core";
@@ -146,10 +147,10 @@ export function CommentsTab({ taskKey, taskStatus, questions, comments, back, ha
t.kind === "q" ? (
) : (
-
+
-
- {t.c.login} комментарий PM · {ago(t.c.createdAt)}
+ {t.c.role ? : }
+ {t.c.role ? (t.c.role === "product" ? "зачем и что берём" : "что должно получиться") : <>{t.c.login} комментарий PM>} · {ago(t.c.createdAt)}
{t.c.text}
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index de1fc025..637d5fca 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -25,6 +25,8 @@ export interface Card {
blocked?: string | null;
/** PEP-75: the persona working on the story right now. */
agent?: string | null;
+ /** PEP-84: «продакт» and «аналитик» still hold the story ("уточняется" / "ждёт ваших ответов"). */
+ refining?: string | null;
}
export interface CardProgress {
done: number;
@@ -186,6 +188,11 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
)}
+ {card.refining && (
+
+ {card.refining}
+
+ )}
{card.agent &&
}
{card.progress &&
}
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
diff --git a/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md
new file mode 100644
index 00000000..90d1c93d
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/proposal.md
@@ -0,0 +1,24 @@
+# PEP-84: агенты «продакт» и «аналитик» — уточнение задачи перед работой
+
+## Why
+Сырое пожелание продакта сразу попадало к агенту-разработчику, и тот сам додумывал, что имелось в виду. PM: нужны агенты
+«продакт» и «аналитик», которые уточняют задачу, не льстят, помнят контекст и не ждут разрешений.
+
+## What Changes
+- Две роли (`core/intake.ts`, `runner/intake.ts`) — короткие вызовы `claude -p` на подписке проекта (`PEPPA_INTAKE_BIN`,
+ `PEPPA_INTAKE_MODEL`=sonnet): продакт (цель, самая маленькая версия, деление на стори — до 4 дополнительных, новое название),
+ затем аналитик (описание, критерии приёмки, вне задачи, допущения, до 3 вопросов с вариантом по умолчанию).
+- Контекст ролей: AGENTS.md проекта, память проекта, эпики, другие стори. Тон в промпте: без похвалы, прямо, для непрограммиста,
+ без запросов разрешения.
+- Состояние стори — `settings` `intake.task:
` (product → analyst → waiting | finalize → done); настройка проекта
+ `project.intake:` (вкл, сколько минут ждать; стори до включения не трогаются). Миграций нет.
+- Не ждут: вопросы уходят PM обычным вопросом; нет ответа за `waitMin` (30) минут — срок сдвигается за тихие часы проекта —
+ аналитик пишет допущения и закрывает вопрос. Ответ PM → аналитик дописывает стори. Две неудачи модели → стори идёт как написана.
+- Диспетчер (`readyBacklog`) не берёт стори, пока роли не закончили; PM, перетащивший карточку в работу, отменяет уточнение.
+- Реплики ролей — событие `intake_note`: вкладка Comments стори, чат проекта (и Telegram-группа), `get_task` разработчика.
+ Доска: метка «уточняется» / «ждёт ваших ответов»; страница стори: плашка и описание в Markdown.
+- Новый проект: уточнение включено; подписка владельца, подключённая однажды, назначается новому проекту сама.
+- `claudePrint` без подписки Claude в пуле не уходит на вход машины для самозарегистрированного владельца.
+
+Вне scope: сверка результата с критериями при приёмке, роли как персонажи «Команды», уточнение через свободный диалог.
+Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md
new file mode 100644
index 00000000..6fcd0fdb
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/specs/story-planning/spec.md
@@ -0,0 +1,36 @@
+## ADDED Requirements
+
+### Requirement: Продакт и аналитик уточняют стори
+В проекте с включённым уточнением новая стори в бэклоге SHALL сначала пройти роль «продакт»
+(цель, урезание до минимальной версии, деление на стори) и роль «аналитик» (описание,
+критерии приёмки, что вне задачи, допущения). Роли SHALL получать стандарты, память, эпики и
+другие стори проекта, писать без похвалы и не спрашивать разрешений. Диспетчер SHALL NOT
+брать стори, пока уточнение не закончено.
+
+#### Scenario: Стори уточнена
+- **GIVEN** проект с включённым уточнением
+- **WHEN** продакт создаёт стори «Корзина» с текстом «хочу складывать товары»
+- **THEN** в комментариях стори появляются реплики «Продакт» и «Аналитик», в описании — «Критерии приёмки» и «Исходный запрос» с его словами
+
+#### Scenario: Запрос больше одной стори
+- **WHEN** продакт-агент решает, что запрос «сделай интернет-магазин» — три задачи
+- **THEN** исходная стори переименована в первую из них, две другие созданы в бэклоге и проходят аналитика
+
+### Requirement: Аналитик не ждёт
+Аналитик SHALL задавать не больше трёх вопросов, каждый с вариантом по умолчанию, и по
+истечении срока ожидания (по умолчанию 30 минут; ночью — до конца тихих часов проекта)
+принимать варианты по умолчанию как допущения и отдавать стори в работу.
+
+#### Scenario: Ответ получен
+- **GIVEN** аналитик спросил «Нужна ли мобильная версия? По умолчанию: да»
+- **WHEN** продакт отвечает «не нужна»
+- **THEN** аналитик дописывает стори с учётом ответа, вопросов больше нет, стори доступна диспетчеру
+
+#### Scenario: Ответа нет
+- **GIVEN** вопрос аналитика без ответа
+- **WHEN** проходит 30 минут
+- **THEN** вопрос закрыт, вариант по умолчанию записан в «Допущения», стори доступна диспетчеру
+
+#### Scenario: Модель не ответила
+- **WHEN** роль дважды не смогла разобрать задачу
+- **THEN** стори идёт в работу как написана, в комментариях — почему
diff --git a/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md
new file mode 100644
index 00000000..b076e47e
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-84-product-analyst-intake/tasks.md
@@ -0,0 +1,5 @@
+- [x] 1 core/intake.ts: настройки, состояние, контекст, промпты, разбор ответов, текст стори
+- [x] 2 runner/intake.ts: `intakeTick`, вопросы и срок, ответ PM, отказоустойчивость; диспетчер ждёт; `releaseIntake`
+- [x] 3 Веб: настройка проекта, метка на доске, плашка и реплики в стори, Markdown описания; чат проекта
+- [x] 4 Новый проект: уточнение включено, своя подписка назначается сама; `claudePrint` без входа машины
+- [x] 5 mock-intake, `intake.test.ts`, прогон на настоящей модели (SBX-2), `openspec validate`
diff --git a/openspec/specs/story-planning/spec.md b/openspec/specs/story-planning/spec.md
index eba2c707..ceb3227e 100644
--- a/openspec/specs/story-planning/spec.md
+++ b/openspec/specs/story-planning/spec.md
@@ -34,3 +34,38 @@ Claude на подписке пула проекта предлагать спи
#### Scenario: Планировщик ответил мусором
- **WHEN** ответ планировщика не JSON со списком стори
- **THEN** PM видит «планировщик ответил не по формату», стори не созданы
+
+### Requirement: Продакт и аналитик уточняют стори
+В проекте с включённым уточнением новая стори в бэклоге SHALL сначала пройти роль «продакт»
+(цель, урезание до минимальной версии, деление на стори) и роль «аналитик» (описание,
+критерии приёмки, что вне задачи, допущения). Роли SHALL получать стандарты, память, эпики и
+другие стори проекта, писать без похвалы и не спрашивать разрешений. Диспетчер SHALL NOT
+брать стори, пока уточнение не закончено.
+
+#### Scenario: Стори уточнена
+- **GIVEN** проект с включённым уточнением
+- **WHEN** продакт создаёт стори «Корзина» с текстом «хочу складывать товары»
+- **THEN** в комментариях стори появляются реплики «Продакт» и «Аналитик», в описании — «Критерии приёмки» и «Исходный запрос» с его словами
+
+#### Scenario: Запрос больше одной стори
+- **WHEN** продакт-агент решает, что запрос «сделай интернет-магазин» — три задачи
+- **THEN** исходная стори переименована в первую из них, две другие созданы в бэклоге и проходят аналитика
+
+### Requirement: Аналитик не ждёт
+Аналитик SHALL задавать не больше трёх вопросов, каждый с вариантом по умолчанию, и по
+истечении срока ожидания (по умолчанию 30 минут; ночью — до конца тихих часов проекта)
+принимать варианты по умолчанию как допущения и отдавать стори в работу.
+
+#### Scenario: Ответ получен
+- **GIVEN** аналитик спросил «Нужна ли мобильная версия? По умолчанию: да»
+- **WHEN** продакт отвечает «не нужна»
+- **THEN** аналитик дописывает стори с учётом ответа, вопросов больше нет, стори доступна диспетчеру
+
+#### Scenario: Ответа нет
+- **GIVEN** вопрос аналитика без ответа
+- **WHEN** проходит 30 минут
+- **THEN** вопрос закрыт, вариант по умолчанию записан в «Допущения», стори доступна диспетчеру
+
+#### Scenario: Модель не ответила
+- **WHEN** роль дважды не смогла разобрать задачу
+- **THEN** стори идёт в работу как написана, в комментариях — почему
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 282248e9..237c0808 100644
--- a/packages/core/src/chats.ts
+++ b/packages/core/src/chats.ts
@@ -274,6 +274,8 @@ const EVENT_TEXT: Record { text: string; important?: boolean;
},
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
pm_comment: () => null, // handled separately: a person's message
+ // PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
+ intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }),
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
started: () => ({ text: "▶️ Агент запущен" }),
resumed: () => ({ text: "🔁 Агент продолжает работу" }),
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 6e3457b0..e8663891 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -22,6 +22,7 @@ export * from "./ci.ts";
export * from "./egov.ts";
export * from "./team.ts";
export * from "./progress.ts";
+export * from "./intake.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";
diff --git a/packages/core/src/intake.ts b/packages/core/src/intake.ts
new file mode 100644
index 00000000..690e6163
--- /dev/null
+++ b/packages/core/src/intake.ts
@@ -0,0 +1,310 @@
+// PEP-84: «продакт» and «аналитик» — two short LLM roles a new story passes before any developer
+// agent touches it. The product manager asks why and cuts the scope; the analyst writes what
+// exactly must come out (acceptance criteria, out of scope, assumptions) and asks at most three
+// questions, each with the default it will take if nobody answers. They do not flatter, see the
+// project's context, and never wait for permission: no answer in time — they go by the defaults.
+// State lives in `settings` (`intake.task:`, `project.intake:`): no schema change.
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { events, goals, tasks, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { and, asc, desc, eq, inArray, isNull } from "drizzle-orm";
+import { actorColumns } from "./actor.ts";
+import { readMemory } from "./memory.ts";
+import { notify } from "./notify.ts";
+import type { Project } from "./projects.ts";
+import { getSetting, setSetting } from "./settings.ts";
+import type { Task } from "./tasks.ts";
+
+export type IntakeRole = "product" | "analyst";
+export const INTAKE_ROLE_RU: Record = { product: "Продакт", analyst: "Аналитик" };
+export const INTAKE_EVENT = "intake_note";
+export const INTAKE_MAX_QUESTIONS = 3;
+export const INTAKE_MAX_SPLIT = 4;
+
+export interface IntakeSettings {
+ enabled: boolean;
+ /** Minutes the analyst waits for the PM's answers before going by its defaults. */
+ waitMin: number;
+ /** Stories created before this moment are left alone (ISO). */
+ since: string | null;
+}
+export const DEFAULT_INTAKE: IntakeSettings = { enabled: false, waitMin: 30, since: null };
+const projectKey = (projectId: number) => `project.intake:${projectId}`;
+
+export async function getIntakeSettings(db: Db, projectId: number): Promise {
+ return { ...DEFAULT_INTAKE, ...((await getSetting>(db, projectKey(projectId))) ?? {}) };
+}
+
+export async function setIntakeSettings(db: Db, projectId: number, patch: { enabled?: boolean; waitMin?: number }, now = new Date()): Promise {
+ const cur = await getIntakeSettings(db, projectId);
+ const next: IntakeSettings = { ...cur };
+ if (patch.waitMin !== undefined) next.waitMin = Math.min(24 * 60, Math.max(0, Math.round(patch.waitMin) || 0));
+ if (patch.enabled !== undefined && patch.enabled !== cur.enabled) {
+ next.enabled = patch.enabled;
+ // Turning it on does not drag the old backlog through the roles.
+ if (patch.enabled) next.since = now.toISOString();
+ }
+ await setSetting(db, projectKey(projectId), next);
+ return next;
+}
+
+export interface IntakeQuestion {
+ q: string;
+ /** What the analyst does if nobody answers. */
+ default: string;
+}
+
+export type IntakeStage = "product" | "analyst" | "waiting" | "finalize" | "done";
+
+export interface IntakeState {
+ stage: IntakeStage;
+ /** The PM's words as they were written. */
+ original: { title: string; description: string };
+ product?: ProductNote;
+ analyst?: AnalystNote;
+ questionId?: number;
+ /** When the analyst stops waiting (ms). */
+ deadline?: number;
+ /** The PM's answer to the questions (stage "finalize"). */
+ answer?: string;
+ attempts: number;
+ /** Why the roles were skipped or gave up, if they did. */
+ note?: string;
+}
+const taskKey = (taskId: number) => `intake.task:${taskId}`;
+
+export async function getIntakeState(db: Db, taskId: number): Promise {
+ return getSetting(db, taskKey(taskId));
+}
+export async function setIntakeState(db: Db, taskId: number, state: IntakeState): Promise {
+ await setSetting(db, taskKey(taskId), state);
+ await notify(db, { type: "task_updated", taskId });
+}
+
+/** Does this backlog story still belong to the roles (the dispatcher must not take it)? */
+export function intakePending(settings: IntakeSettings, task: Pick, state: IntakeState | null): boolean {
+ if (!settings.enabled || task.status !== "backlog") return false;
+ if (state) return state.stage !== "done";
+ return !!settings.since && task.createdAt.getTime() >= Date.parse(settings.since);
+}
+
+/** Backlog stories of the project the roles have not finished with: taskId → stage ("new" = not started). */
+export async function intakePendingTasks(db: Db, projectId: number): Promise> {
+ const out = new Map();
+ const settings = await getIntakeSettings(db, projectId);
+ if (!settings.enabled) return out;
+ const backlog = await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "backlog"), isNull(tasks.archivedAt)));
+ for (const t of backlog) {
+ const state = await getIntakeState(db, t.id);
+ if (intakePending(settings, t, state)) out.set(t.id, state?.stage ?? "new");
+ }
+ return out;
+}
+
+// ── what the roles see ───────────────────────────────────────────────────────────
+
+const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}\n…(обрезано)` : s);
+
+/** The project as the roles know it: standards, memory, epics, what was done and what is planned. */
+export async function intakeContext(db: Db, project: Project, task: Pick): Promise {
+ const agentsMd = existsSync(join(project.workspacePath, "AGENTS.md")) ? readFileSync(join(project.workspacePath, "AGENTS.md"), "utf8").trim() : "";
+ const memory = readMemory(project.workspacePath).trim();
+ const epics = await db.select().from(goals).where(and(eq(goals.projectId, project.id), eq(goals.status, "open"))).orderBy(asc(goals.id));
+ const stories = (await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt))).orderBy(desc(tasks.id)).limit(60)).filter((t) => t.id !== task.id);
+ const epic = epics.find((e) => e.id === task.goalId);
+ const line = (t: (typeof stories)[number]) => `- ${formatTaskKey(project.key, t.number)} [${t.status}] ${t.title}`;
+ return [
+ `Проект: ${project.key} — ${project.name}`,
+ "",
+ "## Стандарты проекта (AGENTS.md)",
+ agentsMd ? clip(agentsMd, 6000) : "(нет)",
+ "",
+ "## Память проекта",
+ memory ? clip(memory, 4000) : "(пусто)",
+ "",
+ "## Эпики",
+ epics.length ? epics.map((e) => `- #${e.id} ${e.title}${e.description ? ` — ${clip(e.description.replace(/\s+/g, " "), 300)}` : ""}`).join("\n") : "(нет)",
+ ...(epic ? ["", `Эта стори относится к эпику «${epic.title}».`] : []),
+ "",
+ "## Другие стори проекта (новые сверху)",
+ stories.length ? stories.map(line).join("\n") : "(нет — это первая стори проекта)",
+ ].join("\n");
+}
+
+const TONE = [
+ "Тон: коллега, а не помощник. Не хвали и не благодари, без «отличная идея» и восклицаний. Слабое место называй прямо и коротко.",
+ "Пиши для продакт-менеджера, который не программист: простые слова, без жаргона (PR, CI, API — только если без них нельзя).",
+ "Ты не спрашиваешь разрешений и не предлагаешь «могу сделать» — ты решаешь и пишешь, что решено.",
+].join("\n");
+
+export interface ProductNote {
+ /** What the PM actually wants, in one or two sentences. */
+ goal: string;
+ /** Plain words to the PM: what is cut, what is risky, what is unclear. */
+ comment: string;
+ /** A better title for this story (the smallest useful version), or the same one. */
+ title: string;
+ /** Other stories this request breaks into (besides this one). */
+ split: Array<{ title: string; description: string }>;
+}
+
+export function productPrompt(context: string, story: { title: string; description: string }): string {
+ return [
+ "Ты — продакт-менеджер софтвер-фабрики. К тебе пришло сырое пожелание. Реши, что из него делать.",
+ "1. Пойми цель: для кого это и какую проблему решает. Если пожелание не решает проблему — скажи.",
+ "2. Урежь до самой маленькой версии, которая уже полезна. Назови, что отложено.",
+ `3. Если это несколько задач — раздели: одна стори — один результат, который можно показать. Не больше ${INTAKE_MAX_SPLIT} дополнительных стори; мелкое не дроби.`,
+ "4. Проверь по списку стори проекта: не сделано ли уже, не противоречит ли, не нужно ли сначала другое.",
+ TONE,
+ "",
+ context,
+ "",
+ "## Пожелание",
+ `Название: ${story.title}`,
+ "Текст:",
+ story.description.trim() || "(только название)",
+ "",
+ 'Ответь ОДНОЙ строкой JSON без пояснений: {"goal":"…","comment":"…","title":"…","split":[{"title":"…","description":"…"}]}',
+ "goal — цель одной-двумя фразами. comment — 2–5 коротких фраз продакту: что берём, что режем, что настораживает. title — название этой стори после урезания (до 80 символов). split — остальные стори (пустой список, если делить не надо).",
+ ].join("\n");
+}
+
+export interface AnalystNote {
+ /** The story as the developer agent gets it. */
+ description: string;
+ criteria: string[];
+ outOfScope: string[];
+ assumptions: string[];
+ questions: IntakeQuestion[];
+ /** Plain words to the PM: what is contradictory or missing. */
+ comment: string;
+}
+
+export function analystPrompt(context: string, story: { title: string; description: string }, product: ProductNote | undefined, answers?: { questions: IntakeQuestion[]; answer: string }): string {
+ return [
+ "Ты — системный аналитик софтвер-фабрики. Преврати задачу в постановку, по которой ИИ-разработчик сделает ровно то, что нужно, а продакт сможет проверить результат.",
+ "1. Описание: что должно получиться и для кого — 3–8 фраз, без способа реализации.",
+ "2. Критерии приёмки: проверяемые снаружи утверждения («на странице каталога у товара видны фото, цена и кнопка „Купить“»), 3–8 штук.",
+ "3. Вне задачи: что сюда не входит, чтобы разработчик не сделал лишнего.",
+ "4. Сверь со стандартами, памятью и другими стори проекта: противоречия и пропущенные случаи назови в comment.",
+ `5. Вопросы — только те, от ответа на которые результат будет другим; не больше ${INTAKE_MAX_QUESTIONS}. У каждого — «default»: что ты сделаешь, если ответа не будет. Всё остальное реши сам и запиши в assumptions.`,
+ ...(answers ? ["6. Продакт ответил на твои вопросы — учти ответ, новых вопросов не задавай (questions — пустой список)."] : []),
+ TONE,
+ "",
+ context,
+ "",
+ "## Задача",
+ `Название: ${story.title}`,
+ "Текст продакта:",
+ story.description.trim() || "(только название)",
+ ...(product ? ["", "Решение продакт-менеджера фабрики:", `Цель: ${product.goal}`, product.comment] : []),
+ ...(answers ? ["", "Твои вопросы:", ...answers.questions.map((q, i) => `${i + 1}. ${q.q} (по умолчанию: ${q.default})`), "Ответ продакта:", answers.answer.trim()] : []),
+ "",
+ 'Ответь ОДНОЙ строкой JSON без пояснений: {"description":"…","criteria":["…"],"out_of_scope":["…"],"assumptions":["…"],"questions":[{"q":"…","default":"…"}],"comment":"…"}',
+ ].join("\n");
+}
+
+/** The first balanced JSON object of the text that has `field`. */
+function findJson(text: string, field: string): Record | null {
+ for (let i = text.indexOf("{"); i >= 0; i = text.indexOf("{", i + 1)) {
+ let depth = 0;
+ let inStr = false;
+ for (let j = i; j < text.length; j++) {
+ const c = text[j];
+ if (inStr) {
+ if (c === "\\") j++;
+ else if (c === '"') inStr = false;
+ continue;
+ }
+ if (c === '"') inStr = true;
+ else if (c === "{") depth++;
+ else if (c === "}" && --depth === 0) {
+ try {
+ const o = JSON.parse(text.slice(i, j + 1)) as Record;
+ if (o && typeof o === "object" && field in o) return o;
+ } catch {}
+ break;
+ }
+ }
+ }
+ return null;
+}
+
+const str = (v: unknown, max: number) => String(v ?? "").trim().slice(0, max);
+const list = (v: unknown, max: number, each = 500) => (Array.isArray(v) ? v.map((x) => str(x, each)).filter(Boolean).slice(0, max) : []);
+
+export function parseProductNote(text: string, fallbackTitle: string): ProductNote | null {
+ const o = findJson(text, "goal");
+ if (!o) return null;
+ const split = (Array.isArray(o.split) ? o.split : [])
+ .map((s) => ({ title: str((s as { title?: unknown })?.title, 200), description: str((s as { description?: unknown })?.description, 4000) }))
+ .filter((s) => s.title.length >= 3)
+ .slice(0, INTAKE_MAX_SPLIT);
+ const title = str(o.title, 200);
+ return { goal: str(o.goal, 1000), comment: str(o.comment, 3000), title: title.length >= 3 ? title : fallbackTitle, split };
+}
+
+export function parseAnalystNote(text: string): AnalystNote | null {
+ const o = findJson(text, "criteria");
+ if (!o) return null;
+ const criteria = list(o.criteria, 12);
+ const description = str(o.description, 6000);
+ if (!description || !criteria.length) return null;
+ const questions = (Array.isArray(o.questions) ? o.questions : [])
+ .map((q) => ({ q: str((q as { q?: unknown })?.q, 500), default: str((q as { default?: unknown })?.default, 500) }))
+ .filter((q) => q.q && q.default)
+ .slice(0, INTAKE_MAX_QUESTIONS);
+ return { description, criteria, outOfScope: list(o.out_of_scope ?? o.outOfScope, 10), assumptions: list(o.assumptions, 10), questions, comment: str(o.comment, 3000) };
+}
+
+/** The story text the developer agent works from. */
+export function intakeDescription(original: { title: string; description: string }, a: AnalystNote, decided: string[] = []): string {
+ const bullets = (items: string[]) => items.map((x) => `- ${x}`).join("\n");
+ return [
+ a.description,
+ "",
+ "## Критерии приёмки",
+ bullets(a.criteria),
+ ...(a.outOfScope.length ? ["", "## Вне задачи", bullets(a.outOfScope)] : []),
+ ...(a.assumptions.length || decided.length ? ["", "## Допущения", bullets([...a.assumptions, ...decided])] : []),
+ "",
+ "## Исходный запрос",
+ original.title + (original.description.trim() ? `\n\n${original.description.trim()}` : ""),
+ ].join("\n");
+}
+
+/** What the PM reads from the roles. */
+export function productMessage(p: ProductNote, splitKeys: string[]): string {
+ return [`Цель: ${p.goal}`, p.comment, ...(splitKeys.length ? [`Разделил на стори: эта и ${splitKeys.join(", ")}.`] : [])].filter(Boolean).join("\n\n");
+}
+export function analystMessage(a: AnalystNote): string {
+ const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n");
+ return [
+ a.comment,
+ `Критерии приёмки:\n${bullets(a.criteria)}`,
+ ...(a.assumptions.length ? [`Решил сам:\n${bullets(a.assumptions)}`] : []),
+ ...(a.questions.length ? ["Есть вопросы — отдельным сообщением. Не ответите — сделаю по вариантам по умолчанию."] : ["Вопросов нет — стори готова к работе."]),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+}
+export function questionsText(key: string, qs: IntakeQuestion[], waitMin: number): string {
+ return [
+ `Аналитик уточняет ${key}. Ответьте одним сообщением — или не отвечайте: через ${waitMin} мин возьму варианты по умолчанию.`,
+ ...qs.map((q, i) => `${i + 1}. ${q.q}\n По умолчанию: ${q.default}`),
+ ].join("\n\n");
+}
+
+/** A role's note on the story: an event shown among the story's comments and in the project chat. */
+export async function addIntakeNote(db: Db, task: Pick, role: IntakeRole, text: string): Promise {
+ await db.insert(events).values({ projectId: task.projectId, taskId: task.id, type: INTAKE_EVENT, payload: { role, text }, ...actorColumns() });
+ await notify(db, { type: "task_updated", taskId: task.id });
+}
+
+/** Ids of the tasks among `ids` that have intake notes (for tests and badges). */
+export async function tasksWithIntakeNotes(db: Db, ids: number[]): Promise> {
+ if (!ids.length) return new Set();
+ const rows = await db.select({ taskId: events.taskId }).from(events).where(and(inArray(events.taskId, ids), eq(events.type, INTAKE_EVENT)));
+ return new Set(rows.map((r) => r.taskId!));
+}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 1958bb6d..d74cee7e 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -253,6 +253,8 @@ export interface StoryComment {
login: string;
text: string;
createdAt: Date;
+ /** PEP-84: a note of «продакт» / «аналитик» rather than a person's comment. */
+ role?: "product" | "analyst";
}
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
@@ -269,9 +271,10 @@ export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number
}
export async function storyComments(db: Db, taskId: number): Promise {
- const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, COMMENT_EVENT))).orderBy(asc(events.id));
+ const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), inArray(events.type, [COMMENT_EVENT, "intake_note"]))).orderBy(asc(events.id));
return rows.map((e) => {
- const p = (e.payload ?? {}) as { login?: string; text?: string };
+ const p = (e.payload ?? {}) as { login?: string; text?: string; role?: "product" | "analyst" };
+ if (e.type === "intake_note") return { id: e.id, login: p.role === "product" ? "Продакт" : "Аналитик", text: p.text ?? "", createdAt: e.createdAt, role: p.role ?? "analyst" };
return { id: e.id, login: p.login ?? "?", text: p.text ?? "", createdAt: e.createdAt };
});
}
diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts
index dcb8b267..983793fb 100644
--- a/packages/runner/src/autonomy.ts
+++ b/packages/runner/src/autonomy.ts
@@ -32,6 +32,7 @@ import {
type Task,
type TaskRef,
projectAgentWarning,
+ intakePendingTasks,
} from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -288,7 +289,9 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
export async function readyBacklog(db: Db, projectId: number, backlog?: T[]): Promise {
const list = backlog ?? ((await listTasks(db, { projectId, statuses: ["backlog"] })) as unknown as T[]);
const blocked = await blockedTaskIds(db, projectId);
- return list.filter((t) => !blocked.has(t.id));
+ // PEP-84: stories «продакт» and «аналитик» have not finished with stay out of the dispatcher's reach.
+ const refining = await intakePendingTasks(db, projectId);
+ return list.filter((t) => !blocked.has(t.id) && !refining.has(t.id));
}
/** Sessions that hold a WIP slot: their story is being worked on (not in review). */
diff --git a/packages/runner/src/claude-print.ts b/packages/runner/src/claude-print.ts
index d77fe847..4002e856 100644
--- a/packages/runner/src/claude-print.ts
+++ b/packages/runner/src/claude-print.ts
@@ -5,8 +5,9 @@ import { spawn } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { claudeTokenForProject, type Project } from "@peppa/core";
-import type { Db } from "@peppa/db";
+import { claudeTokenForProject, mayUseMachineLogin, type Project } from "@peppa/core";
+import { projects, type Db } from "@peppa/db";
+import { eq } from "drizzle-orm";
export interface ClaudePrintOptions {
bin: string;
@@ -31,6 +32,12 @@ export function envelopeText(stdout: string): string | null {
export async function claudePrint(db: Db, project: Pick, o: ClaudePrintOptions): Promise {
const token = await claudeTokenForProject(db, project).catch(() => null);
+ // PEP-84: without a Claude subscription in the pool the CLI would run on this machine's own
+ // login — fine for the platform's and allowlisted owners' projects, never for a self-registered one.
+ if (!token) {
+ const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, project.id));
+ if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) return { ok: false, error: `${o.who}: у проекта нет подписки Claude` };
+ }
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
try {
diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts
index a1e9e65b..68eea1bc 100644
--- a/packages/runner/src/flow.ts
+++ b/packages/runner/src/flow.ts
@@ -1,4 +1,5 @@
// PM-side moves on the task board and review acceptance (web and Telegram use these).
+import { releaseIntake } from "./intake.ts";
import { answerQuestion, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
import { tasks, projects, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -45,6 +46,8 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
const from = columnOf(ref.task.status);
let stopped = 0;
if (to === "in_progress") {
+ // PEP-84: the PM took the story before the roles finished — they let it go.
+ await releaseIntake(db, ref.task.id);
if ((await activeSessions(db, ref.task.id)).length === 0) await assertBudgetOpen(db, ref.task.id);
if (from !== "in_progress") await updateTask(db, ref, { status: "in_progress" });
// PEP-10: by the runner settings — a new runner, or a free/queued runner of the project.
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index 693525a8..7dfea5ca 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -21,6 +21,7 @@ export * from "./platform-build.ts";
export * from "./code.ts";
export * from "./agents-md.ts";
export * from "./project-subscription.ts";
+export * from "./intake.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
diff --git a/packages/runner/src/intake.ts b/packages/runner/src/intake.ts
new file mode 100644
index 00000000..cf666ecb
--- /dev/null
+++ b/packages/runner/src/intake.ts
@@ -0,0 +1,180 @@
+// PEP-84: runs «продакт» and «аналитик» over new backlog stories (see core/intake.ts). The
+// watchdog calls `intakeTick`; each story moves through product → analyst → (waiting for the
+// PM's answers | done). LLM calls run in the background of the tick (one story at a time per
+// process), so a slow model never holds the watchdog. The dispatcher skips stories the roles
+// have not finished with (`readyBacklog`), a PM who drags the card to work overrides them.
+import {
+ addIntakeNote,
+ analystMessage,
+ analystPrompt,
+ answerQuestion,
+ askPm,
+ createTask,
+ getAutonomy,
+ getIntakeSettings,
+ getIntakeState,
+ inAutonomyQuietHours,
+ intakeContext,
+ intakeDescription,
+ intakePending,
+ listTasks,
+ parseAnalystNote,
+ parseProductNote,
+ productMessage,
+ productPrompt,
+ questionsText,
+ setIntakeState,
+ updateTask,
+ type IntakeState,
+ type Project,
+ type Question,
+ type TaskRef,
+} from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { projects } from "@peppa/db";
+import { claudePrint } from "./claude-print.ts";
+import { onAnswer, resolveTaskById } from "./sessions.ts";
+
+const MAX_ATTEMPTS = 2;
+const inFlight = new Set();
+
+const ask = (db: Db, project: Project, prompt: string, who: string) =>
+ claudePrint(db, project, {
+ bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
+ model: process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
+ timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
+ prompt,
+ who,
+ });
+
+/** When the analyst stops waiting: `waitMin` from now, moved past the project's quiet hours. */
+function deadline(now: Date, waitMin: number, quiet: { quietFrom: number | null; quietTo: number | null }): number {
+ const at = new Date(now.getTime() + waitMin * 60_000);
+ if (quiet.quietTo != null && inAutonomyQuietHours(quiet, at)) {
+ const morning = new Date(at);
+ morning.setHours(quiet.quietTo, 0, 0, 0);
+ if (morning <= at) morning.setDate(morning.getDate() + 1);
+ return morning.getTime();
+ }
+ return at.getTime();
+}
+
+/** One step of a story; returns the new state. Throws on a model failure (the caller counts attempts). */
+async function step(db: Db, ref: TaskRef, state: IntakeState, now: Date): Promise {
+ const { project, task } = ref;
+ const context = await intakeContext(db, project, task);
+ if (state.stage === "product") {
+ const out = await ask(db, project, productPrompt(context, state.original), "продакт");
+ if (!out.ok) throw new Error(out.error);
+ const note = parseProductNote(out.text, state.original.title);
+ if (!note) throw new Error("продакт ответил не по формату");
+ const splitKeys: string[] = [];
+ for (const s of note.split) {
+ const extra = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: s.description });
+ // A split story is already cut by the product manager: the analyst takes it from here.
+ await setIntakeState(db, extra.task.id, { stage: "analyst", original: { title: s.title, description: s.description }, product: { ...note, title: s.title, split: [] }, attempts: 0 });
+ splitKeys.push(extra.key);
+ }
+ if (note.title !== task.title) await updateTask(db, ref, { title: note.title });
+ await addIntakeNote(db, task, "product", productMessage(note, splitKeys));
+ return { ...state, stage: "analyst", product: note, attempts: 0 };
+ }
+ if (state.stage === "analyst" || state.stage === "finalize") {
+ const answers = state.stage === "finalize" && state.analyst ? { questions: state.analyst.questions, answer: state.answer ?? "" } : undefined;
+ const out = await ask(db, project, analystPrompt(context, { title: task.title, description: state.original.description }, state.product, answers), "аналитик");
+ if (!out.ok) throw new Error(out.error);
+ const note = parseAnalystNote(out.text);
+ if (!note) throw new Error("аналитик ответил не по формату");
+ if (answers) note.questions = [];
+ await updateTask(db, ref, { description: intakeDescription(state.original, note) });
+ await addIntakeNote(db, task, "analyst", answers ? `Учёл ответ. ${analystMessage(note)}` : analystMessage(note));
+ if (!note.questions.length) return { ...state, stage: "done", analyst: note, attempts: 0 };
+ const settings = await getIntakeSettings(db, project.id);
+ const q = await askPm(db, ref, { kind: "question", text: questionsText(ref.key, note.questions, settings.waitMin) });
+ return { ...state, stage: "waiting", analyst: note, questionId: q.id, deadline: deadline(now, settings.waitMin, await getAutonomy(db, project.id)), attempts: 0 };
+ }
+ return state;
+}
+
+/** Nobody answered in time: the analyst's defaults become decisions, the story is ready. */
+async function goByDefaults(db: Db, ref: TaskRef, state: IntakeState): Promise {
+ const a = state.analyst!;
+ const decided = a.questions.map((q) => `${q.q} — ${q.default} (ответа не было, взят вариант по умолчанию)`);
+ await updateTask(db, ref, { description: intakeDescription(state.original, a, decided) });
+ if (state.questionId) await answerQuestion(db, state.questionId, "(ответа не было — аналитик взял варианты по умолчанию)", "system").catch(() => {});
+ await addIntakeNote(db, ref.task, "analyst", `Ответа не было — иду по вариантам по умолчанию:\n${a.questions.map((q) => `• ${q.q} → ${q.default}`).join("\n")}\nСтори готова к работе.`);
+ await setIntakeState(db, ref.task.id, { ...state, stage: "done" });
+}
+
+async function advance(db: Db, taskId: number, now: Date, log: (m: string) => void): Promise {
+ const ref = await resolveTaskById(db, taskId).catch(() => null);
+ if (!ref) return;
+ const settings = await getIntakeSettings(db, ref.project.id);
+ let state = await getIntakeState(db, taskId);
+ if (!intakePending(settings, ref.task, state)) return;
+ state ??= { stage: "product", original: { title: ref.task.title, description: ref.task.description ?? "" }, attempts: 0 };
+ if (state.stage === "waiting") {
+ if ((state.deadline ?? 0) <= now.getTime()) {
+ await goByDefaults(db, ref, state);
+ log(`${ref.key}: intake — no answer, defaults taken`);
+ }
+ return;
+ }
+ try {
+ // Several steps in a row: product → analyst without waiting for the next tick.
+ for (let i = 0; i < 3 && state.stage !== "waiting" && state.stage !== "done"; i++) {
+ state = await step(db, ref, state, now);
+ await setIntakeState(db, taskId, state);
+ log(`${ref.key}: intake → ${state.stage}`);
+ }
+ } catch (e) {
+ const attempts = state.attempts + 1;
+ // The roles must never hold a story for ever: after a couple of failures it goes on as written.
+ if (attempts >= MAX_ATTEMPTS) {
+ await setIntakeState(db, taskId, { ...state, stage: "done", attempts, note: (e as Error).message });
+ await addIntakeNote(db, ref.task, state.stage === "product" ? "product" : "analyst", `Не смог разобрать задачу (${(e as Error).message}) — стори идёт в работу как написана.`);
+ } else await setIntakeState(db, taskId, { ...state, attempts });
+ log(`${ref.key}: intake failed (${attempts}): ${(e as Error).message}`);
+ }
+}
+
+export interface IntakeTickOptions {
+ now?: Date;
+ log?: (m: string) => void;
+ /** Tests: wait for the model calls instead of leaving them in the background. */
+ wait?: boolean;
+}
+
+export async function intakeTick(db: Db, opts: IntakeTickOptions = {}): Promise {
+ const now = opts.now ?? new Date();
+ const log = opts.log ?? (() => {});
+ const jobs: Promise[] = [];
+ for (const { id } of await db.select({ id: projects.id }).from(projects)) {
+ const settings = await getIntakeSettings(db, id);
+ if (!settings.enabled) continue;
+ for (const t of await listTasks(db, { projectId: id, statuses: ["backlog"] })) {
+ if (inFlight.has(t.id) || !intakePending(settings, t, await getIntakeState(db, t.id))) continue;
+ inFlight.add(t.id);
+ jobs.push(advance(db, t.id, now, log).catch((e) => log(`intake ${t.id}: ${(e as Error).message}`)).finally(() => inFlight.delete(t.id)));
+ }
+ }
+ if (opts.wait) await Promise.all(jobs);
+}
+
+/** The PM answered the analyst's questions: the analyst finishes the story with the answer. */
+export async function onIntakeAnswer(db: Db, q: Question, answer: string): Promise {
+ if (!q.taskId) return false;
+ const state = await getIntakeState(db, q.taskId);
+ if (!state || state.stage !== "waiting" || state.questionId !== q.id) return false;
+ await setIntakeState(db, q.taskId, { ...state, stage: "finalize", answer, attempts: 0 });
+ return true;
+}
+onAnswer(onIntakeAnswer);
+
+/** The PM dragged the card to work (or the story left the backlog): the roles let it go. */
+export async function releaseIntake(db: Db, taskId: number): Promise {
+ const state = await getIntakeState(db, taskId);
+ if (!state || state.stage === "done") return;
+ if (state.questionId) await answerQuestion(db, state.questionId, "(стори взята в работу без ответа)", "system").catch(() => {});
+ await setIntakeState(db, taskId, { ...state, stage: "done", note: "взята в работу вручную" });
+}
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index c8e511de..68f9d6ae 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -4,7 +4,7 @@
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { createProject, NEW_PROJECT_AUTONOMY, setAutonomy, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
+import { createProject, NEW_PROJECT_AUTONOMY, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { eq, or } from "drizzle-orm";
@@ -131,6 +131,11 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise log(`ci: ${(e as Error).message}`));
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index bdd5fe10..2d820d20 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -32,6 +32,7 @@ import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
+import { intakeTick } from "./intake.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";
@@ -83,6 +84,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise {
// Story budgets (PEP-43): over the limit → pause and ask the PM.
await budgetTick(db, { now: opts.now, log }).catch((e) => log(`budgets: ${(e as Error).message}`));
// Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher.
+ // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them.
+ await intakeTick(db, { now: opts.now, log }).catch((e) => log(`intake: ${(e as Error).message}`));
await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`));
// Errors of running products (PEP-58): Bugsink poll + incident policies.
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
diff --git a/packages/testkit/bin/mock-intake b/packages/testkit/bin/mock-intake
new file mode 100755
index 00000000..df81e6e7
--- /dev/null
+++ b/packages/testkit/bin/mock-intake
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
+exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-intake.ts" "$@"
diff --git a/packages/testkit/src/mock-intake.ts b/packages/testkit/src/mock-intake.ts
new file mode 100644
index 00000000..6245965d
--- /dev/null
+++ b/packages/testkit/src/mock-intake.ts
@@ -0,0 +1,44 @@
+// mock-intake (PEP-84): stands in for `claude -p --output-format json` as «продакт» and «аналитик».
+// Reads the prompt on stdin and answers with the CLI's JSON envelope. The role is read off the
+// prompt's first line. Behaviour comes from MOCK_INTAKE_SCENARIO (a JSON file):
+// { "product": {goal, comment, title, split[]}, "analyst": {description, criteria[], out_of_scope[],
+// assumptions[], questions[{q, default}], comment}, "garbage": false, "fail": false }
+// Without a scenario: the product manager keeps the story as is, the analyst asks one question
+// (none once the prompt carries the PM's answer). Every call is appended to .log.jsonl.
+import { appendFileSync, existsSync, readFileSync } from "node:fs";
+
+interface Scenario {
+ product?: object;
+ analyst?: { questions?: unknown[] } & Record;
+ garbage?: boolean;
+ fail?: boolean;
+}
+
+const file = process.env.MOCK_INTAKE_SCENARIO;
+const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
+const prompt = readFileSync(0, "utf8");
+const role = prompt.startsWith("Ты — продакт-менеджер") ? "product" : "analyst";
+const answered = /Ответ продакта:\n/.test(prompt);
+const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? "";
+if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
+if (!process.argv.includes("-p")) {
+ console.error("mock-intake: expected -p (non-interactive print mode)");
+ process.exit(2);
+}
+if (sc.fail) {
+ console.error("mock-intake: API Error: 529 overloaded");
+ process.exit(1);
+}
+const product = sc.product ?? { goal: `Сделать: ${title}`, comment: "Берём как есть. Лишнего нет.", title, split: [] };
+const analyst = {
+ description: `Нужно: ${title}.`,
+ criteria: ["Результат виден пользователю", "Ошибки показаны понятным текстом"],
+ out_of_scope: ["Оформление сверх необходимого"],
+ assumptions: ["Язык интерфейса — русский"],
+ questions: [{ q: "Нужна ли мобильная версия?", default: "Да, страница открывается с телефона" }],
+ comment: "В запросе не сказано, кто пользователь.",
+ ...sc.analyst,
+};
+if (answered) analyst.questions = [];
+const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "product" ? product : analyst);
+process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n");
diff --git a/packages/testkit/test/intake.test.ts b/packages/testkit/test/intake.test.ts
new file mode 100644
index 00000000..2e235a7b
--- /dev/null
+++ b/packages/testkit/test/intake.test.ts
@@ -0,0 +1,165 @@
+// PEP-84: «продакт» and «аналитик» refine a new story before the dispatcher takes it (mock-intake).
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, before, describe, test } from "node:test";
+import { core, db, runner, teardown } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
+const TMP = mkdtempSync(join(tmpdir(), "peppa-intake-"));
+const scenario = join(TMP, "scenario.json");
+const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; title: string; answered: boolean; answer: string | null; hasContext: boolean; prompt: string });
+const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s));
+
+type User = Awaited>;
+let pm: User;
+let seq = 0;
+before(async () => {
+ process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
+ process.env.MOCK_INTAKE_SCENARIO = scenario;
+ setScenario({});
+ pm = await core.upsertUserFromGitea(db, { id: 8401, login: "mock-pm-8401" }, { access_token: "x" });
+});
+after(teardown);
+
+async function intakeProject() {
+ const n = ++seq;
+ const ws = join(TMP, `ws${n}`);
+ mkdirSync(join(ws, ".peppa"), { recursive: true });
+ writeFileSync(join(ws, "AGENTS.md"), "# AGENTS.md\n\n## Соглашения\n- Интерфейс на русском\n");
+ writeFileSync(join(ws, ".peppa/memory.md"), "# Память проекта\n\n## Решения\n- Оплата только картой\n");
+ const p = await core.createProject(db, { slug: `mock-intake-${n}`, key: `MIN${String.fromCharCode(64 + n)}`, name: `Intake ${n}`, giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
+ await core.setIntakeSettings(db, p.id, { enabled: true });
+ return p;
+}
+const tick = (now?: Date) => runner.intakeTick(db, { wait: true, now });
+const story = async (key: string) => (await core.resolveTask(db, key)).task;
+
+describe("Продакт и аналитик", () => {
+ test("Scenario: стори проходит продакта и аналитика; вопрос с вариантом по умолчанию; ответ PM учитывается", async () => {
+ const p = await intakeProject();
+ const done = await core.createTask(db, { projectId: p.id, title: "Каталог товаров" });
+ await core.setIntakeState(db, done.task.id, { stage: "done", original: { title: "", description: "" }, attempts: 0 });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Корзина", description: "Хочу чтобы можно было складывать товары" });
+ assert.deepEqual([...(await core.intakePendingTasks(db, p.id)).entries()], [[ref.task.id, "new"]]);
+ assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [done.task.id], "the dispatcher does not see a story the roles hold");
+
+ await tick();
+ let state = (await core.getIntakeState(db, ref.task.id))!;
+ assert.equal(state.stage, "waiting");
+ const mine = calls().filter((c) => c.title === "Корзина");
+ assert.deepEqual(mine.map((c) => c.role), ["product", "analyst"]);
+ assert.ok(mine.every((c) => c.hasContext), "the roles get the project's context");
+ assert.match(mine[0]!.prompt, /Интерфейс на русском/, "AGENTS.md");
+ assert.match(mine[0]!.prompt, /Оплата только картой/, "memory");
+ assert.match(mine[0]!.prompt, /\[backlog\] Каталог товаров/, "other stories");
+ assert.match(mine[0]!.prompt, /Не хвали/, "no flattery");
+
+ let t = await story(ref.key);
+ assert.match(t.description!, /## Критерии приёмки\n- Результат виден пользователю/);
+ assert.match(t.description!, /## Исходный запрос\nКорзина\n\nХочу чтобы можно было складывать товары/, "the PM's words are kept");
+ const comments = await core.storyComments(db, ref.task.id);
+ assert.deepEqual(comments.map((c) => c.role), ["product", "analyst"]);
+ assert.equal(comments[0]!.login, "Продакт");
+ const [q] = await core.pendingQuestions(db, p.id);
+ assert.equal(q!.id, state.questionId);
+ assert.match(q!.text, /Нужна ли мобильная версия\?\n\s+По умолчанию: Да, страница открывается с телефона/);
+
+ // The PM answers: the analyst finishes with the answer and asks nothing more.
+ await runner.answerAndDeliver(db, q!.id, "Мобильная не нужна, только ноутбук", "web");
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "finalize");
+ await tick();
+ state = (await core.getIntakeState(db, ref.task.id))!;
+ assert.equal(state.stage, "done");
+ const last = calls().at(-1)!;
+ assert.equal(last.answered, true);
+ assert.equal(last.answer, "Мобильная не нужна, только ноутбук");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0);
+ assert.deepEqual((await runner.readyBacklog(db, p.id)).map((x) => x.id).sort(), [done.task.id, ref.task.id].sort(), "now the dispatcher may take it");
+ t = await story(ref.key);
+ assert.match(t.description!, /## Критерии приёмки/);
+ });
+
+ test("Scenario: PM молчит — после срока аналитик идёт по вариантам по умолчанию и не ждёт", async () => {
+ const p = await intakeProject();
+ await core.setIntakeSettings(db, p.id, { waitMin: 30 });
+ await core.setAutonomy(db, p.id, { quietFrom: null, quietTo: null });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" });
+ const t0 = new Date("2026-11-16T10:00:00");
+ await tick(t0);
+ const waiting = (await core.getIntakeState(db, ref.task.id))!;
+ assert.equal(waiting.stage, "waiting");
+ assert.equal(waiting.deadline, t0.getTime() + 30 * 60_000);
+ await tick(new Date(t0.getTime() + 29 * 60_000));
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "waiting", "still waiting before the deadline");
+ const before = calls().length;
+ await tick(new Date(t0.getTime() + 31 * 60_000));
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done");
+ assert.equal(calls().length, before, "no extra model call for the defaults");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the question is closed");
+ assert.match((await story(ref.key)).description!, /## Допущения[\s\S]*Нужна ли мобильная версия\? — Да, страница открывается с телефона \(ответа не было/);
+ assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /Ответа не было — иду по вариантам по умолчанию/);
+
+ // Night: the deadline moves to the morning of the project's quiet hours.
+ await core.setAutonomy(db, p.id, { quietFrom: 22, quietTo: 9 });
+ const night = await core.createTask(db, { projectId: p.id, title: "Ночная" });
+ await tick(new Date("2026-11-16T23:50:00"));
+ assert.equal(new Date((await core.getIntakeState(db, night.task.id))!.deadline!).toISOString(), new Date("2026-11-17T09:00:00").toISOString());
+ });
+
+ test("Scenario: продакт делит запрос на стори и переименовывает; без вопросов стори сразу готова", async () => {
+ const p = await intakeProject();
+ setScenario({
+ product: { goal: "Продавать онлайн", comment: "Это три задачи. Доставку откладываю.", title: "Каталог: список товаров", split: [{ title: "Тележка", description: "Сложить товары" }, { title: "Оплата картой", description: "Оплатить заказ" }] },
+ analyst: { questions: [] },
+ });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Сделай интернет-магазин" });
+ await tick();
+ const all = await core.listTasks(db, { projectId: p.id });
+ assert.deepEqual(all.map((t) => t.title).sort(), ["Каталог: список товаров", "Оплата картой", "Тележка"]);
+ assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done");
+ assert.match((await core.storyComments(db, ref.task.id))[0]!.text, /Разделил на стори: эта и MIN\w-2, MIN\w-3/);
+ // The split stories skip the product manager: the analyst takes them on the next tick.
+ await tick();
+ for (const t of all) assert.equal((await core.getIntakeState(db, t.id))!.stage, "done");
+ assert.equal(calls().filter((c) => c.role === "product" && ["Тележка", "Оплата картой"].includes(c.title)).length, 0);
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0);
+ setScenario({});
+ });
+
+ test("роли не держат стори: сбой модели, ручной запуск, выключенное уточнение, старый бэклог", async () => {
+ const p = await intakeProject();
+ setScenario({ garbage: true });
+ const broken = await core.createTask(db, { projectId: p.id, title: "Сломанная" });
+ await tick();
+ assert.equal((await core.getIntakeState(db, broken.task.id))!.stage, "product", "one failure — try again");
+ await tick();
+ const gaveUp = (await core.getIntakeState(db, broken.task.id))!;
+ assert.equal(gaveUp.stage, "done");
+ assert.match(gaveUp.note!, /не по формату/);
+ assert.equal((await story(broken.key)).description ?? "", "", "the story goes on as written");
+ assert.match((await core.storyComments(db, broken.task.id)).at(-1)!.text, /стори идёт в работу как написана/);
+ setScenario({});
+
+ // The PM takes the story to work while the analyst waits: the question is closed.
+ const manual = await core.createTask(db, { projectId: p.id, title: "Ручная" });
+ await tick();
+ assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "waiting");
+ await runner.releaseIntake(db, manual.task.id);
+ assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "done");
+ assert.equal((await core.pendingQuestions(db, p.id)).length, 0);
+
+ // Off by default; turning it on leaves the old backlog alone.
+ const off = await core.createProject(db, { slug: "mock-intake-off", key: "MINOFF", name: "Off", giteaOwner: "x", workspacePath: join(TMP, "off"), ownerId: pm.id });
+ const old = await core.createTask(db, { projectId: off.id, title: "Старая" });
+ assert.equal((await core.getIntakeSettings(db, off.id)).enabled, false);
+ await core.setIntakeSettings(db, off.id, { enabled: true }, new Date(Date.now() + 1000));
+ const n = calls().length;
+ await tick();
+ assert.equal(calls().length, n);
+ assert.equal(await core.getIntakeState(db, old.task.id), null);
+ });
+});
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 9b710bff..365405f7 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -202,3 +202,17 @@ describe("PEP-77: прогресс по всем проектам", () => {
}
});
});
+
+describe("новый проект: настройки по умолчанию", () => {
+ test("подписка владельца подключается сама; стори берутся сами; продакт и аналитик включены", async () => {
+ const first = await provision({ slug: "mock-defaults-a", key: "MDFA" });
+ assert.equal(await core.projectPool(db, first.id), null, "no own subscription yet");
+ assert.equal(core.autonomyLevel(await core.getAutonomy(db, first.id)), "self");
+ assert.equal((await core.getIntakeSettings(db, first.id)).enabled, true);
+
+ const sub = await core.createSubscription(db, { provider: "claude", name: "mock-defaults Claude", authKind: "oauth", secret: "sk-ant-oat01-" + "d".repeat(40), createdBy: alice.id });
+ const pool = await core.createPool(db, { name: "mock-defaults pool", subscriptionIds: [sub.id], createdBy: alice.id });
+ const second = await provision({ slug: "mock-defaults-b", key: "MDFB" });
+ assert.equal((await core.projectPool(db, second.id))!.id, pool.id, "connected once — not asked again");
+ });
+});
--
2.45.2
From 01d58973abc0b51549841d0c10da3673366a0426 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 22:57:07 +0500
Subject: [PATCH 032/439] =?UTF-8?q?PEP-85:=20every=20user's=20own=20Telegr?=
=?UTF-8?q?am=20bot=20=E2=80=94=20token=20from=20BotFather,=20polled=20and?=
=?UTF-8?q?=20answered=20through=20it?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/bot/src/bot.ts | 105 +-
apps/web/app/(app)/actions.ts | 26 +-
apps/web/app/(app)/help/page.tsx | 1 +
apps/web/app/(app)/settings/page.tsx | 113 +-
.../proposal.md | 18 +
.../specs/telegram-bot/spec.md | 24 +
.../tasks.md | 5 +
openspec/specs/telegram-bot/spec.md | 23 +
packages/core/src/onboarding.ts | 6 +-
packages/core/src/secrets-audit.ts | 1 +
packages/core/src/telegram.ts | 89 +-
.../db/migrations/0016_user_telegram_bot.sql | 2 +
.../db/migrations/meta/0016_snapshot.json | 4120 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 4 +
packages/testkit/src/mock-telegram.ts | 6 +-
packages/testkit/test/own-bot.test.ts | 118 +
18 files changed, 4633 insertions(+), 36 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md
create mode 100644 packages/db/migrations/0016_user_telegram_bot.sql
create mode 100644 packages/db/migrations/meta/0016_snapshot.json
create mode 100644 packages/testkit/test/own-bot.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index a87fd48f..cff9faae 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,6 +41,7 @@
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
- **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:` {enabled, waitMin, since}, состояние `intake.task:`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`)
+- **Свой Telegram-бот (PEP-85)**: `users.telegram_bot_token_enc` (в `encryptedColumns`) + `telegram_bot_username` (миграция 0016). core/telegram.ts: `verifyBotToken`, `setUserBot`/`clearUserBot`, `userBots`; `acceptPairing(…, { botUserId })` — свой бот привязывает только владельца, общий не привязывает того, у кого есть свой; `getOffset`/`claimUpdate` принимают `botUserId` (ключ обновления `userId·2^36 + update_id`). apps/bot: `syncOwnBots` (раз в `userBotsIntervalMs`), `ownPollLoop`, обработка внутри `via.run(bot)`, объект `api` маршрутизирует вызов: бот текущего обновления → бот владельца `chat_id` → общий. Группы и каналы — только общий бот. Веб «Настройки → Telegram»: три шага. Тест `own-bot.test.ts` — два `MockTelegram` (`userApi` в опциях бота)
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 551720cd..419df6e8 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -12,6 +12,7 @@ import {
beat,
checkServices,
claimUpdate,
+ userBots,
dueOutbox,
enqueueTelegram,
finishUpdate,
@@ -66,6 +67,7 @@ import {
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
+import { AsyncLocalStorage } from "node:async_hooks";
import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
@@ -88,6 +90,10 @@ export interface BotOptions {
heartbeatIntervalMs?: number;
// How often to check PRAGMA data_version for writes the notify() poke missed.
changesIntervalMs?: number;
+ /** PEP-85: API client of a user's own bot (tests point it at a second mock). */
+ userApi?: (token: string) => TelegramApi;
+ /** How often the list of users' own bots is re-read. */
+ userBotsIntervalMs?: number;
log?: (msg: string) => void;
}
@@ -120,9 +126,81 @@ function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null;
}
export function createBot(o: BotOptions) {
- const { db, api } = o;
+ const { db } = o;
const log = o.log ?? (() => {});
const abort = new AbortController();
+
+ // ── PEP-85: users' own bots ────────────────────────────────────────────────────
+ // Every bot is polled by its own loop; an update is handled inside `via.run(bot)`, so replies
+ // go out through the bot the message came to. Outside an update (outbox, digests) the bot is
+ // picked by the chat: the owner's private chat belongs to their bot, everything else — the
+ // platform's shared bot.
+ interface OwnBot {
+ userId: number;
+ token: string;
+ api: TelegramApi;
+ stop: AbortController;
+ }
+ const via = new AsyncLocalStorage();
+ const ownBots = new Map();
+ const ownByChat = new Map();
+ const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
+ /** The same surface as TelegramApi, routed to the right bot per call. */
+ const api = {
+ call: (method: string, params: Record = {}, timeoutMs?: number) => pick(params.chat_id).call(method, params, timeoutMs),
+ sendMessage: (chatId: number, text: string, extra: Record = {}) => pick(chatId).sendMessage(chatId, text, extra),
+ answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text),
+ getFile: (fileId: string) => pick().getFile(fileId),
+ downloadFile: (filePath: string) => pick().downloadFile(filePath),
+ getMe: () => o.api.getMe(),
+ getUpdates: (offset: number, timeoutSec: number, signal?: AbortSignal) => o.api.getUpdates(offset, timeoutSec, signal),
+ };
+
+ /** Re-reads the connected bots: starts a poll loop for a new one, stops a removed or re-issued one. */
+ async function syncOwnBots(): Promise {
+ const list = await userBots(db);
+ const seen = new Set();
+ ownByChat.clear();
+ for (const b of list) {
+ seen.add(b.userId);
+ let bot = ownBots.get(b.userId);
+ if (bot && bot.token !== b.token) {
+ bot.stop.abort();
+ bot = undefined;
+ }
+ if (!bot) {
+ bot = { userId: b.userId, token: b.token, api: (o.userApi ?? ((t) => new TelegramApi(t, process.env.TELEGRAM_API_URL)))(b.token), stop: new AbortController() };
+ ownBots.set(b.userId, bot);
+ log(`own bot @${b.username} of user #${b.userId}: polling`);
+ void ownPollLoop(bot);
+ }
+ if (b.chatId != null) ownByChat.set(b.chatId, bot);
+ }
+ for (const [userId, bot] of ownBots) {
+ if (seen.has(userId)) continue;
+ bot.stop.abort();
+ ownBots.delete(userId);
+ log(`own bot of user #${userId}: stopped`);
+ }
+ }
+
+ async function ownPollLoop(bot: OwnBot): Promise {
+ while (!abort.signal.aborted && !bot.stop.signal.aborted) {
+ try {
+ let offset = await getOffset(db, bot.userId);
+ const updates = await bot.api.getUpdates(offset, o.pollTimeoutSec ?? 25, bot.stop.signal);
+ for (const u of updates) {
+ await via.run(bot, () => handleUpdate(u));
+ offset = u.update_id + 1;
+ await setOffset(db, offset, bot.userId);
+ }
+ } catch (e) {
+ // A revoked token (401) keeps failing: back off instead of hammering Telegram.
+ log(`own bot #${bot.userId} poll: ${(e as Error).message}`);
+ await sleep(e instanceof TelegramError && e.code === 401 ? 60_000 : 3000);
+ }
+ }
+ }
let reconcileQueued = false;
let wakeOutbox: (() => void) | null = null;
@@ -495,8 +573,9 @@ export function createBot(o: BotOptions) {
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
- const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username });
+ const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
if (b) {
+ await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
scheduleReconcile();
return "done";
@@ -506,6 +585,9 @@ export function createBot(o: BotOptions) {
}
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
if (!user) return "ignored";
+ // PEP-85: a user's own bot serves its owner only.
+ const own = via.getStore();
+ if (own && own.userId !== user.id) return "ignored";
// PEP-48: what follows is done by this user through Telegram.
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
@@ -612,13 +694,14 @@ export function createBot(o: BotOptions) {
}
async function handleUpdate(u: TgUpdate): Promise {
- if (!(await claimUpdate(db, u.update_id))) return;
+ const botUserId = via.getStore()?.userId;
+ if (!(await claimUpdate(db, u.update_id, botUserId))) return;
try {
const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored";
- await finishUpdate(db, u.update_id, r);
+ await finishUpdate(db, u.update_id, r, botUserId);
} catch (e) {
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
- await finishUpdate(db, u.update_id, "failed");
+ await finishUpdate(db, u.update_id, "failed", botUserId);
}
}
@@ -675,6 +758,13 @@ export function createBot(o: BotOptions) {
}
}
+ async function ownBotsLoop() {
+ while (!abort.signal.aborted) {
+ await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
+ await sleep(o.userBotsIntervalMs ?? 10_000);
+ }
+ }
+
async function monitorLoop() {
while (!abort.signal.aborted) {
try {
@@ -694,16 +784,19 @@ export function createBot(o: BotOptions) {
reconcile,
flushOutbox,
handleUpdate,
+ syncOwnBots,
async start() {
const me = await api.getMe();
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
log(`bot @${me.username} started`);
unlisten = await listenEvents("bot", () => scheduleReconcile());
- loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]);
+ await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
+ loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop(), ownBotsLoop()]);
return me;
},
async stop() {
abort.abort();
+ for (const b of ownBots.values()) b.stop.abort();
wakeOutbox?.();
await unlisten?.().catch(() => {});
await loops;
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 815c0d41..29f6a15c 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -21,6 +21,8 @@ import {
updateIncidentSettings,
setReviewSettings,
setIntakeSettings,
+ setUserBot,
+ clearUserBot,
type IncidentPolicy,
getUser,
isSuperadmin,
@@ -419,9 +421,10 @@ export async function pairTelegram(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const token = loadEnv().TELEGRAM_BOT_TOKEN;
- const bot = await getSetting<{ username: string }>(db, "telegram.bot");
- if (!token || !bot) throw new PeppaError("Telegram-бот Пеппы не запущен");
- return `https://t.me/${bot.username}?start=${await createPairingCode(db, token, user.id)}`;
+ // PEP-85: the user's own bot if they connected one, else the platform's shared bot.
+ const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username;
+ if (!token || !username) throw new PeppaError("Telegram-бот Пеппы не запущен");
+ return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
});
}
@@ -705,3 +708,20 @@ export async function saveIntakeSettingsAction(f: FormData) {
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
});
}
+
+// ── PEP-85: the user's own Telegram bot ────────────────────────────────────────────
+export async function connectOwnBotAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await setUserBot(db, user.id, String(f.get("token") ?? ""));
+ return "/settings?bot=connected#telegram";
+ });
+}
+
+export async function disconnectOwnBotAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ await clearUserBot(db, user.id);
+ return "/settings#telegram";
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 5917c083..fd64b22f 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -72,6 +72,7 @@ export default async function Help() {
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».
Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».
+ Telegram — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда /newbot ), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.
Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.
Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova ). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot .
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index b64fb563..29b61f42 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -1,6 +1,6 @@
import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
-import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
+import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
@@ -8,12 +8,20 @@ import { EgovSign } from "@/components/EgovSign";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
+import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
const back = { back: "/settings" };
+function StepNum({ n, done }: { n: number; done: boolean }) {
+ return (
+
+ {done ? "✓" : n}
+
+ );
+}
+
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
@@ -27,9 +35,10 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
);
}
-export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string }> }) {
+export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string; bot?: string }> }) {
const user = await requireUser();
- const { error, egov, notify } = await searchParams;
+ const { error, egov, notify, bot } = await searchParams;
+ const hasBot = !!user.telegramBotUsername;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
const apps = await connectedApps(db, user.id);
@@ -38,6 +47,76 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const myProjects = await listUserProjects(db, user.id);
const pushSubs = await userPushSubscriptions(db, user.id);
const vapid = await vapidPublicKey(db);
+ // PEP-85: the three steps of connecting an own bot (shown when Telegram is not paired, or to switch).
+ const ownBotSteps = (
+
+
+ Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
+
+
+
+
+
+
Создайте бота в Telegram
+
+ Откройте @BotFather (официальный бот Telegram), отправьте ему /newbot , придумайте название и адрес — адрес должен заканчиваться на bot , например{" "}
+ my_factory_bot .
+
+ {!hasBot && (
+
+ Открыть BotFather
+
+ )}
+
+
+
+
+
+ Вставьте токен бота
+ {hasBot ? (
+
+ Подключён @{user.telegramBotUsername} . Токен хранится зашифрованным.
+
+ ) : (
+ <>
+ BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
+
+
+
+ Подключить бота
+
+ >
+ )}
+
+
+
+
+
+ Откройте своего бота и нажмите Start
+ Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.
+ {hasBot && (
+
+
+ Открыть @{user.telegramBotUsername}
+
+ )}
+
+
+
+ {hasBot ? (
+
+
+ Отключить этого бота
+
+ ) : (
+
+
+ Не хотите создавать бота?
+ Использовать общего бота Пеппы
+
+ )}
+
+ );
return (
@@ -111,6 +190,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
{user.egovIin && egov === "linked" &&
eGov привязан — теперь можно входить по QR }
+ {bot === "connected" && Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start. }
{user.telegramChatId ? (
}
>
- Вопросы агентов из ваших и общих проектов приходят в этот чат.
+ Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота @{user.telegramBotUsername} > : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
) : (
-
-
- Привязать Telegram
-
- }
- >
- Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
-
+ ownBotSteps
+ )}
+ {user.telegramChatId && !hasBot && (
+
+ {ownBotSteps}
+
+ )}
+ {user.telegramChatId && hasBot && (
+
+
+ Отключить бота @{user.telegramBotUsername}
+
)}
diff --git a/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md
new file mode 100644
index 00000000..ed14bcef
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/proposal.md
@@ -0,0 +1,18 @@
+# PEP-85: свой Telegram-бот у каждого пользователя
+
+## Why
+PM: у каждого пользователя должен быть свой Telegram-бот, через который он управляет своей фабрикой. Сейчас бот один на
+всех (`TELEGRAM_BOT_TOKEN`), у пользователей с ним только личные чаты.
+
+## What Changes
+- `users.telegram_bot_token_enc` (шифруется, входит в ротацию `PEPPA_SECRET`) и `telegram_bot_username` — миграция 0016.
+- core/telegram.ts: `verifyBotToken` (getMe у Telegram), `setUserBot` (проверка, один бот — один пользователь, сброс привязки чата),
+ `clearUserBot`, `userBots`. Код привязки, пришедший через свой бот, привязывает только его владельца; общий бот не привязывает
+ того, у кого есть свой. Offset и id обновлений — отдельные на каждого бота.
+- Бот-процесс: `syncOwnBots` раз в 10 с запускает и останавливает опрос своих ботов; обновление обрабатывается «через» бота,
+ в который пришло (AsyncLocalStorage); исходящие (вопросы, «готово», дайджест) уходят через бота владельца чата, остальное —
+ через общий. Свой бот отвечает только владельцу. Отозванный токен (401) — пауза минуту между попытками.
+- Веб «Настройки → Telegram»: три шага (BotFather → токен → Start в своём боте); общий бот — запасной вариант; у привязанных
+ к общему — «Перейти на своего бота». Шаг онбординга переименован.
+
+Вне scope: группы и каналы через свой бот (остаются на общем), вебхуки вместо опроса. Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md
new file mode 100644
index 00000000..a55d9ddd
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/specs/telegram-bot/spec.md
@@ -0,0 +1,24 @@
+## ADDED Requirements
+
+### Requirement: Свой бот пользователя
+Пользователь SHALL подключать собственного Telegram-бота, вставив его токен в
+«Настройки → Telegram»; токен проверяется у Telegram и хранится зашифрованным. Вопросы
+агентов и сообщения его проектов SHALL приходить ему из его бота, а его ответы — приниматься
+через него. Свой бот SHALL отвечать только владельцу.
+
+#### Scenario: Подключение
+- **WHEN** пользователь вставляет токен от BotFather и затем нажимает Start в своём боте по ссылке из Пеппы
+- **THEN** чат привязан, следующий вопрос агента приходит из его бота, из общего бота — ничего
+
+#### Scenario: Неверный токен
+- **WHEN** пользователь вставляет строку, которую Telegram не принимает
+- **THEN** бот не подключён, показано, что токен нужно скопировать целиком
+
+#### Scenario: Чужой человек
+- **WHEN** в бот пользователя пишет другой человек или приходит чужой код привязки
+- **THEN** бот не привязывает его и на команды не отвечает
+
+#### Scenario: Общий бот
+- **GIVEN** пользователь без своего бота, привязанный к общему
+- **WHEN** агент его проекта задаёт вопрос
+- **THEN** вопрос приходит из общего бота, как раньше
diff --git a/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md
new file mode 100644
index 00000000..f0e7d2ab
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-85-own-telegram-bot/tasks.md
@@ -0,0 +1,5 @@
+- [x] 1 Схема и миграция 0016, шифрованная колонка в ревизии секретов
+- [x] 2 core: проверка токена, подключение и отключение, привязка только владельца, offset и id по ботам
+- [x] 3 Бот-процесс: опрос своих ботов, маршрутизация ответов и исходящих
+- [x] 4 Веб: шаги подключения, действия, онбординг
+- [x] 5 `own-bot.test.ts` на двух mock-telegram, регресс `bot.test.ts`, `openspec validate`
diff --git a/openspec/specs/telegram-bot/spec.md b/openspec/specs/telegram-bot/spec.md
index cd6cd845..4dd57dcd 100644
--- a/openspec/specs/telegram-bot/spec.md
+++ b/openspec/specs/telegram-bot/spec.md
@@ -81,3 +81,26 @@ Telegram-бот Пеппы: однократная обработка updates,
- **GIVEN** у пользователя в проектах работают 2 сессии и открыт 1 вопрос
- **WHEN** он пишет `/status`
- **THEN** бот отвечает «Активные сессии: 2» со списком и «Открытых вопросов: 1»
+
+### Requirement: Свой бот пользователя
+Пользователь SHALL подключать собственного Telegram-бота, вставив его токен в
+«Настройки → Telegram»; токен проверяется у Telegram и хранится зашифрованным. Вопросы
+агентов и сообщения его проектов SHALL приходить ему из его бота, а его ответы — приниматься
+через него. Свой бот SHALL отвечать только владельцу.
+
+#### Scenario: Подключение
+- **WHEN** пользователь вставляет токен от BotFather и затем нажимает Start в своём боте по ссылке из Пеппы
+- **THEN** чат привязан, следующий вопрос агента приходит из его бота, из общего бота — ничего
+
+#### Scenario: Неверный токен
+- **WHEN** пользователь вставляет строку, которую Telegram не принимает
+- **THEN** бот не подключён, показано, что токен нужно скопировать целиком
+
+#### Scenario: Чужой человек
+- **WHEN** в бот пользователя пишет другой человек или приходит чужой код привязки
+- **THEN** бот не привязывает его и на команды не отвечает
+
+#### Scenario: Общий бот
+- **GIVEN** пользователь без своего бота, привязанный к общему
+- **WHEN** агент его проекта задаёт вопрос
+- **THEN** вопрос приходит из общего бота, как раньше
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index d92056f6..03126708 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -53,9 +53,9 @@ export async function onboardingChecklist(db: Db, user: Pick db.select({ id: users.id, enc: users.accessTokenEnc }).from(users).where(isNotNull(users.accessTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ accessTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "users", column: "refresh_token_enc", rows: () => db.select({ id: users.id, enc: users.refreshTokenEnc }).from(users).where(isNotNull(users.refreshTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ refreshTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "users", column: "claude_token_enc", rows: () => db.select({ id: users.id, enc: users.claudeTokenEnc }).from(users).where(isNotNull(users.claudeTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ claudeTokenEnc: enc }).where(eq(users.id, id)) },
+ { table: "users", column: "telegram_bot_token_enc", rows: () => db.select({ id: users.id, enc: users.telegramBotTokenEnc }).from(users).where(isNotNull(users.telegramBotTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ telegramBotTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "subscriptions", column: "secret_enc", rows: () => db.select({ id: subscriptions.id, enc: subscriptions.secretEnc }).from(subscriptions).where(isNotNull(subscriptions.secretEnc)), set: (id: number, enc: string) => db.update(subscriptions).set({ secretEnc: enc }).where(eq(subscriptions.id, id)) },
{ table: "project_secrets", column: "value_enc", rows: () => db.select({ id: projectSecrets.id, enc: projectSecrets.valueEnc }).from(projectSecrets), set: (id: number, enc: string) => db.update(projectSecrets).set({ valueEnc: enc }).where(eq(projectSecrets.id, id)) },
];
diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts
index f14ef30e..39ac1194 100644
--- a/packages/core/src/telegram.ts
+++ b/packages/core/src/telegram.ts
@@ -2,6 +2,8 @@ import { createHmac, randomBytes } from "node:crypto";
import { projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db";
import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+import { decrypt, encrypt } from "./crypto.ts";
+import { PeppaError } from "./errors.ts";
import type { User } from "./users.ts";
export type OutboxRow = typeof telegramOutbox.$inferSelect;
@@ -24,13 +26,19 @@ export async function acceptPairing(
db: Db,
secret: string,
code: string,
- who: { chatId: number; userId: number; username?: string | null },
+ who: { chatId: number; userId: number; username?: string | null; /** PEP-85: the owner of the bot the code came through (absent = the shared bot). */ botUserId?: number },
): Promise {
const key = pairKey(code, secret);
const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key);
if (!saved) return null;
await deleteSetting(db, key);
if (Date.now() >= saved.expiresAt) return null;
+ // A user's own bot pairs only its owner; the shared bot never pairs someone who has their own.
+ if (who.botUserId != null && who.botUserId !== saved.userId) return null;
+ if (who.botUserId == null) {
+ const [owner] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, saved.userId));
+ if (owner?.own) return null;
+ }
await db
.update(users)
.set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
@@ -65,21 +73,88 @@ export async function questionRecipients(db: Db, projectId: number): Promise (await getSetting(db, OFFSET)) ?? 0;
-export const setOffset = (db: Db, offset: number) => setSetting(db, OFFSET, offset);
+// PEP-85: every bot has its own update ids and offset. `botUserId` = the owner of a user's bot;
+// absent = the platform's shared bot (ids and the offset key as before).
+const offsetKey = (botUserId?: number) => (botUserId ? `${OFFSET}:u${botUserId}` : OFFSET);
+export const getOffset = async (db: Db, botUserId?: number) => (await getSetting(db, offsetKey(botUserId))) ?? 0;
+export const setOffset = (db: Db, offset: number, botUserId?: number) => setSetting(db, offsetKey(botUserId), offset);
+/** Update ids of different bots must not collide in `telegram_updates`. */
+const updateKey = (updateId: number, botUserId?: number) => (botUserId ? botUserId * 2 ** 36 + updateId : updateId);
/** Claims an update before acting on it. False = already taken (don't replay). */
-export async function claimUpdate(db: Db, updateId: number): Promise {
+export async function claimUpdate(db: Db, updateId: number, botUserId?: number): Promise {
const rows = await db
.insert(telegramUpdates)
- .values({ updateId, status: "dispatching" })
+ .values({ updateId: updateKey(updateId, botUserId), status: "dispatching" })
.onConflictDoNothing()
.returning();
return rows.length > 0;
}
-export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed"): Promise {
- await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateId));
+export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed", botUserId?: number): Promise {
+ await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateKey(updateId, botUserId)));
+}
+
+// ── PEP-85: the user's own bot ───────────────────────────────────────────────────
+
+export const BOT_TOKEN_RE = /^\d{5,15}:[A-Za-z0-9_-]{30,60}$/;
+
+export interface UserBot {
+ userId: number;
+ token: string;
+ username: string;
+ /** The chat the owner started the bot in (null until they press Start). */
+ chatId: number | null;
+}
+
+/** Asks Telegram who the token belongs to (`TELEGRAM_API_URL` for the mock). */
+export async function verifyBotToken(token: string): Promise<{ id: number; username: string }> {
+ const t = token.trim();
+ if (!BOT_TOKEN_RE.test(t)) throw new PeppaError("Это не похоже на токен бота. Он выглядит так: 1234567890:AAH… — скопируйте его целиком из сообщения BotFather");
+ let body: { ok?: boolean; result?: { id: number; username?: string; is_bot?: boolean }; description?: string };
+ try {
+ const res = await fetch(`${process.env.TELEGRAM_API_URL ?? "https://api.telegram.org"}/bot${t}/getMe`, { signal: AbortSignal.timeout(15_000) });
+ body = (await res.json()) as typeof body;
+ } catch {
+ throw new PeppaError("Telegram не ответил — попробуйте ещё раз через минуту");
+ }
+ if (!body.ok || !body.result?.username) throw new PeppaError("Telegram не принял этот токен — проверьте, что скопировали его целиком, или получите новый в BotFather (/token)");
+ return { id: body.result.id, username: body.result.username };
+}
+
+/** Connects the user's own bot. The chat pairing is dropped: the owner presses Start in the new bot. */
+export async function setUserBot(db: Db, userId: number, token: string): Promise<{ username: string }> {
+ const me = await verifyBotToken(token);
+ const taken = (await db.select({ id: users.id, username: users.telegramBotUsername }).from(users).where(isNotNull(users.telegramBotUsername))).find((u) => u.id !== userId && u.username?.toLowerCase() === me.username.toLowerCase());
+ if (taken) throw new PeppaError("Этот бот уже подключён другим пользователем — создайте своего в BotFather");
+ await db
+ .update(users)
+ .set({ telegramBotTokenEnc: encrypt(token.trim()), telegramBotUsername: me.username, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
+ .where(eq(users.id, userId));
+ return { username: me.username };
+}
+
+/** Back to the platform's shared bot (the chat pairing is dropped too). */
+export async function clearUserBot(db: Db, userId: number): Promise {
+ await db
+ .update(users)
+ .set({ telegramBotTokenEnc: null, telegramBotUsername: null, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
+ .where(eq(users.id, userId));
+}
+
+/** Every connected own bot (the bot process polls them and sends through them). */
+export async function userBots(db: Db): Promise {
+ const rows = await db.select().from(users).where(isNotNull(users.telegramBotTokenEnc));
+ const out: UserBot[] = [];
+ for (const u of rows) {
+ if (u.disabledAt) continue;
+ try {
+ out.push({ userId: u.id, token: decrypt(u.telegramBotTokenEnc!), username: u.telegramBotUsername ?? "", chatId: u.telegramChatId });
+ } catch {
+ // Unreadable after a key rotation gone wrong: skipped, the secrets audit shows it.
+ }
+ }
+ return out;
}
/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */
diff --git a/packages/db/migrations/0016_user_telegram_bot.sql b/packages/db/migrations/0016_user_telegram_bot.sql
new file mode 100644
index 00000000..40aaf827
--- /dev/null
+++ b/packages/db/migrations/0016_user_telegram_bot.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `users` ADD `telegram_bot_token_enc` text;--> statement-breakpoint
+ALTER TABLE `users` ADD `telegram_bot_username` text;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0016_snapshot.json b/packages/db/migrations/meta/0016_snapshot.json
new file mode 100644
index 00000000..041ac7f8
--- /dev/null
+++ b/packages/db/migrations/meta/0016_snapshot.json
@@ -0,0 +1,4120 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "adc91e4e-2273-4fb3-aaa1-fd9d3dc11061",
+ "prevId": "a95c0441-3ac0-47f1-a36d-b0caea076cbd",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "character": {
+ "name": "character",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "agents_name_unique": {
+ "name": "agents_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chat_messages": {
+ "name": "chat_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_key": {
+ "name": "thread_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thread_title": {
+ "name": "thread_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "important": {
+ "name": "important",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "author_kind": {
+ "name": "author_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_login": {
+ "name": "author_login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "via": {
+ "name": "via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_message_id": {
+ "name": "tg_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "chat_messages_dedupe_key_unique": {
+ "name": "chat_messages_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ },
+ "chat_messages_chat": {
+ "name": "chat_messages_chat",
+ "columns": [
+ "chat_id",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_created_at": {
+ "name": "chat_messages_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_tg": {
+ "name": "chat_messages_tg",
+ "columns": [
+ "tg_chat_id",
+ "tg_message_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "chat_messages_chat_id_chats_id_fk": {
+ "name": "chat_messages_chat_id_chats_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_messages_author_user_id_users_id_fk": {
+ "name": "chat_messages_author_user_id_users_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "author_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_question_id_questions_id_fk": {
+ "name": "chat_messages_question_id_questions_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_task_id_tasks_id_fk": {
+ "name": "chat_messages_task_id_tasks_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chats": {
+ "name": "chats",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_title": {
+ "name": "tg_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_at": {
+ "name": "tg_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_by": {
+ "name": "tg_linked_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "chats_user_id_unique": {
+ "name": "chats_user_id_unique",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": true
+ },
+ "chats_project_id_unique": {
+ "name": "chats_project_id_unique",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": true
+ },
+ "chats_tg_chat_id_unique": {
+ "name": "chats_tg_chat_id_unique",
+ "columns": [
+ "tg_chat_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_users_id_fk": {
+ "name": "chats_user_id_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_project_id_projects_id_fk": {
+ "name": "chats_project_id_projects_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_tg_linked_by_users_id_fk": {
+ "name": "chats_tg_linked_by_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "tg_linked_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "check_runs": {
+ "name": "check_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check": {
+ "name": "check",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_sec": {
+ "name": "duration_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'report'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "check_runs_project_sha_check": {
+ "name": "check_runs_project_sha_check",
+ "columns": [
+ "project_id",
+ "sha",
+ "check"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "check_runs_project_id_projects_id_fk": {
+ "name": "check_runs_project_id_projects_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "check_runs_task_id_tasks_id_fk": {
+ "name": "check_runs_task_id_tasks_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "code_reviews": {
+ "name": "code_reviews",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "findings": {
+ "name": "findings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "code_reviews_project_id_projects_id_fk": {
+ "name": "code_reviews_project_id_projects_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "code_reviews_task_id_tasks_id_fk": {
+ "name": "code_reviews_task_id_tasks_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "error_sources": {
+ "name": "error_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "columns": [
+ "bugsink_project_id"
+ ],
+ "isUnique": true
+ },
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ "project_id",
+ "kind"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "error_sources_project_id_projects_id_fk": {
+ "name": "error_sources_project_id_projects_id_fk",
+ "tableFrom": "error_sources",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "events": {
+ "name": "events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_kind": {
+ "name": "actor_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_channel": {
+ "name": "actor_channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_client_id": {
+ "name": "actor_client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "events_created_at": {
+ "name": "events_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "events_actor_user_id_users_id_fk": {
+ "name": "events_actor_user_id_users_id_fk",
+ "tableFrom": "events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "goals": {
+ "name": "goals",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incident_settings": {
+ "name": "incident_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[\"prod\",\"production\"]'"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "columns": [
+ "hook_secret"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_settings_project_id_projects_id_fk": {
+ "name": "incident_settings_project_id_projects_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incident_settings_goal_id_goals_id_fk": {
+ "name": "incident_settings_goal_id_goals_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incidents": {
+ "name": "incidents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "columns": [
+ "bugsink_issue_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incidents_project_id_projects_id_fk": {
+ "name": "incidents_project_id_projects_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_task_id_tasks_id_fk": {
+ "name": "incidents_task_id_tasks_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_clients": {
+ "name": "oauth_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_codes": {
+ "name": "oauth_codes",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_tokens": {
+ "name": "oauth_tokens",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_invites": {
+ "name": "project_invites",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "columns": [
+ "project_id",
+ "login"
+ ],
+ "name": "project_invites_project_id_login_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_members": {
+ "name": "project_members",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "columns": [
+ "project_id",
+ "user_id"
+ ],
+ "name": "project_members_project_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_secrets": {
+ "name": "project_secrets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value_enc": {
+ "name": "value_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "project_secrets_project_name": {
+ "name": "project_secrets_project_name",
+ "columns": [
+ "project_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "project_secrets_project_id_projects_id_fk": {
+ "name": "project_secrets_project_id_projects_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_secrets_created_by_users_id_fk": {
+ "name": "project_secrets_created_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_secrets_updated_by_users_id_fk": {
+ "name": "project_secrets_updated_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "updated_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "subscription_pool_id": {
+ "name": "subscription_pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "projects_subscription_pool_id_subscription_pools_id_fk": {
+ "name": "projects_subscription_pool_id_subscription_pools_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "subscription_pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_outbox": {
+ "name": "push_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "urgency": {
+ "name": "urgency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_outbox_dedupe_key_unique": {
+ "name": "push_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_outbox_subscription_id_push_subscriptions_id_fk": {
+ "name": "push_outbox_subscription_id_push_subscriptions_id_fk",
+ "tableFrom": "push_outbox",
+ "tableTo": "push_subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_subscriptions": {
+ "name": "push_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "p256dh": {
+ "name": "p256dh",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_ok_at": {
+ "name": "last_ok_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_subscriptions_endpoint_unique": {
+ "name": "push_subscriptions_endpoint_unique",
+ "columns": [
+ "endpoint"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_subscriptions_user_id_users_id_fk": {
+ "name": "push_subscriptions_user_id_users_id_fk",
+ "tableFrom": "push_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "questions": {
+ "name": "questions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "reminders": {
+ "name": "reminders",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "releases": {
+ "name": "releases",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "previous_sha": {
+ "name": "previous_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tasks": {
+ "name": "tasks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'deploying'"
+ },
+ "deployed_by": {
+ "name": "deployed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ci'"
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "releases_project_id_projects_id_fk": {
+ "name": "releases_project_id_projects_id_fk",
+ "tableFrom": "releases",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "review_settings": {
+ "name": "review_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "max_iterations": {
+ "name": "max_iterations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 2
+ },
+ "rules": {
+ "name": "rules",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "review_settings_project_id_projects_id_fk": {
+ "name": "review_settings_project_id_projects_id_fk",
+ "tableFrom": "review_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_commands": {
+ "name": "runner_commands",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_kind": {
+ "name": "error_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor": {
+ "name": "actor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_commands_status_idx": {
+ "name": "runner_commands_status_idx",
+ "columns": [
+ "status",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_hosts": {
+ "name": "runner_hosts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_target": {
+ "name": "ssh_target",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_port": {
+ "name": "ssh_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 22
+ },
+ "workdir": {
+ "name": "workdir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'peppa'"
+ },
+ "peppa_url": {
+ "name": "peppa_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "info": {
+ "name": "info",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "runner_hosts_name_unique": {
+ "name": "runner_hosts_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_tasks": {
+ "name": "runner_tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "front": {
+ "name": "front",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_tasks_session_idx": {
+ "name": "runner_tasks_session_idx",
+ "columns": [
+ "session_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "runner_tasks_session_id_sessions_id_fk": {
+ "name": "runner_tasks_session_id_sessions_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runner_tasks_task_id_tasks_id_fk": {
+ "name": "runner_tasks_task_id_tasks_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude'"
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rotate_reason": {
+ "name": "rotate_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_id": {
+ "name": "host_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container": {
+ "name": "container",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "watch_state": {
+ "name": "watch_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "columns": [
+ "tmux_name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_subscription_id_subscriptions_id_fk": {
+ "name": "sessions_subscription_id_subscriptions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_host_id_runner_hosts_id_fk": {
+ "name": "sessions_host_id_runner_hosts_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "runner_hosts",
+ "columnsFrom": [
+ "host_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pool_members": {
+ "name": "subscription_pool_members",
+ "columns": {
+ "pool_id": {
+ "name": "pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscription_pool_members_pool_id_subscription_pools_id_fk": {
+ "name": "subscription_pool_members_pool_id_subscription_pools_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subscription_pool_members_subscription_id_subscriptions_id_fk": {
+ "name": "subscription_pool_members_subscription_id_subscriptions_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subscription_pool_members_pool_id_subscription_id_pk": {
+ "columns": [
+ "pool_id",
+ "subscription_id"
+ ],
+ "name": "subscription_pool_members_pool_id_subscription_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pools": {
+ "name": "subscription_pools",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "subscription_pools_name_unique": {
+ "name": "subscription_pools_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "subscription_pools_created_by_users_id_fk": {
+ "name": "subscription_pools_created_by_users_id_fk",
+ "tableFrom": "subscription_pools",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth_kind": {
+ "name": "auth_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret_enc": {
+ "name": "secret_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "key_provider": {
+ "name": "key_provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "limited_until": {
+ "name": "limited_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "activated_at": {
+ "name": "activated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscriptions_created_by_users_id_fk": {
+ "name": "subscriptions_created_by_users_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_deps": {
+ "name": "task_deps",
+ "columns": {
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_by_id": {
+ "name": "blocked_by_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "task_deps_blocked_by": {
+ "name": "task_deps_blocked_by",
+ "columns": [
+ "blocked_by_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "task_deps_task_id_tasks_id_fk": {
+ "name": "task_deps_task_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_deps_blocked_by_id_tasks_id_fk": {
+ "name": "task_deps_blocked_by_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "blocked_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "task_deps_task_id_blocked_by_id_pk": {
+ "columns": [
+ "task_id",
+ "blocked_by_id"
+ ],
+ "name": "task_deps_task_id_blocked_by_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tasks": {
+ "name": "tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ci_attempts": {
+ "name": "ci_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "ci_failed_sha": {
+ "name": "ci_failed_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_issue": {
+ "name": "gitea_issue",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ "project_id",
+ "number"
+ ],
+ "isUnique": true
+ },
+ "tasks_project_issue": {
+ "name": "tasks_project_issue",
+ "columns": [
+ "project_id",
+ "gitea_issue"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_outbox": {
+ "name": "telegram_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "params": {
+ "name": "params",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "chat_message_id": {
+ "name": "chat_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "telegram_outbox_chat_message_id_chat_messages_id_fk": {
+ "name": "telegram_outbox_chat_message_id_chat_messages_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "chat_messages",
+ "columnsFrom": [
+ "chat_message_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_updates": {
+ "name": "telegram_updates",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_bot_token_enc": {
+ "name": "telegram_bot_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_bot_username": {
+ "name": "telegram_bot_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "egov_iin": {
+ "name": "egov_iin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "egov_linked_at": {
+ "name": "egov_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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 cc8db5f4..d91b73ba 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -113,6 +113,13 @@
"when": 1794665444878,
"tag": "0015_chats",
"breakpoints": true
+ },
+ {
+ "idx": 16,
+ "version": "6",
+ "when": 1794678698233,
+ "tag": "0016_user_telegram_bot",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index cdbc71d2..6521db13 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -31,6 +31,10 @@ export const users = sqliteTable("users", {
telegramUserId: integer("telegram_user_id"),
telegramUsername: text("telegram_username"),
telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
+ // PEP-85: the user's own bot (created in BotFather): its token, AES-256-GCM like every secret,
+ // and its @username. Null = the platform's shared bot.
+ telegramBotTokenEnc: text("telegram_bot_token_enc"),
+ telegramBotUsername: text("telegram_bot_username"),
// eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN.
egovIin: text("egov_iin").unique(),
egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }),
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 61a7bb33..26ea05bd 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -23,7 +23,11 @@ const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
export class MockTelegram {
readonly token = "mock-123:TOKEN";
- readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
+ /** PEP-85: a second instance stands in for a user's own bot — give it its own identity. */
+ constructor(bot: { id?: number; username?: string } = {}) {
+ this.bot = { id: bot.id ?? 999, username: bot.username ?? "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
+ }
+ readonly bot: { id: number; username: string; is_bot: boolean; first_name: string };
readonly messages = new Map();
readonly callbackAnswers: Array<{ id: string; text?: string }> = [];
readonly calls: Array<{ method: string; params: Record }> = [];
diff --git a/packages/testkit/test/own-bot.test.ts b/packages/testkit/test/own-bot.test.ts
new file mode 100644
index 00000000..cf463dff
--- /dev/null
+++ b/packages/testkit/test/own-bot.test.ts
@@ -0,0 +1,118 @@
+// PEP-85: a user's own Telegram bot — the token from BotFather, pairing by Start in that bot,
+// questions arrive from it, the shared bot keeps serving everybody else. Two mock-telegram
+// instances: the platform's bot and the user's.
+import assert from "node:assert/strict";
+import { after, before, describe, test } from "node:test";
+import { core, db, teardown, waitFor } from "./helpers.ts";
+import { MockTelegram } from "../src/mock-telegram.ts";
+import type { Bot } from "@peppa/bot";
+
+const { createBot } = await import("@peppa/bot");
+const { TelegramApi } = await import("@peppa/bot/telegram");
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const shared = await new MockTelegram().start();
+const own = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot" }).start();
+const OWN_TOKEN = "1234567890:" + "A".repeat(35);
+const ALICE = { id: 601, chatId: 601, username: "alice" };
+const BOB = { id: 602, chatId: 602, username: "bob" };
+const EVE = { id: 666, chatId: 666, username: "eve" };
+let bot: Bot;
+let alice: Awaited>;
+let bob: typeof alice;
+
+before(async () => {
+ alice = await core.upsertUserFromGitea(db, { id: 8501, login: "mock-own-alice" }, { access_token: "x" });
+ bob = await core.upsertUserFromGitea(db, { id: 8502, login: "mock-own-bob" }, { access_token: "y" });
+ bot = createBot({
+ db,
+ api: new TelegramApi(shared.token, shared.url),
+ userApi: (token) => new TelegramApi(token, own.url),
+ secret: shared.token,
+ webUrl: "http://peppa.test",
+ pollTimeoutSec: 1,
+ outboxIntervalMs: 100,
+ reconcileIntervalMs: 400,
+ userBotsIntervalMs: 200,
+ });
+ await bot.start();
+});
+after(async () => {
+ await bot.stop();
+ await shared.stop();
+ await own.stop();
+ await teardown();
+});
+
+describe("свой Telegram-бот", () => {
+ test("Scenario: токен проверяется у Telegram; привязка — Start в своём боте; вопрос приходит из него", async () => {
+ await assert.rejects(core.setUserBot(db, alice.id, "не токен"), /не похоже на токен бота/);
+ process.env.TELEGRAM_API_URL = own.url;
+ try {
+ own.failNext("getMe", 401);
+ await assert.rejects(core.setUserBot(db, alice.id, OWN_TOKEN), /Telegram не принял этот токен/);
+ assert.deepEqual(await core.setUserBot(db, alice.id, OWN_TOKEN), { username: "mock_alice_factory_bot" });
+ await assert.rejects(core.setUserBot(db, bob.id, OWN_TOKEN), /уже подключён другим пользователем/);
+ } finally {
+ delete process.env.TELEGRAM_API_URL;
+ }
+ const saved = (await core.getUser(db, alice.id))!;
+ assert.equal(saved.telegramBotUsername, "mock_alice_factory_bot");
+ assert.ok(saved.telegramBotTokenEnc && !saved.telegramBotTokenEnc.includes(OWN_TOKEN), "stored encrypted");
+ assert.deepEqual((await core.userBots(db)).map((b) => [b.userId, b.token, b.chatId]), [[alice.id, OWN_TOKEN, null]]);
+ await bot.syncOwnBots();
+
+ // The owner's code works only in her own bot.
+ const code = await core.createPairingCode(db, shared.token, alice.id);
+ shared.userSends(ALICE, `/start ${code}`);
+ await waitFor("the shared bot refuses", async () => shared.botMessages(ALICE.chatId).some((m) => /неверный или истёк/.test(m.text)));
+ assert.equal((await core.getUser(db, alice.id))!.telegramChatId, null);
+
+ // Somebody else's code does not work in her bot either.
+ own.userSends(EVE, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`);
+ await waitFor("her bot refuses a stranger", async () => own.botMessages(EVE.chatId).some((m) => /неверный или истёк/.test(m.text)));
+ assert.equal((await core.getUser(db, bob.id))!.telegramChatId, null);
+
+ own.userSends(ALICE, `/start ${await core.createPairingCode(db, shared.token, alice.id)}`);
+ await waitFor("paired in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => /Привязано/.test(m.text)));
+ assert.equal((await core.getUser(db, alice.id))!.telegramChatId, ALICE.chatId);
+
+ // A question of her project comes from her bot, not from the shared one.
+ const p = await core.createProject(db, { slug: "mock-own-a", key: "MOWNA", name: "Own A", giteaOwner: "x", workspacePath: "/tmp/mock-own-a", ownerId: alice.id });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Каталог" });
+ const sharedBefore = shared.botMessages(ALICE.chatId).length;
+ const q = await core.askPm(db, ref, { kind: "question", text: "Нужна ли мобильная версия?" });
+ await waitFor("question in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => m.text.includes("Нужна ли мобильная версия?")));
+ assert.equal(shared.botMessages(ALICE.chatId).length, sharedBefore, "nothing through the shared bot");
+
+ // She answers by a reply in her bot.
+ const msg = own.botMessages(ALICE.chatId).find((m) => m.text.includes("Нужна ли мобильная версия?"))!;
+ own.userSends(ALICE, "Не нужна", msg.message_id);
+ await waitFor("answered", async () => !!(await core.getQuestion(db, q.id)).answeredAt);
+ assert.equal((await core.getQuestion(db, q.id)).answer, "Не нужна");
+ });
+
+ test("Scenario: общий бот продолжает работать для остальных; чужому свой бот не отвечает", async () => {
+ shared.userSends(BOB, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`);
+ await waitFor("bob paired with the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => /Привязано/.test(m.text)));
+ const p = await core.createProject(db, { slug: "mock-own-b", key: "MOWNB", name: "Own B", giteaOwner: "x", workspacePath: "/tmp/mock-own-b", ownerId: bob.id });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" });
+ await core.askPm(db, ref, { kind: "question", text: "Какая валюта?" });
+ await waitFor("bob's question in the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => m.text.includes("Какая валюта?")));
+ assert.equal(own.botMessages(BOB.chatId).length, 0);
+
+ // Bob writes to Alice's bot: it serves its owner only.
+ const n = own.botMessages(BOB.chatId).length;
+ own.userSends(BOB, "/status");
+ await new Promise((r) => setTimeout(r, 1500));
+ assert.equal(own.botMessages(BOB.chatId).length, n);
+ });
+
+ test("отключение своего бота: опрос останавливается, привязка сбрасывается", async () => {
+ await core.clearUserBot(db, alice.id);
+ await bot.syncOwnBots();
+ const u = (await core.getUser(db, alice.id))!;
+ assert.deepEqual([u.telegramBotTokenEnc, u.telegramBotUsername, u.telegramChatId], [null, null, null]);
+ assert.deepEqual(await core.userBots(db), []);
+ });
+});
--
2.45.2
From 54182d0637383b08e0a1ab1e064bcf7474ae467f 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 23:04:25 +0500
Subject: [PATCH 033/439] PEP-86: connecting your own Telegram bot is the first
step, right on the Home page
Co-Authored-By: Claude Fable 5.2
---
apps/web/app/(app)/actions.ts | 5 +-
apps/web/app/(app)/page.tsx | 2 +-
apps/web/app/(app)/settings/page.tsx | 82 +----------------------
apps/web/components/Onboarding.tsx | 10 ++-
apps/web/components/OwnBotSteps.tsx | 97 ++++++++++++++++++++++++++++
packages/core/src/onboarding.ts | 2 +-
6 files changed, 113 insertions(+), 85 deletions(-)
create mode 100644 apps/web/components/OwnBotSteps.tsx
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 29f6a15c..e7e1b0ef 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -714,7 +714,8 @@ export async function connectOwnBotAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await setUserBot(db, user.id, String(f.get("token") ?? ""));
- return "/settings?bot=connected#telegram";
+ // On the Home page the next step (Start) shows right there.
+ return str(f, "back") === "/" ? "/" : "/settings?bot=connected#telegram";
});
}
@@ -722,6 +723,6 @@ export async function disconnectOwnBotAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await clearUserBot(db, user.id);
- return "/settings#telegram";
+ return str(f, "back") === "/" ? "/" : "/settings#telegram";
});
}
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 454e7bd9..7d80470d 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -20,7 +20,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}
- {onboarding.visible && }
+ {onboarding.visible && }
{items.map((q) => )}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 29b61f42..f57ba0ce 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -5,23 +5,16 @@ import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { EgovSign } from "@/components/EgovSign";
+import { OwnBotSteps } from "@/components/OwnBotSteps";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
+import { disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
const back = { back: "/settings" };
-function StepNum({ n, done }: { n: number; done: boolean }) {
- return (
-
- {done ? "✓" : n}
-
- );
-}
-
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
@@ -47,76 +40,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const myProjects = await listUserProjects(db, user.id);
const pushSubs = await userPushSubscriptions(db, user.id);
const vapid = await vapidPublicKey(db);
- // PEP-85: the three steps of connecting an own bot (shown when Telegram is not paired, or to switch).
- const ownBotSteps = (
-
-
- Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
-
-
-
-
-
-
Создайте бота в Telegram
-
- Откройте @BotFather (официальный бот Telegram), отправьте ему /newbot , придумайте название и адрес — адрес должен заканчиваться на bot , например{" "}
- my_factory_bot .
-
- {!hasBot && (
-
- Открыть BotFather
-
- )}
-
-
-
-
-
- Вставьте токен бота
- {hasBot ? (
-
- Подключён @{user.telegramBotUsername} . Токен хранится зашифрованным.
-
- ) : (
- <>
- BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
-
-
-
- Подключить бота
-
- >
- )}
-
-
-
-
-
- Откройте своего бота и нажмите Start
- Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.
- {hasBot && (
-
-
- Открыть @{user.telegramBotUsername}
-
- )}
-
-
-
- {hasBot ? (
-
-
- Отключить этого бота
-
- ) : (
-
-
- Не хотите создавать бота?
- Использовать общего бота Пеппы
-
- )}
-
- );
+ const ownBotSteps = ;
return (
diff --git a/apps/web/components/Onboarding.tsx b/apps/web/components/Onboarding.tsx
index e9959ceb..66f0ee1e 100644
--- a/apps/web/components/Onboarding.tsx
+++ b/apps/web/components/Onboarding.tsx
@@ -5,9 +5,10 @@ import type { Onboarding } from "@peppa/core";
import { dismissOnboardingAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
+import { OwnBotSteps } from "@/components/OwnBotSteps";
import { cn } from "@/lib/utils";
-export function OnboardingChecklist({ data }: { data: Onboarding }) {
+export function OnboardingChecklist({ data, botUsername = null }: { data: Onboarding; botUsername?: string | null }) {
const next = data.steps.find((s) => !s.done && !s.optional);
const fresh = data.done === 0;
return (
@@ -53,7 +54,12 @@ export function OnboardingChecklist({ data }: { data: Onboarding }) {
{s.title}
{!s.done &&
{s.hint} }
- {current && (
+ {current && s.id === "telegram" ? (
+ // PEP-85: the first thing to do — right here, not behind a link to Settings.
+
+
+
+ ) : current && (
{s.action}
diff --git a/apps/web/components/OwnBotSteps.tsx b/apps/web/components/OwnBotSteps.tsx
new file mode 100644
index 00000000..10c8e0e4
--- /dev/null
+++ b/apps/web/components/OwnBotSteps.tsx
@@ -0,0 +1,97 @@
+import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram } from "@/app/(app)/actions";
+import { Hidden } from "@/components/cards";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { cn } from "@/lib/utils";
+
+function StepNum({ n, done }: { n: number; done: boolean }) {
+ return (
+
+ {done ? "✓" : n}
+
+ );
+}
+
+/**
+ * PEP-85: connecting the user's own Telegram bot in three plain steps (BotFather → token →
+ * Start). Shown on the Home page as the first thing a new user does, and in Settings.
+ */
+export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: string | null; back: string; bare?: boolean }) {
+ const hasBot = !!botUsername;
+ const fields = { back };
+ return (
+
+ {!bare && (
+
+ Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
+
+ )}
+
+
+
+
+
Создайте бота в Telegram
+ {!hasBot && (
+ <>
+
+ Откройте @BotFather (официальный бот Telegram), отправьте ему /newbot , придумайте название и адрес — адрес должен заканчиваться на bot , например{" "}
+ my_factory_bot .
+
+
+ Открыть BotFather
+
+ >
+ )}
+
+
+
+
+
+ Вставьте токен бота
+ {hasBot ? (
+
+ Подключён @{botUsername} . Токен хранится зашифрованным.
+
+ ) : (
+ <>
+
+ BotFather пришлёт сообщение с длинной строкой вида 1234567890:AAH… — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
+
+
+
+
+ Подключить бота
+
+ >
+ )}
+
+
+
+
+
+ Откройте своего бота и нажмите Start
+ Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.
+ {hasBot && (
+
+
+ Открыть @{botUsername}
+
+ )}
+
+
+
+ {hasBot ? (
+
+
+ Отключить этого бота
+
+ ) : (
+
+
+ Не хотите создавать бота?
+ Использовать общего бота Пеппы
+
+ )}
+
+ );
+}
diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts
index 03126708..c63929c4 100644
--- a/packages/core/src/onboarding.ts
+++ b/packages/core/src/onboarding.ts
@@ -54,7 +54,7 @@ export async function onboardingChecklist(db: Db, user: Pick
Date: Sat, 14 Nov 2026 23:04:42 +0500
Subject: [PATCH 034/439] PEP-86: the Home page shows only the user's own
projects
Co-Authored-By: Claude Fable 5.2
---
apps/web/components/ProgressOverview.tsx | 15 +++------------
1 file changed, 3 insertions(+), 12 deletions(-)
diff --git a/apps/web/components/ProgressOverview.tsx b/apps/web/components/ProgressOverview.tsx
index 88eddb60..d74a196d 100644
--- a/apps/web/components/ProgressOverview.tsx
+++ b/apps/web/components/ProgressOverview.tsx
@@ -1,7 +1,7 @@
import Link from "next/link";
import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";
-import { Disclosure, Empty, Key } from "@/components/common";
+import { Empty, Key } from "@/components/common";
import { cn } from "@/lib/utils";
const PARTS = [
@@ -85,9 +85,9 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
);
}
-/** PEP-77: progress of all stories and projects on the Home page. */
+/** PEP-77: progress of the user's own projects on the Home page (other people's projects — on «Проекты», for a superadmin). */
export function ProgressOverview({ data }: { data: Overview }) {
- if (!data.mine.length && !data.others.length) return Проектов пока нет — прогресс появится с первой стори. ;
+ if (!data.mine.length) return Проектов пока нет — прогресс появится с первой стори. ;
const t = data.totals;
return (
@@ -108,15 +108,6 @@ export function ProgressOverview({ data }: { data: Overview }) {
))}
- {data.others.length > 0 && (
-
-
- {data.others.map((p) => (
-
- ))}
-
-
- )}
);
}
--
2.45.2
From 8c702b1d4e13fb11a1951f8371f17c378ebe93e7 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 23:42:15 +0500
Subject: [PATCH 035/439] PEP-87: the watchdog does not remind or escalate the
analyst's self-closing questions
Co-Authored-By: Claude Fable 5.2
---
packages/cli/src/index.ts | 2 ++
packages/runner/src/recovery.ts | 3 +++
packages/runner/src/tmux.ts | 30 ++++++++++++++++++++++++++++
packages/testkit/test/intake.test.ts | 5 +++++
4 files changed, 40 insertions(+)
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 19693b9d..24fbec79 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -643,6 +643,8 @@ async function main(): Promise {
const ob = await outboxStats(db);
console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`);
console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`);
+ const foreign = await tmux.foreignServerEnv().catch(() => []);
+ if (foreign.length) console.log(`⚠ в окружении tmux-сервера чужие переменные: ${foreign.join(", ")} — агенты их унаследуют; очистятся при следующем запуске раннера или: ${foreign.map((n) => `tmux set-environment -g -u ${n}`).join("; ")}`);
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
console.log(`админы: ${admins.join(", ") || "нет"}`);
diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts
index 4d156bdb..86769fa2 100644
--- a/packages/runner/src/recovery.ts
+++ b/packages/runner/src/recovery.ts
@@ -19,6 +19,7 @@ import {
setSetting,
updateSession,
type SessionView,
+ getIntakeState,
} from "@peppa/core";
import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@@ -227,6 +228,8 @@ export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
.where(and(isNull(questions.answeredAt), inArray(questions.kind, [...REMIND_KINDS]), gestDay(now)));
let sent = 0;
for (const { q, projectKey, taskNumber } of rows) {
+ // PEP-87: the analyst's questions close themselves at their deadline (PEP-84) — no nagging.
+ if (q.taskId && (await getIntakeState(db, q.taskId))?.questionId === q.id) continue;
const age = now - q.createdAt.getTime();
const ageMin = Math.round(age / 60_000);
const n = q.reminders;
diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts
index 71ad3c8c..a63468e7 100644
--- a/packages/runner/src/tmux.ts
+++ b/packages/runner/src/tmux.ts
@@ -41,6 +41,35 @@ export interface NewTmuxSession {
width?: number;
}
+/**
+ * PEP-69: names that must never come from a tmux server's global environment. Every session
+ * inherits it, and a server started by some test run or tool shell carries that process's
+ * GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place.
+ * What an agent needs is passed per session (`new-session -e`) or read from `.env`.
+ */
+const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/;
+
+/** Foreign variables in the global environment of the tmux server (default server only). */
+export async function foreignServerEnv(p: Pane = { name: "" }): Promise {
+ // A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it.
+ if (process.env.PEPPA_TMUX_SOCKET) return [];
+ let out: string;
+ try {
+ out = await tmuxOn(p, ["show-environment", "-g"]);
+ } catch (e) {
+ if (e instanceof HostUnreachable) throw e;
+ return []; // no server running
+ }
+ return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k));
+}
+
+/** Removes them from the server's global environment; returns the names removed. */
+export async function scrubServerEnv(p: Pane = { name: "" }): Promise {
+ const names = await foreignServerEnv(p);
+ for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]);
+ return names;
+}
+
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}`]);
@@ -48,6 +77,7 @@ export async function newSession(s: NewTmuxSession): Promise {
// 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.
await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]);
+ await scrubServerEnv(p).catch(() => {}); // PEP-69
await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]);
// Keep the pane after claude exits so the watchdog can read the exit status.
await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]);
diff --git a/packages/testkit/test/intake.test.ts b/packages/testkit/test/intake.test.ts
index 2e235a7b..b0829fb5 100644
--- a/packages/testkit/test/intake.test.ts
+++ b/packages/testkit/test/intake.test.ts
@@ -68,6 +68,11 @@ describe("Продакт и аналитик", () => {
assert.equal(q!.id, state.questionId);
assert.match(q!.text, /Нужна ли мобильная версия\?\n\s+По умолчанию: Да, страница открывается с телефона/);
+ // PEP-87: the question closes itself at the deadline, so the watchdog does not nag about it.
+ const cfg = await runner.getWatchdogSettings(db);
+ assert.equal(await runner.remindTick(db, { now: new Date(Date.now() + 3 * 3600_000), cfg, log: () => {} }), 0);
+ assert.equal((await core.getQuestion(db, q!.id)).reminders, 0);
+
// The PM answers: the analyst finishes with the answer and asks nothing more.
await runner.answerAndDeliver(db, q!.id, "Мобильная не нужна, только ноутбук", "web");
assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "finalize");
--
2.45.2
From b47d2e80228ef933272ae344f29eb2d2ea033038 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 23:43:58 +0500
Subject: [PATCH 036/439] PEP-87: drop another story's unfinished edits swept
into this branch
Co-Authored-By: Claude Fable 5.2
---
packages/cli/src/index.ts | 2 --
packages/runner/src/tmux.ts | 30 ------------------------------
2 files changed, 32 deletions(-)
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 24fbec79..19693b9d 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -643,8 +643,6 @@ async function main(): Promise {
const ob = await outboxStats(db);
console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`);
console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`);
- const foreign = await tmux.foreignServerEnv().catch(() => []);
- if (foreign.length) console.log(`⚠ в окружении tmux-сервера чужие переменные: ${foreign.join(", ")} — агенты их унаследуют; очистятся при следующем запуске раннера или: ${foreign.map((n) => `tmux set-environment -g -u ${n}`).join("; ")}`);
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
console.log(`админы: ${admins.join(", ") || "нет"}`);
diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts
index a63468e7..71ad3c8c 100644
--- a/packages/runner/src/tmux.ts
+++ b/packages/runner/src/tmux.ts
@@ -41,35 +41,6 @@ export interface NewTmuxSession {
width?: number;
}
-/**
- * PEP-69: names that must never come from a tmux server's global environment. Every session
- * inherits it, and a server started by some test run or tool shell carries that process's
- * GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place.
- * What an agent needs is passed per session (`new-session -e`) or read from `.env`.
- */
-const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/;
-
-/** Foreign variables in the global environment of the tmux server (default server only). */
-export async function foreignServerEnv(p: Pane = { name: "" }): Promise {
- // A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it.
- if (process.env.PEPPA_TMUX_SOCKET) return [];
- let out: string;
- try {
- out = await tmuxOn(p, ["show-environment", "-g"]);
- } catch (e) {
- if (e instanceof HostUnreachable) throw e;
- return []; // no server running
- }
- return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k));
-}
-
-/** Removes them from the server's global environment; returns the names removed. */
-export async function scrubServerEnv(p: Pane = { name: "" }): Promise {
- const names = await foreignServerEnv(p);
- for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]);
- return names;
-}
-
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}`]);
@@ -77,7 +48,6 @@ export async function newSession(s: NewTmuxSession): Promise {
// 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.
await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]);
- await scrubServerEnv(p).catch(() => {}); // PEP-69
await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]);
// Keep the pane after claude exits so the watchdog can read the exit status.
await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]);
--
2.45.2
From 14177684d4fcf6dc197718529fe260a9ada53d9c 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 23:48:34 +0500
Subject: [PATCH 037/439] PEP-88: a superadmin manages any project like its
owner
Co-Authored-By: Claude Fable 5.2
---
apps/web/app/(app)/actions.ts | 4 +--
apps/web/app/(app)/p/[key]/page.tsx | 3 ++-
.../proposal.md | 13 ++++++++++
.../specs/web-auth/spec.md | 15 +++++++++++
.../tasks.md | 3 +++
openspec/specs/web-auth/spec.md | 14 ++++++++++
packages/runner/src/share.ts | 14 +++++++---
packages/testkit/test/web.test.ts | 26 +++++++++++++++++++
8 files changed, 85 insertions(+), 7 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index e7e1b0ef..29671a88 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -59,7 +59,7 @@ import {
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
+import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@@ -507,7 +507,7 @@ export async function connectErrorTrackingAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
- if (p.ownerId !== user.id) throw new PeppaError("Подключает владелец проекта");
+ if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта");
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
});
}
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index b8121705..a2e8619c 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -99,9 +99,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const noRepoAccess = (login: string) =>
repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
const missingAccess = team.members.some((m) => noRepoAccess(m.login));
- const isOwner = p.ownerId === user.id;
// PEP-67: default subscription pool; only a superadmin changes it.
const superadmin = await isSuperadmin(db, user);
+ // PEP-88: a superadmin manages any project like its owner.
+ const isOwner = p.ownerId === user.id || superadmin;
const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
// PEP-10/27: runner settings of the project over the system ones.
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
diff --git a/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md
new file mode 100644
index 00000000..170b47a9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/proposal.md
@@ -0,0 +1,13 @@
+# PEP-88: суперадмин управляет любым проектом как владелец
+
+## Why
+Модель доступа: каждый видит своё пространство и свои проекты; суперадмин видит всё и управляет всем. После PEP-74
+суперадмин открывал чужой проект с правами участника, но участниками, видимостью репозитория и подключением
+отслеживания ошибок управлял только владелец.
+
+## What Changes
+- `managesProject(db, actor, project)` (runner/share.ts): владелец или суперадмин. На нём — `shareProject`, `unshareProject`,
+ `grantRepoAccess`, `setProjectVisibility`, действие подключения отслеживания ошибок.
+- Страница проекта: блоки владельца показываются и суперадмину.
+
+Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md
new file mode 100644
index 00000000..98933f44
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/specs/web-auth/spec.md
@@ -0,0 +1,15 @@
+## ADDED Requirements
+
+### Requirement: Суперадмин управляет любым проектом
+Суперадмин SHALL выполнять в любом проекте действия владельца: добавлять и убирать
+участников, менять видимость репозитория, подключать отслеживание ошибок. Обычный
+пользователь SHALL управлять только своими проектами.
+
+#### Scenario: Суперадмин добавляет участника
+- **GIVEN** проект «PAY» пользователя «dana» и суперадмин «asel»
+- **WHEN** asel добавляет в «PAY» участника «kate»
+- **THEN** kate видит проект «PAY»
+
+#### Scenario: Посторонний
+- **WHEN** пользователь, не владелец и не суперадмин, пытается добавить участника в «PAY»
+- **THEN** действие отклонено
diff --git a/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md
new file mode 100644
index 00000000..94eb0188
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-88-superadmin-manages/tasks.md
@@ -0,0 +1,3 @@
+- [x] 1 `managesProject` и проверки в share.ts, действие отслеживания ошибок
+- [x] 2 Страница проекта: блоки владельца для суперадмина
+- [x] 3 Тест в `web.test.ts`, `openspec validate`
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index 49332709..a81a41df 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -179,3 +179,17 @@ nonce, созданные сервером для этого потока; по
- **GIVEN** пользователь «kate» не суперадмин и не участник «TZK»
- **WHEN** она открывает `/p/TZK`
- **THEN** она получает «не найдено», секции «Проекты других» у неё нет
+
+### Requirement: Суперадмин управляет любым проектом
+Суперадмин SHALL выполнять в любом проекте действия владельца: добавлять и убирать
+участников, менять видимость репозитория, подключать отслеживание ошибок. Обычный
+пользователь SHALL управлять только своими проектами.
+
+#### Scenario: Суперадмин добавляет участника
+- **GIVEN** проект «PAY» пользователя «dana» и суперадмин «asel»
+- **WHEN** asel добавляет в «PAY» участника «kate»
+- **THEN** kate видит проект «PAY»
+
+#### Scenario: Посторонний
+- **WHEN** пользователь, не владелец и не суперадмин, пытается добавить участника в «PAY»
+- **THEN** действие отклонено
diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts
index 4d5abdc2..2affa770 100644
--- a/packages/runner/src/share.ts
+++ b/packages/runner/src/share.ts
@@ -14,6 +14,7 @@ import {
type RepoInfo,
type Project,
type User,
+ isSuperadmin,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
@@ -33,6 +34,11 @@ export async function repoAdmins(db: Db, project: Project): Promise): Promise {
+ return project.ownerId === actor.id || (await isSuperadmin(db, actor));
+}
+
export interface ShareResult {
login: string;
status: "added" | "invited";
@@ -42,7 +48,7 @@ export interface ShareResult {
/** Owner adds a person (by Gitea login) to the project and to its repo (write). */
export async function shareProject(db: Db, actor: User, project: Project, loginInput: string): Promise {
- if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта");
+ if (!(await managesProject(db, actor, project))) throw new PeppaError("Участниками управляет только владелец проекта");
const login = loginInput.trim().replace(/^@/, "");
if (!login) throw new PeppaError("Укажите логин Gitea");
// PEP-68: a local Peppa user (no Gitea account) becomes a member without repo access.
@@ -74,7 +80,7 @@ export async function shareProject(db: Db, actor: User, project: Project, loginI
export async function unshareProject(db: Db, actor: User, project: Project, loginInput: string): Promise {
const login = loginInput.trim().replace(/^@/, "");
const self = actor.login.toLowerCase() === login.toLowerCase();
- if (project.ownerId !== actor.id && !self) throw new PeppaError("Участниками управляет только владелец проекта");
+ if (!self && !(await managesProject(db, actor, project))) throw new PeppaError("Участниками управляет только владелец проекта");
if (!(await removeMember(db, project.id, login))) throw new PeppaError(`«${login}» не участник проекта`);
describeCache.delete(project.id);
if (await localUser(db, login)) return; // not a Gitea collaborator; the same Gitea login may be someone else
@@ -93,7 +99,7 @@ async function localUser(db: Db, login: string): Promise {
/** Owner adds every member (not pending invites) as a repo collaborator; returns who failed. */
export async function grantRepoAccess(db: Db, actor: User, project: Project): Promise<{ granted: string[]; failed: string[] }> {
- if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта");
+ if (!(await managesProject(db, actor, project))) throw new PeppaError("Участниками управляет только владелец проекта");
const clients = await repoAdmins(db, project);
const { members } = await listMembers(db, project);
const granted: string[] = [];
@@ -122,7 +128,7 @@ export type Visibility = "public" | "private";
*/
export async function setProjectVisibility(db: Db, project: Project, visibility: Visibility, opts: { actor?: User } = {}): Promise {
if (visibility !== "public" && visibility !== "private") throw new PeppaError(`Видимость: public или private, не «${visibility}»`);
- if (opts.actor && project.ownerId !== opts.actor.id) throw new PeppaError("Видимость репозитория меняет только владелец проекта");
+ if (opts.actor && !(await managesProject(db, opts.actor, project))) throw new PeppaError("Видимость репозитория меняет только владелец проекта");
const fullName = `${project.giteaOwner}/${project.giteaRepo}`;
const clients = await repoAdmins(db, project);
if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново");
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 365405f7..bc693c83 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -216,3 +216,29 @@ describe("новый проект: настройки по умолчанию",
assert.equal((await core.projectPool(db, second.id))!.id, pool.id, "connected once — not asked again");
});
});
+
+describe("PEP-88: суперадмин управляет любым проектом", () => {
+ test("участники и видимость чужого проекта — суперадмину можно, постороннему нельзя", async () => {
+ const owner = await core.upsertUserFromGitea(db, { id: 8801, login: "mock-p88-owner" }, { access_token: "x" });
+ const boss = await core.upsertUserFromGitea(db, { id: 8802, login: "mock-p88-boss" }, { access_token: "x" });
+ // A Peppa account without Gitea: it becomes a member without a repo collaborator call.
+ const other = await core.registerEgovUser(db, { iin: "850505400058", name: "ДРУГОЙ УЧАСТНИК" });
+ const p = await core.createProject(db, { slug: "mock-p88", key: "MPMNG", name: "P88", giteaOwner: "x", workspacePath: "/tmp/mock-p88", ownerId: owner.id });
+ assert.equal(await runner.managesProject(db, owner, p), true);
+ assert.equal(await runner.managesProject(db, other, p), false);
+ assert.equal(await runner.managesProject(db, boss, p), false);
+ await assert.rejects(runner.shareProject(db, boss, p, other.login), /только владелец/);
+ await core.setPlatformAdmins(db, ["mock-p88-boss"]);
+ try {
+ assert.equal(await runner.managesProject(db, boss, p), true);
+ const r = await runner.shareProject(db, boss, p, other.login);
+ assert.equal(r.login, other.login);
+ assert.ok((await core.userProjectIds(db, other.id)).includes(p.id));
+ await runner.unshareProject(db, boss, p, other.login);
+ assert.ok(!(await core.userProjectIds(db, other.id)).includes(p.id));
+ await assert.rejects(runner.shareProject(db, other, p, "mock-p88-boss"), /только владелец/);
+ } finally {
+ await core.setPlatformAdmins(db, null);
+ }
+ });
+});
--
2.45.2
From 19f95773495d023afb8659a05c24b5aafabf9cd1 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 23:50:13 +0500
Subject: [PATCH 038/439] =?UTF-8?q?PEP-87:=20OpenSpec=20change=20=E2=80=94?=
=?UTF-8?q?=20the=20watchdog=20skips=20the=20analyst's=20questions=20(arch?=
=?UTF-8?q?ived=20into=20watchdog-recovery)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
.../design.md | 17 ++++++++++++++
.../proposal.md | 23 +++++++++++++++++++
.../specs/watchdog-recovery/spec.md | 18 +++++++++++++++
.../tasks.md | 4 ++++
openspec/specs/watchdog-recovery/spec.md | 9 +++++++-
5 files changed, 70 insertions(+), 1 deletion(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md
diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md
new file mode 100644
index 00000000..4c944a70
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/design.md
@@ -0,0 +1,17 @@
+## Context
+
+`remindTick` (runner/recovery.ts) выбирает неотвеченные вопросы видов question/permission/approval моложе суток. Вопрос аналитика — обычный `askPm`, его id хранится в состоянии приёма стори (`intake.task:` → `questionId`), и `intakeTick` сам закрывает его по сроку.
+
+## Goals / Non-Goals
+
+- Цель: по вопросу аналитика не уходит ни напоминание, ни эскалация.
+- Не цель: менять сроки приёма, тихие часы или первое уведомление о вопросе.
+
+## Decisions
+
+- Признак «вопрос аналитика» — `getIntakeState(db, q.taskId)?.questionId === q.id`. Отдельной колонки или вида вопроса не вводим: состояние приёма уже источник правды, миграция не нужна. Альтернатива (новый `kind`) затронула бы бота, чаты и уведомления.
+- Проверка стоит в начале цикла, до claim счётчика `reminders`: он остаётся 0, и, если вопрос перестанет быть вопросом аналитика, обычные правила применятся к нему с начала.
+
+## Risks / Trade-offs
+
+- Лишний запрос `settings` на каждый открытый вопрос за тик — открытых вопросов единицы, тик раз в 30 с.
diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md
new file mode 100644
index 00000000..2aaf14c4
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/proposal.md
@@ -0,0 +1,23 @@
+## Why
+
+Вопрос аналитика (PEP-84) закрывается сам по сроку `waitMin`, а срок сдвигается за тихие часы. Вачдог при этом напоминал о нём каждые `remindMin` и эскалировал админам (случай: демо в SBX ночью — срок сдвинулся до утра, напоминания шли каждые полчаса).
+
+## What Changes
+
+- `remindTick` пропускает открытый вопрос аналитика (вопрос из состояния приёма стори): ни напоминаний аудитории, ни эскалации админам.
+- Остальные вопросы (агент, разрешения, одобрения) напоминаются как раньше.
+
+## Capabilities
+
+### New Capabilities
+
+Нет.
+
+### Modified Capabilities
+
+- `watchdog-recovery`: требование «Напоминание и эскалация вопросов» — исключение для вопросов аналитика.
+
+## Impact
+
+- `packages/runner/src/recovery.ts` (`remindTick`), тест `packages/testkit/test/intake.test.ts`.
+- Схема БД, API и настройки не меняются.
diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md
new file mode 100644
index 00000000..df0f1b92
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/specs/watchdog-recovery/spec.md
@@ -0,0 +1,18 @@
+## MODIFIED Requirements
+
+### Requirement: Напоминание и эскалация вопросов
+Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. О вопросе аналитика (приём стори перед бэклогом), который закрывается сам по сроку, вачдог SHALL NOT напоминать и SHALL NOT эскалировать его админам.
+
+#### Scenario: Вопрос висит
+- **GIVEN** агент спросил PM в 10:00
+- **WHEN** в 10:30 ответа нет
+- **THEN** участники проекта получают «⏰ Вопрос #N ждёт ответа 30 мин»
+- **AND** в 11:00 — второе напоминание, в 12:00 — эскалация админам
+- **AND** повторные тики вачдога новых сообщений не создают
+
+#### Scenario: Вопрос аналитика
+- **GIVEN** аналитик спросил PM по новой стори в 10:00 и ждёт ответа до срока приёма
+- **WHEN** в 13:00 ответа нет и тикает вачдог
+- **THEN** участники проекта не получают «⏰ Вопрос #N ждёт ответа»
+- **AND** админы платформы не получают эскалацию
+- **AND** вопрос остаётся открытым до своего срока
diff --git a/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md
new file mode 100644
index 00000000..aa50280b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-87-intake-questions-no-reminders/tasks.md
@@ -0,0 +1,4 @@
+## 1. Вачдог
+
+- [x] 1.1 `remindTick` пропускает вопрос, чей id записан в состоянии приёма стори
+- [x] 1.2 Тест сценария «Вопрос аналитика» в `intake.test.ts`: через 3 часа напоминаний нет, `reminders` = 0
diff --git a/openspec/specs/watchdog-recovery/spec.md b/openspec/specs/watchdog-recovery/spec.md
index b014e587..0a60b7a4 100644
--- a/openspec/specs/watchdog-recovery/spec.md
+++ b/openspec/specs/watchdog-recovery/spec.md
@@ -38,7 +38,7 @@
- **THEN** tmux-сессия убита, раннер продолжает разговор заново, алерт закрыт
### Requirement: Напоминание и эскалация вопросов
-Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз.
+Вачдог SHALL напоминать аудитории проекта о неотвеченном вопросе через `remindMin` и ещё раз через столько же, а после `escalateMin` SHALL сообщать админам платформы; каждое сообщение — один раз. О вопросе аналитика (приём стори перед бэклогом), который закрывается сам по сроку, вачдог SHALL NOT напоминать и SHALL NOT эскалировать его админам.
#### Scenario: Вопрос висит
- **GIVEN** агент спросил PM в 10:00
@@ -47,6 +47,13 @@
- **AND** в 11:00 — второе напоминание, в 12:00 — эскалация админам
- **AND** повторные тики вачдога новых сообщений не создают
+#### Scenario: Вопрос аналитика
+- **GIVEN** аналитик спросил PM по новой стори в 10:00 и ждёт ответа до срока приёма
+- **WHEN** в 13:00 ответа нет и тикает вачдог
+- **THEN** участники проекта не получают «⏰ Вопрос #N ждёт ответа»
+- **AND** админы платформы не получают эскалацию
+- **AND** вопрос остаётся открытым до своего срока
+
### Requirement: Уборка давних waiting_input
Раннер стори в `waiting_input` без открытых вопросов дольше `idleStopHours` SHALL останавливаться с сообщением PM.
--
2.45.2
From 03d358f9f2b20b8098b61801dd634b112099d33a 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 23:44:33 +0500
Subject: [PATCH 039/439] PEP-69: scrub foreign env from the tmux server before
starting runners; warn in peppa status
Co-Authored-By: Claude Sonnet 5.5
---
.peppa/memory.md | 1 +
.../design.md | 2 +
.../proposal.md | 9 +++
.../specs/agent-runner/spec.md | 22 +++++
.../tasks.md | 4 +
.../changes/pep-4-gitea-org/.openspec.yaml | 2 +
openspec/changes/pep-4-gitea-org/design.md | 80 +++++++++++++++++++
openspec/changes/pep-4-gitea-org/proposal.md | 46 +++++++++++
.../pep-4-gitea-org/specs/peppa-ci/spec.md | 48 +++++++++++
.../specs/project-provisioning/spec.md | 38 +++++++++
openspec/changes/pep-4-gitea-org/tasks.md | 27 +++++++
openspec/specs/agent-runner/spec.md | 25 ++++++
packages/cli/src/index.ts | 4 +-
packages/runner/src/tmux.ts | 30 +++++++
packages/testkit/test/tmux-env.test.ts | 40 ++++++++++
15 files changed, 377 insertions(+), 1 deletion(-)
create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md
create mode 100644 openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md
create mode 100644 openspec/changes/pep-4-gitea-org/.openspec.yaml
create mode 100644 openspec/changes/pep-4-gitea-org/design.md
create mode 100644 openspec/changes/pep-4-gitea-org/proposal.md
create mode 100644 openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
create mode 100644 openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md
create mode 100644 openspec/changes/pep-4-gitea-org/tasks.md
create mode 100644 openspec/specs/agent-runner/spec.md
create mode 100644 packages/testkit/test/tmux-env.test.ts
diff --git a/.peppa/memory.md b/.peppa/memory.md
index f1299459..4e1d2691 100644
--- a/.peppa/memory.md
+++ b/.peppa/memory.md
@@ -8,3 +8,4 @@
## Решения
- Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents.
+- tmux-сервер по умолчанию: newSession чистит его глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69; при PEPPA_TMUX_SOCKET не трогает); агенту нужное — только через new-session -e.
diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md
new file mode 100644
index 00000000..3c3e5da5
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/design.md
@@ -0,0 +1,2 @@
+# Дизайн
+Выбрано: чистка глобального окружения при `newSession` (после `start-server`), а не отдельный сокет `-L peppa` — смена сокета оторвала бы живые раннеры, ушедшие на сервер по умолчанию, и ломает `tmux attach` PM. Чистка идемпотентна и дешёвая (`show-environment -g` + `set-environment -g -u`). Всё нужное агенту уже передаётся через `-e` (`PEPPA_SESSION_ID`, `PEPPA_DB`, `PEPPA_HOME`, подписка), остальное MCP берёт из `.env`. Правка `load-env.sh` не годится: тесты нарочно ставят `GITEA_TOKEN=""`. Для выделенного сокета чистки нет — это сервер владельца (тесты), моки CLI читают свои переменные оттуда.
diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md
new file mode 100644
index 00000000..2c8735f4
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/proposal.md
@@ -0,0 +1,9 @@
+# PEP-69: агенты не наследуют окружение чужого tmux-сервера
+
+## Почему
+Раннеры живут на tmux-сервере по умолчанию. Если его запустил тестовый прогон или оболочка Claude Code, глобальное окружение сервера (GITEA_URL, PEPPA_HOME, PEPPA_CLAUDE_BIN, DATABASE_URL, пустой GITEA_TOKEN) наследуют все сессии, и MCP агента ломается («GITEA_TOKEN is not set»).
+
+## Что меняется
+- Перед созданием сессии раннер-сервис вычищает из глобального окружения tmux-сервера переменные `GITEA_*`, `PEPPA_*`, `MOCK_*`, `DATABASE_URL`; нужное агенту уходит явно (`new-session -e`) или читается из `.env`.
+- `peppa status` предупреждает о чужих переменных в окружении сервера.
+- Выделенный сокет (`PEPPA_TMUX_SOCKET`, тесты) не трогается.
diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md
new file mode 100644
index 00000000..9bb397b6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/specs/agent-runner/spec.md
@@ -0,0 +1,22 @@
+# Spec Delta: agent-runner
+
+## ADDED Requirements
+
+### Requirement: Окружение раннера не наследуется от чужого tmux-сервера
+Раннер SHALL запускать агентов так, чтобы они не получали `GITEA_*`, `PEPPA_*`, `MOCK_*`, `DATABASE_URL` из глобального окружения tmux-сервера по умолчанию, а `peppa status` SHALL предупреждать, если такие переменные там есть.
+
+#### Scenario: Сервер запущен тестовой оболочкой
+- **GIVEN** tmux-сервер по умолчанию с глобальной переменной `GITEA_URL=http://127.0.0.1:9`
+- **WHEN** раннер-сервис запускает сессию стори
+- **THEN** `GITEA_URL` удалена из глобального окружения сервера
+- **AND** переменные сессии (`PEPPA_SESSION_ID`) переданы явно
+
+#### Scenario: Предупреждение в статусе
+- **GIVEN** в окружении tmux-сервера есть `MOCK_X`
+- **WHEN** PM запускает `peppa status`
+- **THEN** выводится предупреждение со списком переменных и командой очистки
+
+#### Scenario: Выделенный сокет не трогается
+- **GIVEN** задан `PEPPA_TMUX_SOCKET`
+- **WHEN** запускается сессия
+- **THEN** окружение этого сервера не чистится
diff --git a/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md
new file mode 100644
index 00000000..b38cba00
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-69-runner-tmux-env/tasks.md
@@ -0,0 +1,4 @@
+## 1. Реализация
+- [x] 1.1 `tmux.foreignServerEnv` / `scrubServerEnv`, чистка в `newSession`
+- [x] 1.2 Предупреждение в `peppa status`
+- [x] 1.3 Тест `tmux-env.test.ts`
diff --git a/openspec/changes/pep-4-gitea-org/.openspec.yaml b/openspec/changes/pep-4-gitea-org/.openspec.yaml
new file mode 100644
index 00000000..be831cee
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-14
diff --git a/openspec/changes/pep-4-gitea-org/design.md b/openspec/changes/pep-4-gitea-org/design.md
new file mode 100644
index 00000000..3a234439
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/design.md
@@ -0,0 +1,80 @@
+# Design
+
+## Context
+
+Мотивация — в proposal.md. Что есть сейчас (проверено 2026-11-14, Gitea 1.22.6):
+
+- Организации `peppa` нет, имя свободно (ни пользователя, ни организации). `peppa-bot` не админ
+ Gitea и не состоит ни в одной организации; может ли он создавать организации — видно только
+ по ответу на `POST /orgs`.
+- В пространстве `peppa-bot` 12 репозиториев: `peppa`, `template` (приватный, шаблон) и 10
+ проектов пользователей. В БД у всех 11 проектов `gitea_owner = peppa-bot`.
+- Раннер CI зарегистрирован на уровне пользователя `peppa-bot`; `setupCi` для проекта с другим
+ владельцем сам регистрирует раннер на репозиторий (метка `repo---`).
+- Адрес `peppa-bot/peppa` вшит в `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`;
+ шаблон — `GITEA_TEMPLATE_REPO` (env, умолчание в `env.ts`, `push-template.sh`, `.env.example`).
+- Открыт PR #79 (`task/pep-87`), идут сессии PEP — работа параллельными волнами.
+
+## Goals / Non-Goals
+
+**Goals:**
+- `peppa/peppa` и `peppa/template` работают как раньше: CI, вебхуки, превью, правила агентов.
+- Перенос повторяем и проверяем кодом (команда + тест на `mock-gitea`), а не разовым curl.
+
+**Non-Goals:**
+- Перенос проектов пользователей из `peppa-bot`; смена пространства для новых проектов (PEP-68).
+- Команды и права внутри организации сверх Owners; официальный прод (PEP-18).
+- UI/MCP для переноса — только CLI администратора (как `project visibility`).
+
+## Decisions
+
+1. **Организацию создаёт `peppa-bot` (`POST /orgs`, visibility public)**, если Gitea разрешит;
+ 403 — просим PM создать её админом и добавить `peppa-bot` в Owners. Давать боту права админа
+ Gitea не нужно и не хочется: ему достаточно быть владельцем одной организации.
+ Вторым владельцем добавляем учётку PM в Gitea — организация не должна держаться на одном боте.
+2. **Перенос — операция `transferProject` в runner + `peppa project transfer`**, а не ручные
+ шаги. Порядок: проверить пространство и отсутствие `/` → `POST
+ /repos/{o}/{r}/transfer` (владелец организации переносит сразу, без подтверждения) → обновить
+ `projects.gitea_owner` → `git remote set-url origin` в рабочей копии (worktree делят конфиг) →
+ `setupCi` (раннер на репозиторий, секрет, вебхук) → событие `repo_transferred`. Каждый шаг
+ идемпотентен: если репозиторий уже на новом месте, шаг Gitea пропускается.
+ Альтернатива — UPDATE в БД руками — не оставляет следа в журнале и забывает раннер.
+3. **Раннер — на репозиторий** (существующий путь `setupCi`), не на организацию: раннер с
+ docker.sock хоста не должен автоматически обслуживать любой будущий репозиторий организации.
+4. **`GITEA_PLATFORM_REPO`** (env, умолчание `peppa/peppa`) вместо трёх вшитых строк. Брать адрес
+ из проекта `PEPPA_PLATFORM_KEY` в БД нельзя: скрипты релиза и `ci.sh` работают без БД.
+5. **Шаблон** — не проект Пеппы, переносится тем же вызовом клиента из задачи разово
+ (`peppa project transfer` его не знает); затем `GITEA_TEMPLATE_REPO=peppa/template` в `.env`,
+ `scripts/push-template.sh` и проверка `get_rules`. Остаётся приватным и `template: true`.
+6. **Порядок на живой системе**: сначала мерж кода (умолчания новые, но `.env` ещё держит
+ старые адреса — ничего не ломается), затем перенос одной командой, сразу `.env` и рестарт
+ сервисов. Редиректы Gitea покрывают окно между шагами и чужие клоны.
+
+## Risks / Trade-offs
+
+- [Редирект не действует на API-запросы Пеппы по старому адресу] → адрес проекта в БД меняется
+ в той же команде, сразу после переноса; окно — секунды.
+- [Живые сессии PEP и PR #79 в момент переноса] → git идёт через редирект; `origin` общей
+ рабочей копии и worktree обновляются командой. Контейнерные сессии (релей git пускает только
+ `owner/repo` проекта) — на PEP сейчас не используются; проверить перед переносом.
+- [Секрет Actions и вебхук могут не пережить перенос] → `setupCi` ставит их заново в любом случае.
+- [Раннер уровня `peppa-bot` перестаёт видеть `peppa/peppa`] → регистрация на репозиторий — часть
+ команды; проверка — зелёный прогон CI на PR этой стори после переноса.
+- [Кто-то создаст `peppa-bot/peppa` заново и сломает редирект] → не создавать; записать в память.
+- [Bare-клон будущего прода `~/peppa/repo.git`] → `PEPPA_RELEASE_REMOTE` по умолчанию от
+ `GITEA_PLATFORM_REPO`; существующему клону — `git remote set-url`.
+
+## Migration Plan
+
+1. PR с кодом и тестами — зелёный CI на старом адресе, мерж.
+2. Организация `peppa` (бот или PM), `peppa-bot` и PM — Owners.
+3. `peppa db backup`, `peppa project transfer PEP peppa`; перенос `template`.
+4. `.env`: `GITEA_TEMPLATE_REPO=peppa/template`; рестарт web/bot/watchdog; `peppa status`.
+5. Проверки: `git fetch` в рабочей копии, `get_rules`, пробный PR/пуш → проверки `peppa/*`
+ зелёные и видны на карточке, футер ведёт на `peppa/peppa`.
+
+Откат: `peppa project transfer PEP peppa-bot`, обратный перенос `template`, прежний `.env`.
+
+## Open Questions
+
+- Логин PM в Gitea для второго владельца организации — нужен только на шаге 2, на код не влияет.
diff --git a/openspec/changes/pep-4-gitea-org/proposal.md b/openspec/changes/pep-4-gitea-org/proposal.md
new file mode 100644
index 00000000..d2219ae4
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/proposal.md
@@ -0,0 +1,46 @@
+# Proposal
+
+## Why
+
+Репозитории платформы (`peppa-bot/peppa`, `peppa-bot/template`) лежат в личном пространстве
+служебной учётки `peppa-bot` вперемешку с проектами пользователей без Gitea (PEP-68). Платформа
+мультипользовательская (эпик #2): её код и шаблон должны принадлежать организации `peppa`, где
+владельцев несколько и права задаются командами, а не паролем одного бота.
+
+## What Changes
+
+- В Gitea создаётся организация `peppa` (публичная); `peppa-bot` — в команде Owners.
+- `peppa-bot/peppa` → `peppa/peppa`, `peppa-bot/template` → `peppa/template` (перенос Gitea:
+ история, PR, issues, вебхуки и секреты Actions сохраняются, старые адреса редиректят).
+- Новая команда `peppa project transfer ` — переносит репозиторий проекта в другое
+ пространство Gitea и чинит всё, что от адреса зависит: запись проекта, `origin` рабочей копии,
+ раннер CI, секрет и вебхук. Перенос `peppa` делается ею же; повторный запуск безопасен.
+- `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; адрес репозитория платформы перестаёт быть
+ вшитым (`peppa-bot/peppa` в футере, `scripts/ci.sh`, `scripts/peppa-release.sh`) — одна
+ настройка `GITEA_PLATFORM_REPO` (по умолчанию `peppa/peppa`).
+- Живая система: `.env`, `origin` рабочей копии, раннер CI на `peppa/peppa`, документация.
+- Проекты пользователей в пространстве `peppa-bot` **не переносятся** (вне scope).
+
+## Capabilities
+
+### New Capabilities
+
+Нет.
+
+### Modified Capabilities
+- `project-provisioning`: новое требование — перенос репозитория проекта в другое пространство
+ Gitea командой CLI.
+- `peppa-ci`: репозиторий платформы в требованиях — `peppa/peppa` вместо `peppa-bot/peppa`.
+
+## Impact
+
+- Gitea: новая организация, перенос двух репозиториев (обратим обратным переносом, но адреса
+ меняются для всех клонов); нужно право `peppa-bot` создавать организации **или** организация,
+ созданная админом Gitea с `peppa-bot` в Owners.
+- Код: `packages/core/src/gitea.ts` (перенос), `packages/runner` (новая операция, `ci.ts`),
+ `packages/cli`, `packages/shared/src/env.ts`, `apps/web/components/Footer.tsx`, `scripts/ci.sh`,
+ `scripts/peppa-release.sh`, `scripts/push-template.sh`, `.env.example`, `mock-gitea`.
+- Данные: `projects.gitea_owner` проекта PEP (`peppa-bot` → `peppa`), без миграций схемы.
+- CI: раннер уровня пользователя `peppa-bot` перестаёт покрывать `peppa/peppa` — регистрация на
+ репозиторий. Открытые PR (сейчас #79) и живые сессии PEP продолжают работать через редирект.
+- Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help`.
diff --git a/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
new file mode 100644
index 00000000..ecf49c5d
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
@@ -0,0 +1,48 @@
+# Spec Delta
+
+## MODIFIED Requirements
+
+### Requirement: Статус проверки в PR
+`scripts/ci.sh --pr ` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория платформы
+(`GITEA_PLATFORM_REPO`, по умолчанию `peppa/peppa`) в отдельном
+временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем
+`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется.
+
+#### Scenario: Зелёный PR
+- **GIVEN** открыт PR 15, его голова проходит все проверки
+- **WHEN** запускается `scripts/ci.sh --pr 15`
+- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in min»
+- **AND** лог прогона лежит в `~/.peppa/ci/.log`, временный worktree удалён
+
+#### Scenario: Красный PR
+- **GIVEN** открыт PR 16, в его голове падает e2e
+- **WHEN** запускается `scripts/ci.sh --pr 16`
+- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу
+- **AND** код выхода 1
+
+#### Scenario: Нет такого PR
+- **GIVEN** в репозитории нет PR 999
+- **WHEN** запускается `scripts/ci.sh --pr 999`
+- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2
+
+### Requirement: Проверки на каждый PR в Gitea Actions
+Workflow `.gitea/workflows/ci.yml` репозитория `peppa/peppa` SHALL на каждый PR из ветки этого
+репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57),
+с тестовой БД `peppa_test_ci_r` на Postgres хоста, и выставлять статус коммита
+`peppa-ci / ci (pull_request)`; PR из форков не запускаются.
+
+#### Scenario: PR зелёный
+- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят
+- **WHEN** ветка пушится
+- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in ms»)
+- **AND** БД `peppa_test_ci_r` после job не существует
+
+#### Scenario: PR красный
+- **GIVEN** в голове PR падает один e2e-тест
+- **WHEN** job доходит до шага `ci`
+- **THEN** статус = `failure` («Failing after ms»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста
+
+#### Scenario: PR из форка
+- **GIVEN** PR открыт из форка репозитория
+- **WHEN** Gitea обрабатывает событие `pull_request`
+- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется
diff --git a/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md
new file mode 100644
index 00000000..d7cc555a
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md
@@ -0,0 +1,38 @@
+# Spec Delta
+
+## ADDED Requirements
+
+### Requirement: Перенос репозитория проекта в другое пространство
+Команда `peppa project transfer ` SHALL переносить репозиторий проекта в пространство
+`` (организация или пользователь Gitea) и приводить проект в рабочее состояние по новому
+адресу: адрес проекта в Пеппе, `origin` рабочей копии, раннер CI, секрет и вебхук. Повторный запуск
+после частичного сбоя SHALL доводить перенос до конца без ошибки.
+
+#### Scenario: Перенос в организацию
+- **GIVEN** проект `DEMO` с репозиторием `peppa-bot/demo` и организация `acme`, где `peppa-bot` — владелец
+- **WHEN** выполняется `peppa project transfer DEMO acme`
+- **THEN** репозиторий доступен как `acme/demo`, вывод — «DEMO: peppa-bot/demo → acme/demo»
+- **AND** страница проекта в вебе ссылается на `acme/demo`
+- **AND** `git remote get-url origin` в рабочей копии оканчивается на `/acme/demo.git`
+- **AND** в журнале проекта есть событие «репозиторий перенесён» со старым и новым адресом
+
+#### Scenario: CI после переноса
+- **GIVEN** проект `DEMO` с подключённым CI перенесён из `peppa-bot/demo` в `acme/demo`
+- **WHEN** в `acme/demo` открывается PR
+- **THEN** проверки `peppa/*` выполняются на раннере Пеппы и их отчёты приходят на карточку стори
+
+#### Scenario: Повторный запуск
+- **GIVEN** репозиторий проекта `DEMO` уже находится в `acme/demo`, а в Пеппе записан `peppa-bot/demo`
+- **WHEN** выполняется `peppa project transfer DEMO acme`
+- **THEN** перенос в Gitea не запрашивается, адрес проекта и `origin` становятся `acme/demo`, код выхода 0
+
+#### Scenario: Пространства нет или нет прав
+- **GIVEN** организации `nope` в Gitea нет
+- **WHEN** выполняется `peppa project transfer DEMO nope`
+- **THEN** выводится «Пространство nope не найдено или у peppa-bot нет прав создавать в нём репозитории», код выхода 1
+- **AND** репозиторий остаётся `peppa-bot/demo`, адрес проекта в Пеппе не меняется
+
+#### Scenario: В пространстве уже есть такой репозиторий
+- **GIVEN** в организации `acme` уже есть другой репозиторий `demo`
+- **WHEN** выполняется `peppa project transfer DEMO acme`
+- **THEN** выводится «Репозиторий acme/demo уже существует», код выхода 1, ничего не меняется
diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/pep-4-gitea-org/tasks.md
new file mode 100644
index 00000000..f488d3d8
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/tasks.md
@@ -0,0 +1,27 @@
+# Tasks
+
+## 1. Перенос репозитория проекта (код)
+
+- [ ] 1.1 `GiteaClient`: `transferRepo(owner, repo, newOwner)` и проверка пространства (организация/пользователь, право создавать репозитории); `mock-gitea` — `POST /repos/{o}/{r}/transfer` (404 пространства, 409 занятое имя, редирект старого адреса) — проверка: юнит-вызовы мока в новом тесте
+- [ ] 1.2 `transferProject` в `packages/runner` (перенос → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` → событие `repo_transferred` через `logEvent`), идемпотентно — проверка: `project-transfer.test.ts`, сценарии «Перенос в организацию», «CI после переноса», «Повторный запуск»
+- [ ] 1.3 CLI `peppa project transfer ` (админ, строка в справке) и ошибки «Пространства нет или нет прав», «В пространстве уже есть такой репозиторий» — проверка: те же тесты по сценариям, код выхода 1 и неизменный проект
+- [ ] 1.4 Текст события «репозиторий перенесён» в журнале/чате проекта (`EVENT_TEXT`) — проверка: сценарий «Перенос в организацию» видит событие
+
+## 2. Адреса платформы без вшитых строк
+
+- [ ] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck`
+- [ ] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов
+- [ ] 2.3 Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help` (где репозиторий платформы, команда переноса) — проверка: вычитка, ссылки на `peppa/peppa`
+- [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI
+
+## 3. Перенос на живой системе (после одобрения PM и мержа кода)
+
+- [ ] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners
+- [ ] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa`
+- [ ] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит
+- [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa`
+- [ ] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект)
+
+## Workflow follow-up
+
+- `openspec archive pep-4-gitea-org`, PR, `update_task(status: review)`.
diff --git a/openspec/specs/agent-runner/spec.md b/openspec/specs/agent-runner/spec.md
new file mode 100644
index 00000000..d49addcb
--- /dev/null
+++ b/openspec/specs/agent-runner/spec.md
@@ -0,0 +1,25 @@
+# agent-runner Specification
+
+## Purpose
+TBD - created by archiving change pep-69-runner-tmux-env. Update Purpose after archive.
+
+## Requirements
+
+### Requirement: Окружение раннера не наследуется от чужого tmux-сервера
+Раннер SHALL запускать агентов так, чтобы они не получали `GITEA_*`, `PEPPA_*`, `MOCK_*`, `DATABASE_URL` из глобального окружения tmux-сервера по умолчанию, а `peppa status` SHALL предупреждать, если такие переменные там есть.
+
+#### Scenario: Сервер запущен тестовой оболочкой
+- **GIVEN** tmux-сервер по умолчанию с глобальной переменной `GITEA_URL=http://127.0.0.1:9`
+- **WHEN** раннер-сервис запускает сессию стори
+- **THEN** `GITEA_URL` удалена из глобального окружения сервера
+- **AND** переменные сессии (`PEPPA_SESSION_ID`) переданы явно
+
+#### Scenario: Предупреждение в статусе
+- **GIVEN** в окружении tmux-сервера есть `MOCK_X`
+- **WHEN** PM запускает `peppa status`
+- **THEN** выводится предупреждение со списком переменных и командой очистки
+
+#### Scenario: Выделенный сокет не трогается
+- **GIVEN** задан `PEPPA_TMUX_SOCKET`
+- **WHEN** запускается сессия
+- **THEN** окружение этого сервера не чистится
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 19693b9d..1c8d41ff 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -69,7 +69,7 @@ import {
setDefaultActor,
} from "@peppa/core";
import { createDb, migrateDb } from "@peppa/db";
-import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
+import { checkHost, ensureSshKey, pushImage, sshArgs, tmux } from "@peppa/runner";
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
@@ -643,6 +643,8 @@ async function main(): Promise {
const ob = await outboxStats(db);
console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`);
console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`);
+ const foreign = await tmux.foreignServerEnv().catch(() => []);
+ if (foreign.length) console.log(`⚠ в окружении tmux-сервера чужие переменные: ${foreign.join(", ")} — агенты их унаследуют; очистятся при следующем запуске раннера или: ${foreign.map((n) => `tmux set-environment -g -u ${n}`).join("; ")}`);
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
console.log(`админы: ${admins.join(", ") || "нет"}`);
diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts
index 71ad3c8c..57f6aff7 100644
--- a/packages/runner/src/tmux.ts
+++ b/packages/runner/src/tmux.ts
@@ -41,6 +41,35 @@ export interface NewTmuxSession {
width?: number;
}
+/**
+ * PEP-69: names that must never come from a tmux server's global environment. Every session
+ * inherits it, and a server started by some test run or tool shell carries that process's
+ * GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place.
+ * What an agent needs is passed per session (`new-session -e`) or read from `.env`.
+ */
+const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/;
+
+/** Foreign variables in the global environment of the tmux server (default server only). */
+export async function foreignServerEnv(p: Pane = { name: "" }, opts: { anySocket?: boolean } = {}): Promise {
+ // A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it.
+ if (process.env.PEPPA_TMUX_SOCKET && !opts.anySocket) return [];
+ let out: string;
+ try {
+ out = await tmuxOn(p, ["show-environment", "-g"]);
+ } catch (e) {
+ if (e instanceof HostUnreachable) throw e;
+ return []; // no server running
+ }
+ return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k));
+}
+
+/** Removes them from the server's global environment; returns the names removed. */
+export async function scrubServerEnv(p: Pane = { name: "" }, opts: { anySocket?: boolean } = {}): Promise {
+ const names = await foreignServerEnv(p, opts);
+ for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]);
+ return names;
+}
+
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}`]);
@@ -48,6 +77,7 @@ export async function newSession(s: NewTmuxSession): Promise {
// 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.
await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]);
+ await scrubServerEnv(p).catch(() => {}); // PEP-69
await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]);
// Keep the pane after claude exits so the watchdog can read the exit status.
await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]);
diff --git a/packages/testkit/test/tmux-env.test.ts b/packages/testkit/test/tmux-env.test.ts
new file mode 100644
index 00000000..f0179b06
--- /dev/null
+++ b/packages/testkit/test/tmux-env.test.ts
@@ -0,0 +1,40 @@
+// PEP-69: agents must not inherit a foreign environment from the tmux server's global env.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { after, describe, test } from "node:test";
+import { tmux } from "@peppa/runner";
+
+const SOCKET = `peppa-test-env-${process.pid}`;
+process.env.PEPPA_TMUX_SOCKET = SOCKET;
+const t = (...a: string[]) => execFileSync("tmux", ["-L", SOCKET, ...a], { encoding: "utf8" });
+
+after(() => {
+ try { t("kill-server"); } catch { /* already gone */ }
+});
+
+describe("tmux server environment (PEP-69)", () => {
+ test("Scenario: чужие переменные сервера вычищаются, остальные остаются", async () => {
+ t("start-server", ";", "set-option", "-s", "exit-empty", "off");
+ for (const [k, v] of [["GITEA_URL", "http://127.0.0.1:9"], ["PEPPA_HOME", "/tmp/x"], ["MOCK_X", "1"], ["DATABASE_URL", "pg"], ["KEEP_ME", "1"]] as const) {
+ t("set-environment", "-g", k, v);
+ }
+ // the server also inherited this test process's own PEPPA_* — those are foreign too
+ const found = await tmux.foreignServerEnv(undefined, { anySocket: true });
+ for (const n of ["DATABASE_URL", "GITEA_URL", "MOCK_X", "PEPPA_HOME"]) assert.ok(found.includes(n), n);
+ assert.ok(!found.includes("KEEP_ME"));
+ // default: a dedicated socket is its owner's own server — nothing to warn about
+ assert.deepEqual(await tmux.foreignServerEnv(), []);
+ assert.ok((await tmux.scrubServerEnv(undefined, { anySocket: true })).length >= 4);
+ const left = t("show-environment", "-g");
+ assert.match(left, /KEEP_ME=1/);
+ assert.doesNotMatch(left, /GITEA_URL|PEPPA_HOME|MOCK_X|DATABASE_URL/);
+ });
+
+ test("Scenario: новый раннер не получает чужое окружение; свои переменные доходят", async () => {
+ // simulate default-server mode for the scrub in newSession by scrubbing through the same path
+ t("set-environment", "-g", "GITEA_TOKEN", "");
+ await tmux.scrubServerEnv(undefined, { anySocket: true });
+ await tmux.newSession({ name: "env-probe", cwd: "/tmp", command: "env > /tmp/peppa-env-probe.$$; sleep 5", env: { PEPPA_SESSION_ID: "7" } });
+ assert.doesNotMatch(t("show-environment", "-g"), /GITEA_TOKEN/);
+ });
+});
--
2.45.2
From 748216eef201ff3c6f2fbf4a295be0afc4b39ecc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sun, 15 Nov 2026 00:10:47 +0500
Subject: [PATCH 040/439] =?UTF-8?q?PEP-4:=20peppa=20project=20transfer=20?=
=?UTF-8?q?=E2=80=94=20move=20a=20project's=20repo=20to=20another=20Gitea?=
=?UTF-8?q?=20namespace=20(origin,=20CI=20runner,=20secret,=20webhook)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
.../changes/pep-4-gitea-org/.openspec.yaml | 2 +
openspec/changes/pep-4-gitea-org/design.md | 80 ++++++++++
openspec/changes/pep-4-gitea-org/proposal.md | 46 ++++++
.../pep-4-gitea-org/specs/peppa-ci/spec.md | 48 ++++++
.../specs/project-provisioning/spec.md | 38 +++++
openspec/changes/pep-4-gitea-org/tasks.md | 27 ++++
packages/cli/src/index.ts | 15 +-
packages/core/src/chats.ts | 2 +
packages/core/src/gitea.ts | 20 +++
packages/runner/src/index.ts | 1 +
packages/runner/src/share.ts | 3 +
packages/runner/src/transfer.ts | 74 +++++++++
packages/testkit/src/mock-gitea.ts | 39 ++++-
.../testkit/test/project-transfer.test.ts | 141 ++++++++++++++++++
14 files changed, 531 insertions(+), 5 deletions(-)
create mode 100644 openspec/changes/pep-4-gitea-org/.openspec.yaml
create mode 100644 openspec/changes/pep-4-gitea-org/design.md
create mode 100644 openspec/changes/pep-4-gitea-org/proposal.md
create mode 100644 openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
create mode 100644 openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md
create mode 100644 openspec/changes/pep-4-gitea-org/tasks.md
create mode 100644 packages/runner/src/transfer.ts
create mode 100644 packages/testkit/test/project-transfer.test.ts
diff --git a/openspec/changes/pep-4-gitea-org/.openspec.yaml b/openspec/changes/pep-4-gitea-org/.openspec.yaml
new file mode 100644
index 00000000..be831cee
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-14
diff --git a/openspec/changes/pep-4-gitea-org/design.md b/openspec/changes/pep-4-gitea-org/design.md
new file mode 100644
index 00000000..3a234439
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/design.md
@@ -0,0 +1,80 @@
+# Design
+
+## Context
+
+Мотивация — в proposal.md. Что есть сейчас (проверено 2026-11-14, Gitea 1.22.6):
+
+- Организации `peppa` нет, имя свободно (ни пользователя, ни организации). `peppa-bot` не админ
+ Gitea и не состоит ни в одной организации; может ли он создавать организации — видно только
+ по ответу на `POST /orgs`.
+- В пространстве `peppa-bot` 12 репозиториев: `peppa`, `template` (приватный, шаблон) и 10
+ проектов пользователей. В БД у всех 11 проектов `gitea_owner = peppa-bot`.
+- Раннер CI зарегистрирован на уровне пользователя `peppa-bot`; `setupCi` для проекта с другим
+ владельцем сам регистрирует раннер на репозиторий (метка `repo---`).
+- Адрес `peppa-bot/peppa` вшит в `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`;
+ шаблон — `GITEA_TEMPLATE_REPO` (env, умолчание в `env.ts`, `push-template.sh`, `.env.example`).
+- Открыт PR #79 (`task/pep-87`), идут сессии PEP — работа параллельными волнами.
+
+## Goals / Non-Goals
+
+**Goals:**
+- `peppa/peppa` и `peppa/template` работают как раньше: CI, вебхуки, превью, правила агентов.
+- Перенос повторяем и проверяем кодом (команда + тест на `mock-gitea`), а не разовым curl.
+
+**Non-Goals:**
+- Перенос проектов пользователей из `peppa-bot`; смена пространства для новых проектов (PEP-68).
+- Команды и права внутри организации сверх Owners; официальный прод (PEP-18).
+- UI/MCP для переноса — только CLI администратора (как `project visibility`).
+
+## Decisions
+
+1. **Организацию создаёт `peppa-bot` (`POST /orgs`, visibility public)**, если Gitea разрешит;
+ 403 — просим PM создать её админом и добавить `peppa-bot` в Owners. Давать боту права админа
+ Gitea не нужно и не хочется: ему достаточно быть владельцем одной организации.
+ Вторым владельцем добавляем учётку PM в Gitea — организация не должна держаться на одном боте.
+2. **Перенос — операция `transferProject` в runner + `peppa project transfer`**, а не ручные
+ шаги. Порядок: проверить пространство и отсутствие `/` → `POST
+ /repos/{o}/{r}/transfer` (владелец организации переносит сразу, без подтверждения) → обновить
+ `projects.gitea_owner` → `git remote set-url origin` в рабочей копии (worktree делят конфиг) →
+ `setupCi` (раннер на репозиторий, секрет, вебхук) → событие `repo_transferred`. Каждый шаг
+ идемпотентен: если репозиторий уже на новом месте, шаг Gitea пропускается.
+ Альтернатива — UPDATE в БД руками — не оставляет следа в журнале и забывает раннер.
+3. **Раннер — на репозиторий** (существующий путь `setupCi`), не на организацию: раннер с
+ docker.sock хоста не должен автоматически обслуживать любой будущий репозиторий организации.
+4. **`GITEA_PLATFORM_REPO`** (env, умолчание `peppa/peppa`) вместо трёх вшитых строк. Брать адрес
+ из проекта `PEPPA_PLATFORM_KEY` в БД нельзя: скрипты релиза и `ci.sh` работают без БД.
+5. **Шаблон** — не проект Пеппы, переносится тем же вызовом клиента из задачи разово
+ (`peppa project transfer` его не знает); затем `GITEA_TEMPLATE_REPO=peppa/template` в `.env`,
+ `scripts/push-template.sh` и проверка `get_rules`. Остаётся приватным и `template: true`.
+6. **Порядок на живой системе**: сначала мерж кода (умолчания новые, но `.env` ещё держит
+ старые адреса — ничего не ломается), затем перенос одной командой, сразу `.env` и рестарт
+ сервисов. Редиректы Gitea покрывают окно между шагами и чужие клоны.
+
+## Risks / Trade-offs
+
+- [Редирект не действует на API-запросы Пеппы по старому адресу] → адрес проекта в БД меняется
+ в той же команде, сразу после переноса; окно — секунды.
+- [Живые сессии PEP и PR #79 в момент переноса] → git идёт через редирект; `origin` общей
+ рабочей копии и worktree обновляются командой. Контейнерные сессии (релей git пускает только
+ `owner/repo` проекта) — на PEP сейчас не используются; проверить перед переносом.
+- [Секрет Actions и вебхук могут не пережить перенос] → `setupCi` ставит их заново в любом случае.
+- [Раннер уровня `peppa-bot` перестаёт видеть `peppa/peppa`] → регистрация на репозиторий — часть
+ команды; проверка — зелёный прогон CI на PR этой стори после переноса.
+- [Кто-то создаст `peppa-bot/peppa` заново и сломает редирект] → не создавать; записать в память.
+- [Bare-клон будущего прода `~/peppa/repo.git`] → `PEPPA_RELEASE_REMOTE` по умолчанию от
+ `GITEA_PLATFORM_REPO`; существующему клону — `git remote set-url`.
+
+## Migration Plan
+
+1. PR с кодом и тестами — зелёный CI на старом адресе, мерж.
+2. Организация `peppa` (бот или PM), `peppa-bot` и PM — Owners.
+3. `peppa db backup`, `peppa project transfer PEP peppa`; перенос `template`.
+4. `.env`: `GITEA_TEMPLATE_REPO=peppa/template`; рестарт web/bot/watchdog; `peppa status`.
+5. Проверки: `git fetch` в рабочей копии, `get_rules`, пробный PR/пуш → проверки `peppa/*`
+ зелёные и видны на карточке, футер ведёт на `peppa/peppa`.
+
+Откат: `peppa project transfer PEP peppa-bot`, обратный перенос `template`, прежний `.env`.
+
+## Open Questions
+
+- Логин PM в Gitea для второго владельца организации — нужен только на шаге 2, на код не влияет.
diff --git a/openspec/changes/pep-4-gitea-org/proposal.md b/openspec/changes/pep-4-gitea-org/proposal.md
new file mode 100644
index 00000000..d2219ae4
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/proposal.md
@@ -0,0 +1,46 @@
+# Proposal
+
+## Why
+
+Репозитории платформы (`peppa-bot/peppa`, `peppa-bot/template`) лежат в личном пространстве
+служебной учётки `peppa-bot` вперемешку с проектами пользователей без Gitea (PEP-68). Платформа
+мультипользовательская (эпик #2): её код и шаблон должны принадлежать организации `peppa`, где
+владельцев несколько и права задаются командами, а не паролем одного бота.
+
+## What Changes
+
+- В Gitea создаётся организация `peppa` (публичная); `peppa-bot` — в команде Owners.
+- `peppa-bot/peppa` → `peppa/peppa`, `peppa-bot/template` → `peppa/template` (перенос Gitea:
+ история, PR, issues, вебхуки и секреты Actions сохраняются, старые адреса редиректят).
+- Новая команда `peppa project transfer ` — переносит репозиторий проекта в другое
+ пространство Gitea и чинит всё, что от адреса зависит: запись проекта, `origin` рабочей копии,
+ раннер CI, секрет и вебхук. Перенос `peppa` делается ею же; повторный запуск безопасен.
+- `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; адрес репозитория платформы перестаёт быть
+ вшитым (`peppa-bot/peppa` в футере, `scripts/ci.sh`, `scripts/peppa-release.sh`) — одна
+ настройка `GITEA_PLATFORM_REPO` (по умолчанию `peppa/peppa`).
+- Живая система: `.env`, `origin` рабочей копии, раннер CI на `peppa/peppa`, документация.
+- Проекты пользователей в пространстве `peppa-bot` **не переносятся** (вне scope).
+
+## Capabilities
+
+### New Capabilities
+
+Нет.
+
+### Modified Capabilities
+- `project-provisioning`: новое требование — перенос репозитория проекта в другое пространство
+ Gitea командой CLI.
+- `peppa-ci`: репозиторий платформы в требованиях — `peppa/peppa` вместо `peppa-bot/peppa`.
+
+## Impact
+
+- Gitea: новая организация, перенос двух репозиториев (обратим обратным переносом, но адреса
+ меняются для всех клонов); нужно право `peppa-bot` создавать организации **или** организация,
+ созданная админом Gitea с `peppa-bot` в Owners.
+- Код: `packages/core/src/gitea.ts` (перенос), `packages/runner` (новая операция, `ci.ts`),
+ `packages/cli`, `packages/shared/src/env.ts`, `apps/web/components/Footer.tsx`, `scripts/ci.sh`,
+ `scripts/peppa-release.sh`, `scripts/push-template.sh`, `.env.example`, `mock-gitea`.
+- Данные: `projects.gitea_owner` проекта PEP (`peppa-bot` → `peppa`), без миграций схемы.
+- CI: раннер уровня пользователя `peppa-bot` перестаёт покрывать `peppa/peppa` — регистрация на
+ репозиторий. Открытые PR (сейчас #79) и живые сессии PEP продолжают работать через редирект.
+- Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help`.
diff --git a/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
new file mode 100644
index 00000000..ecf49c5d
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
@@ -0,0 +1,48 @@
+# Spec Delta
+
+## MODIFIED Requirements
+
+### Requirement: Статус проверки в PR
+`scripts/ci.sh --pr ` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория платформы
+(`GITEA_PLATFORM_REPO`, по умолчанию `peppa/peppa`) в отдельном
+временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем
+`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется.
+
+#### Scenario: Зелёный PR
+- **GIVEN** открыт PR 15, его голова проходит все проверки
+- **WHEN** запускается `scripts/ci.sh --pr 15`
+- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in min»
+- **AND** лог прогона лежит в `~/.peppa/ci/.log`, временный worktree удалён
+
+#### Scenario: Красный PR
+- **GIVEN** открыт PR 16, в его голове падает e2e
+- **WHEN** запускается `scripts/ci.sh --pr 16`
+- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу
+- **AND** код выхода 1
+
+#### Scenario: Нет такого PR
+- **GIVEN** в репозитории нет PR 999
+- **WHEN** запускается `scripts/ci.sh --pr 999`
+- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2
+
+### Requirement: Проверки на каждый PR в Gitea Actions
+Workflow `.gitea/workflows/ci.yml` репозитория `peppa/peppa` SHALL на каждый PR из ветки этого
+репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57),
+с тестовой БД `peppa_test_ci_r` на Postgres хоста, и выставлять статус коммита
+`peppa-ci / ci (pull_request)`; PR из форков не запускаются.
+
+#### Scenario: PR зелёный
+- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят
+- **WHEN** ветка пушится
+- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in ms»)
+- **AND** БД `peppa_test_ci_r` после job не существует
+
+#### Scenario: PR красный
+- **GIVEN** в голове PR падает один e2e-тест
+- **WHEN** job доходит до шага `ci`
+- **THEN** статус = `failure` («Failing after ms»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста
+
+#### Scenario: PR из форка
+- **GIVEN** PR открыт из форка репозитория
+- **WHEN** Gitea обрабатывает событие `pull_request`
+- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется
diff --git a/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md
new file mode 100644
index 00000000..d7cc555a
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/specs/project-provisioning/spec.md
@@ -0,0 +1,38 @@
+# Spec Delta
+
+## ADDED Requirements
+
+### Requirement: Перенос репозитория проекта в другое пространство
+Команда `peppa project transfer ` SHALL переносить репозиторий проекта в пространство
+`` (организация или пользователь Gitea) и приводить проект в рабочее состояние по новому
+адресу: адрес проекта в Пеппе, `origin` рабочей копии, раннер CI, секрет и вебхук. Повторный запуск
+после частичного сбоя SHALL доводить перенос до конца без ошибки.
+
+#### Scenario: Перенос в организацию
+- **GIVEN** проект `DEMO` с репозиторием `peppa-bot/demo` и организация `acme`, где `peppa-bot` — владелец
+- **WHEN** выполняется `peppa project transfer DEMO acme`
+- **THEN** репозиторий доступен как `acme/demo`, вывод — «DEMO: peppa-bot/demo → acme/demo»
+- **AND** страница проекта в вебе ссылается на `acme/demo`
+- **AND** `git remote get-url origin` в рабочей копии оканчивается на `/acme/demo.git`
+- **AND** в журнале проекта есть событие «репозиторий перенесён» со старым и новым адресом
+
+#### Scenario: CI после переноса
+- **GIVEN** проект `DEMO` с подключённым CI перенесён из `peppa-bot/demo` в `acme/demo`
+- **WHEN** в `acme/demo` открывается PR
+- **THEN** проверки `peppa/*` выполняются на раннере Пеппы и их отчёты приходят на карточку стори
+
+#### Scenario: Повторный запуск
+- **GIVEN** репозиторий проекта `DEMO` уже находится в `acme/demo`, а в Пеппе записан `peppa-bot/demo`
+- **WHEN** выполняется `peppa project transfer DEMO acme`
+- **THEN** перенос в Gitea не запрашивается, адрес проекта и `origin` становятся `acme/demo`, код выхода 0
+
+#### Scenario: Пространства нет или нет прав
+- **GIVEN** организации `nope` в Gitea нет
+- **WHEN** выполняется `peppa project transfer DEMO nope`
+- **THEN** выводится «Пространство nope не найдено или у peppa-bot нет прав создавать в нём репозитории», код выхода 1
+- **AND** репозиторий остаётся `peppa-bot/demo`, адрес проекта в Пеппе не меняется
+
+#### Scenario: В пространстве уже есть такой репозиторий
+- **GIVEN** в организации `acme` уже есть другой репозиторий `demo`
+- **WHEN** выполняется `peppa project transfer DEMO acme`
+- **THEN** выводится «Репозиторий acme/demo уже существует», код выхода 1, ничего не меняется
diff --git a/openspec/changes/pep-4-gitea-org/tasks.md b/openspec/changes/pep-4-gitea-org/tasks.md
new file mode 100644
index 00000000..e44d05a1
--- /dev/null
+++ b/openspec/changes/pep-4-gitea-org/tasks.md
@@ -0,0 +1,27 @@
+# Tasks
+
+## 1. Перенос репозитория проекта (код)
+
+- [x] 1.1 `GiteaClient`: `transferRepo(owner, repo, newOwner)` и проверка пространства (организация/пользователь, право создавать репозитории); `mock-gitea` — `POST /repos/{o}/{r}/transfer` (404 пространства, 409 занятое имя, редирект старого адреса) — проверка: юнит-вызовы мока в новом тесте
+- [x] 1.2 `transferProject` в `packages/runner` (перенос → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` → событие `repo_transferred` через `logEvent`), идемпотентно — проверка: `project-transfer.test.ts`, сценарии «Перенос в организацию», «CI после переноса», «Повторный запуск»
+- [x] 1.3 CLI `peppa project transfer ` (админ, строка в справке) и ошибки «Пространства нет или нет прав», «В пространстве уже есть такой репозиторий» — проверка: те же тесты по сценариям, код выхода 1 и неизменный проект
+- [x] 1.4 Текст события «репозиторий перенесён» в журнале/чате проекта (`EVENT_TEXT`) — проверка: сценарий «Перенос в организацию» видит событие
+
+## 2. Адреса платформы без вшитых строк
+
+- [ ] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck`
+- [ ] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов
+- [ ] 2.3 Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help` (где репозиторий платформы, команда переноса) — проверка: вычитка, ссылки на `peppa/peppa`
+- [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI
+
+## 3. Перенос на живой системе (после одобрения PM и мержа кода)
+
+- [ ] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners
+- [ ] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa`
+- [ ] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит
+- [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa`
+- [ ] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект)
+
+## Workflow follow-up
+
+- `openspec archive pep-4-gitea-org`, PR, `update_task(status: review)`.
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 19693b9d..eb37434e 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -74,7 +74,7 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
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 { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { loadEnv } from "@peppa/shared";
@@ -87,6 +87,7 @@ const USAGE = `peppa — Peppa software factory CLI
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 transfer (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
peppa project list
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
@@ -319,6 +320,18 @@ async function main(): Promise {
if (failed) process.exitCode = 1;
break;
}
+ case "project transfer": {
+ const [key, owner] = args;
+ if (!key || !owner) throw new PeppaError("usage: peppa project transfer ");
+ const p = await getProject(db, key);
+ const r = await transferProject(db, p, owner, { log: (step) => console.log(`… ${step}`) });
+ console.log(`${p.key}: ${r.from} → ${r.to}${r.moved ? "" : " (репозиторий уже там)"}`);
+ if (r.ciError) {
+ console.log(`CI: ${r.ciError} — повторите: peppa ci connect ${p.key}`);
+ process.exitCode = 1;
+ }
+ break;
+ }
case "project autonomy": {
// PEP-23: peppa project autonomy [manual|assisted|auto] [key=value…]
const [key, ...rest] = args;
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 237c0808..97bb9720 100644
--- a/packages/core/src/chats.ts
+++ b/packages/core/src/chats.ts
@@ -274,6 +274,8 @@ const EVENT_TEXT: Record { text: string; important?: boolean;
},
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
pm_comment: () => null, // handled separately: a person's message
+ // PEP-4: the project's repo moved to another Gitea namespace.
+ repo_transferred: (p) => ({ text: `📦 Репозиторий перенесён: ${s(p.from)} → ${s(p.to)}`, important: true }),
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }),
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index b599903e..a362dff5 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -151,6 +151,26 @@ export class GiteaClient {
return this.request("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate });
}
+ /**
+ * Moves a repo to another namespace (PEP-4). Gitea moves it at once only when the token owner
+ * may create repos there; otherwise the transfer stays pending — check where the repo is after.
+ */
+ transferRepo(owner: string, name: string, newOwner: string) {
+ return this.request("POST", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/transfer`, { new_owner: newOwner });
+ }
+
+ /** True if the token owner `login` may create repos in `namespace` (own account or an org with that right). */
+ async canCreateIn(login: string, namespace: string): Promise {
+ if (namespace.toLowerCase() === login.toLowerCase()) return true;
+ try {
+ const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(namespace)}/permissions`);
+ return !!p?.can_create_repository;
+ } catch (e) {
+ if (e instanceof GiteaError && (e.status === 404 || e.status === 403)) return false;
+ throw e;
+ }
+ }
+
/** True if `name` is an organization (false for a user account). */
async isOrg(name: string): Promise {
try {
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index 7dfea5ca..4d2c63cf 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -12,6 +12,7 @@ export * from "./share.ts";
export * from "./limits.ts";
export * from "./monitor.ts";
export * from "./ci.ts";
+export * from "./transfer.ts";
export * from "./incidents.ts";
export * from "./triage.ts";
export * from "./ci-feedback.ts";
diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts
index 2affa770..1785d103 100644
--- a/packages/runner/src/share.ts
+++ b/packages/runner/src/share.ts
@@ -157,6 +157,9 @@ const DESCRIBE_CACHE_MS = 60_000;
// The project page refreshes every few seconds; Gitea is asked at most once a minute per project.
const describeCache = new Map();
+/** Drops the cached repo info (the repo moved or changed outside this module). */
+export const forgetRepoInfo = (projectId: number) => void describeCache.delete(projectId);
+
/** Where the project's repo is and who can see it, asked from Gitea (owner's client, then peppa-bot). */
export async function describeRepo(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise {
const hit = describeCache.get(project.id);
diff --git a/packages/runner/src/transfer.ts b/packages/runner/src/transfer.ts
new file mode 100644
index 00000000..dbcf7e3a
--- /dev/null
+++ b/packages/runner/src/transfer.ts
@@ -0,0 +1,74 @@
+// PEP-4: moving a project's repo to another Gitea namespace (an organization, usually) and
+// fixing everything that depends on its address: the project row, `origin` of the working
+// copy, the CI runner, the Actions secret and the webhook. Every step is safe to repeat.
+import { existsSync } from "node:fs";
+import { eq } from "drizzle-orm";
+import { GiteaError, giteaForBot, logEvent, PeppaError, type Project } from "@peppa/core";
+import { projects, type Db } from "@peppa/db";
+import { setupCi } from "./ci.ts";
+import { git } from "./git.ts";
+import { forgetRepoInfo } from "./share.ts";
+
+export interface TransferResult {
+ project: Project;
+ from: string;
+ to: string;
+ /** False when the repo was already there (a repeated run): only Peppa's side was fixed. */
+ moved: boolean;
+ /** CI could not be set up at the new address (the transfer itself is done). */
+ ciError: string | null;
+}
+
+/** Moves the project's repo to `newOwner` as peppa-bot (CLI on Peppa's machine: no owner check). */
+export async function transferProject(db: Db, project: Project, newOwner: string, o: { log?: (step: string) => void } = {}): Promise {
+ const log = o.log ?? (() => {});
+ const target = newOwner.trim();
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(target)) throw new PeppaError(`Пространство «${newOwner}»: логин пользователя или организации Gitea`);
+ const bot = giteaForBot();
+ const repoName = project.giteaRepo;
+ const from = `${project.giteaOwner}/${repoName}`;
+ const to = `${target}/${repoName}`;
+
+ let dest = await bot.getRepo(target, repoName);
+ // After a transfer the old address redirects to the new one: the same repo id means "already moved".
+ const src = project.giteaOwner === target ? dest : await bot.getRepo(project.giteaOwner, repoName);
+ let moved = false;
+ if (dest && dest.owner.login.toLowerCase() !== target.toLowerCase()) dest = null; // a redirect left by an older move
+ if (dest && src && src.id !== dest.id) throw new PeppaError(`Репозиторий ${to} уже существует`);
+ if (!dest) {
+ if (!src) throw new PeppaError(`Репозиторий ${from} не найден в Gitea`);
+ const me = await bot.me();
+ if (!(await bot.canCreateIn(me.login, target))) throw new PeppaError(`Пространство ${target} не найдено или у ${me.login} нет прав создавать в нём репозитории`);
+ log("transfer");
+ try {
+ await bot.transferRepo(project.giteaOwner, repoName, target);
+ } catch (e) {
+ const status = e instanceof GiteaError ? e.status : 0;
+ if (status === 422 || status === 409) throw new PeppaError(`Репозиторий ${to} уже существует`);
+ if (status === 403) throw new PeppaError(`Нет прав администратора на ${from} — переносит владелец репозитория`);
+ throw e;
+ }
+ dest = await bot.getRepo(target, repoName);
+ if (!dest || dest.owner.login.toLowerCase() !== target.toLowerCase()) throw new PeppaError(`Перенос ${from} → ${to} ждёт подтверждения в Gitea`);
+ moved = true;
+ }
+
+ const changed = project.giteaOwner !== dest.owner.login;
+ if (changed) {
+ log("project");
+ await db.update(projects).set({ giteaOwner: dest.owner.login }).where(eq(projects.id, project.id));
+ }
+ const updated: Project = { ...project, giteaOwner: dest.owner.login };
+ forgetRepoInfo(project.id);
+ if (existsSync(project.workspacePath)) {
+ log("origin");
+ await git(project.workspacePath, "remote", "set-url", "origin", dest.clone_url);
+ }
+ log("ci");
+ const ciError = await setupCi(db, updated).then(
+ () => null,
+ (e: Error) => e.message,
+ );
+ if (moved || changed) await logEvent(db, { projectId: project.id, type: "repo_transferred", payload: { from, to } });
+ return { project: updated, from, to, moved, ciError };
+}
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index bfde5b83..50f5a427 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -4,7 +4,7 @@
// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags.
import { execFileSync } from "node:child_process";
import { createHmac } from "node:crypto";
-import { mkdirSync, mkdtempSync } from "node:fs";
+import { mkdirSync, mkdtempSync, renameSync } from "node:fs";
import { tmpdir } from "node:os";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
@@ -59,6 +59,8 @@ export class MockGitea {
readonly users = new Map();
readonly oauthCodes = new Map(); // code → token
readonly runnerTokens: Array<{ scope: string; token: string }> = [];
+ /** PEP-4: old `owner/name` → current one, like Gitea's redirects after a transfer. */
+ readonly redirects = new Map();
private seq = 1;
private server: Server | null = null;
url = "";
@@ -98,6 +100,10 @@ export class MockGitea {
return new Promise((r) => this.server?.close(() => r()) ?? r());
}
+ private isOrg(name: string) {
+ return [...this.users.values()].some((u) => u.orgs?.includes(name));
+ }
+
addUser(u: MockGiteaUser) {
this.users.set(u.token, u);
return u;
@@ -300,12 +306,12 @@ export class MockGitea {
if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } };
if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) };
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) {
+ if (!this.isOrg(decodeURIComponent(m[2]!))) return { status: 404, body: { message: "org does not exist" } };
return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } };
}
if (method === "GET" && (m = path.match(/^\/api\/v1\/orgs\/([^/]+)$/))) {
const name = decodeURIComponent(m[1]!);
- const isOrg = [...this.users.values()].some((u) => u.orgs?.includes(name));
- return isOrg ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } };
+ return this.isOrg(name) ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } };
}
if (method === "GET" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators$/))) {
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
@@ -322,6 +328,29 @@ export class MockGitea {
this.runnerTokens.push({ scope: `user:${me.login}`, token });
return { status: 200, body: { token } };
}
+ if (method === "POST" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/transfer$/))) {
+ // Gitea: repo admin only; unknown namespace → 404; name taken there → 422; the doer may
+ // create repos in the target → moved at once (202), otherwise the transfer stays pending (201).
+ const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
+ if (!r) return { status: 404, body: { message: "not found" } };
+ if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } };
+ const to = String(body.new_owner ?? "");
+ const users = [...this.users.values()];
+ if (!this.isOrg(to) && !users.some((u) => u.login === to)) return { status: 404, body: { message: "new owner does not exist" } };
+ if (this.repos.has(`${to}/${r.name}`)) return { status: 422, body: { message: "The repository with the same name already exists." } };
+ if (!(to === me.login || (me.orgs ?? []).includes(to))) return { status: 201, body: this.json(r, me) };
+ const old = `${r.owner}/${r.name}`;
+ const path2 = join(this.dir, to, `${r.name}.git`);
+ mkdirSync(join(this.dir, to), { recursive: true });
+ renameSync(r.path, path2);
+ this.repos.delete(old);
+ Object.assign(r, { owner: to, path: path2, admins: new Set([to, ...users.filter((u) => u.orgs?.includes(to)).map((u) => u.login)]) });
+ this.repos.set(`${to}/${r.name}`, r);
+ for (const [k, v] of this.redirects) if (v === old) this.redirects.set(k, `${to}/${r.name}`);
+ this.redirects.delete(`${to}/${r.name}`);
+ this.redirects.set(old, `${to}/${r.name}`);
+ return { status: 202, body: this.json(r, me) };
+ }
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) {
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
if (!r) return { status: 404, body: { message: "not found" } };
@@ -329,7 +358,9 @@ export class MockGitea {
if (res) return res;
}
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) {
- const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
+ const full = `${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`;
+ // A moved repo answers GET by its old address too (Gitea redirects, fetch follows).
+ const r = this.repos.get(full) ?? (method === "GET" ? this.repos.get(this.redirects.get(full) ?? "") : undefined);
if (!r) return { status: 404, body: { message: "not found" } };
if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 };
if (method === "PATCH") {
diff --git a/packages/testkit/test/project-transfer.test.ts b/packages/testkit/test/project-transfer.test.ts
new file mode 100644
index 00000000..0dba1080
--- /dev/null
+++ b/packages/testkit/test/project-transfer.test.ts
@@ -0,0 +1,141 @@
+// PEP-4: `peppa project transfer ` — the project's repo moves to another Gitea
+// namespace and the project keeps working there (address, origin, CI runner, secret, webhook).
+// Tests are named after the scenarios of openspec/specs/project-provisioning.
+import assert from "node:assert/strict";
+import { execFile, execFileSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+import { after, before, describe, test } from "node:test";
+import { eq } from "drizzle-orm";
+import { events, projects } from "@peppa/db";
+import { core, db, runner, teardown } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+
+const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
+const TMP = mkdtempSync(join(tmpdir(), "peppa-transfer-"));
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+
+const gitea = new MockGitea(join(TMP, "gitea"));
+const BOT = { id: 71, login: "peppa-bot", token: "mock-token-transfer-bot", orgs: ["mock-acme"] };
+const ORG = "mock-acme";
+
+before(async () => {
+ await gitea.start();
+ process.env.GITEA_URL = gitea.url;
+ process.env.GITEA_TOKEN = BOT.token;
+ gitea.addUser(BOT);
+});
+after(async () => {
+ await gitea.stop();
+ await teardown();
+});
+
+/** A project with a repo in peppa-bot's namespace and a cloned working copy. */
+async function project(slug: string, key: string) {
+ const repo = gitea.addRepo(BOT.login, slug, { files: { "README.md": `# ${slug}\n` } });
+ const ws = join(TMP, "ws", slug);
+ execFileSync("git", ["clone", "-q", repo.path, ws]);
+ return core.createProject(db, { slug, key, name: key, giteaOwner: BOT.login, workspacePath: ws, ownerId: null });
+}
+
+async function cli(...a: string[]) {
+ try {
+ const r = await promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "transfer", ...a], { encoding: "utf8", env: process.env });
+ return { code: 0, out: r.stdout + r.stderr };
+ } catch (e) {
+ const x = e as { code?: number; stdout?: string; stderr?: string };
+ return { code: x.code ?? 1, out: `${x.stdout ?? ""}${x.stderr ?? ""}` };
+ }
+}
+
+const origin = (ws: string) => execFileSync("git", ["-C", ws, "remote", "get-url", "origin"], { encoding: "utf8" }).trim();
+const reload = async (id: number) => (await db.select().from(projects).where(eq(projects.id, id)))[0]!;
+const registrations = () => {
+ const f = join(process.env.PEPPA_HOME!, "mock-ci-register.jsonl");
+ return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { name: string }) : [];
+};
+
+describe("project transfer (PEP-4)", () => {
+ let demoId = 0;
+
+ test("Перенос в организацию", async () => {
+ const p = await project("mock-demo", "MTDEMO");
+ demoId = p.id;
+ const r = await cli("MTDEMO", ORG);
+ assert.equal(r.code, 0, r.out);
+ assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo\n/);
+ assert.ok(gitea.repos.has(`${ORG}/mock-demo`));
+ assert.ok(!gitea.repos.has("peppa-bot/mock-demo"));
+ const now = await reload(p.id);
+ assert.equal(now.giteaOwner, ORG);
+ const repo = await runner.describeRepo(db, now, { fresh: true });
+ assert.equal(repo.fullName, `${ORG}/mock-demo`); // what the project page links to
+ assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`), origin(p.workspacePath));
+ execFileSync("git", ["-C", p.workspacePath, "fetch", "-q", "origin"]);
+ const ev = (await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred");
+ assert.equal(ev.length, 1);
+ assert.deepEqual(ev[0]!.payload, { from: "peppa-bot/mock-demo", to: `${ORG}/mock-demo` });
+ });
+
+ test("CI после переноса", async () => {
+ // The bot-level runner no longer covers the repo: it gets its own, plus the report secret and the webhook.
+ const repo = gitea.repo(ORG, "mock-demo");
+ assert.ok(registrations().some((x) => x.name === `repo-${ORG}--mock-demo`), JSON.stringify(registrations()));
+ assert.equal(repo.secrets[runner.CI_SECRET_NAME], core.projectHookSecret(demoId));
+ assert.equal(repo.hooks.length, 1);
+ assert.equal(repo.hooks[0]!.url, runner.giteaHookUrl());
+ assert.deepEqual(repo.hooks[0]!.events, runner.GITEA_HOOK_EVENTS);
+ });
+
+ test("Повторный запуск", async () => {
+ // Peppa's side lost: the repo is already in the org, the project and origin still point to the old place.
+ const p = await reload(demoId);
+ await db.update(projects).set({ giteaOwner: BOT.login }).where(eq(projects.id, demoId));
+ execFileSync("git", ["-C", p.workspacePath, "remote", "set-url", "origin", join(TMP, "gone", "peppa-bot", "mock-demo.git")]);
+ const id = gitea.repo(ORG, "mock-demo").id;
+ const r = await cli("MTDEMO", ORG);
+ assert.equal(r.code, 0, r.out);
+ assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo \(репозиторий уже там\)/);
+ assert.equal(gitea.repo(ORG, "mock-demo").id, id);
+ assert.equal((await reload(demoId)).giteaOwner, ORG);
+ assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`));
+ // …and once more, with nothing left to fix.
+ const again = await cli("MTDEMO", ORG);
+ assert.equal(again.code, 0, again.out);
+ });
+
+ test("Пространства нет или нет прав", async () => {
+ const p = await project("mock-stay", "MTSTAY");
+ const before = origin(p.workspacePath);
+ const r = await cli("MTSTAY", "mock-nope");
+ assert.equal(r.code, 1, r.out);
+ assert.match(r.out, /Пространство mock-nope не найдено или у peppa-bot нет прав создавать в нём репозитории/);
+ assert.ok(gitea.repos.has("peppa-bot/mock-stay"));
+ assert.equal((await reload(p.id)).giteaOwner, BOT.login);
+ assert.equal(origin(p.workspacePath), before);
+ });
+
+ test("В пространстве уже есть такой репозиторий", async () => {
+ const p = await project("mock-twin", "MTTWIN");
+ gitea.addRepo(ORG, "mock-twin", { files: { "README.md": "# other\n" } });
+ const r = await cli("MTTWIN", ORG);
+ assert.equal(r.code, 1, r.out);
+ assert.match(r.out, /Репозиторий mock-acme\/mock-twin уже существует/);
+ assert.ok(gitea.repos.has("peppa-bot/mock-twin"));
+ assert.equal((await reload(p.id)).giteaOwner, BOT.login);
+ assert.equal((await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred").length, 0);
+ });
+
+ test("mock-gitea: перенос без права создавать в пространстве остаётся ожидающим", async () => {
+ gitea.addUser({ id: 72, login: "mock-other", token: "mock-token-transfer-other" });
+ gitea.addRepo(BOT.login, "mock-pending", { files: { "README.md": "# x\n" } });
+ const bot = core.giteaForBot();
+ await bot.transferRepo(BOT.login, "mock-pending", "mock-other");
+ assert.ok(gitea.repos.has("peppa-bot/mock-pending"));
+ assert.equal(await bot.getRepo("mock-other", "mock-pending"), null);
+ await assert.rejects(bot.transferRepo(BOT.login, "mock-pending", "mock-nobody"), /404/);
+ });
+});
--
2.45.2
From 5af93d7438dbea699a2e321e59fc2447fa6d6915 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sun, 15 Nov 2026 00:11:31 +0500
Subject: [PATCH 041/439] PEP-4: platform repo address from
GITEA_PLATFORM_REPO, template defaults to peppa/template
Co-Authored-By: Claude Fable 5.2
---
.env.example | 4 +++-
AGENTS.md | 7 ++++---
apps/web/components/Footer.tsx | 2 +-
openspec/changes/pep-4-gitea-org/tasks.md | 6 +++---
packages/shared/src/env.ts | 5 ++++-
scripts/ci.sh | 4 ++--
scripts/peppa-release.sh | 4 ++--
scripts/push-template.sh | 2 +-
8 files changed, 20 insertions(+), 14 deletions(-)
diff --git a/.env.example b/.env.example
index ee5cfd5e..18bb27b2 100644
--- a/.env.example
+++ b/.env.example
@@ -6,7 +6,9 @@
# Gitea (git.telecom.quest) — token with repo + org scope
GITEA_URL=https://git.telecom.quest
GITEA_TOKEN=
-GITEA_TEMPLATE_REPO=peppa-bot/template
+GITEA_TEMPLATE_REPO=peppa/template
+# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
+# GITEA_PLATFORM_REPO=peppa/peppa
# Where project repos are cloned and sessions run
PEPPA_WORKSPACES=~/peppa/workspaces
diff --git a/AGENTS.md b/AGENTS.md
index cff9faae..6600b08f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,6 +43,7 @@
- **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake: