From f284c4093361d1b660d29e1f0868540734104420 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 04:46:19 +0500 Subject: [PATCH 001/472] PEP-23/24/25: project autonomy levels, backlog dispatcher with idle pushes, auto-merge and closing, working copy sync Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 15 + apps/web/app/(app)/actions.ts | 30 ++ apps/web/app/(app)/help/page.tsx | 15 + apps/web/app/(app)/p/[key]/page.tsx | 9 +- apps/web/components/Autonomy.tsx | 90 +++++ openspec/changes/pep-23-autonomy/design.md | 90 +++++ openspec/changes/pep-23-autonomy/proposal.md | 42 ++ .../specs/project-autonomy/spec.md | 89 +++++ openspec/changes/pep-23-autonomy/tasks.md | 25 ++ packages/cli/src/index.ts | 32 ++ packages/core/src/autonomy.ts | 160 ++++++++ packages/core/src/index.ts | 1 + packages/core/src/subscriptions.ts | 10 + packages/core/src/tasks.ts | 5 +- packages/mcp/src/format.ts | 11 +- packages/mcp/src/index.ts | 6 + packages/mcp/src/manager.ts | 47 +++ packages/runner/src/autonomy.ts | 332 ++++++++++++++++ packages/runner/src/ci-feedback.ts | 5 +- packages/runner/src/flow.ts | 10 +- packages/runner/src/hook.ts | 7 + packages/runner/src/index.ts | 2 + packages/runner/src/sessions.ts | 17 +- packages/runner/src/watchdog.ts | 3 + packages/runner/src/workspace-sync.ts | 31 ++ packages/testkit/src/mock-agent.ts | 9 +- packages/testkit/test/autonomy-levels.test.ts | 375 ++++++++++++++++++ template/RULES.md | 13 +- 28 files changed, 1467 insertions(+), 14 deletions(-) create mode 100644 apps/web/components/Autonomy.tsx create mode 100644 openspec/changes/pep-23-autonomy/design.md create mode 100644 openspec/changes/pep-23-autonomy/proposal.md create mode 100644 openspec/changes/pep-23-autonomy/specs/project-autonomy/spec.md create mode 100644 openspec/changes/pep-23-autonomy/tasks.md create mode 100644 packages/core/src/autonomy.ts create mode 100644 packages/runner/src/autonomy.ts create mode 100644 packages/runner/src/workspace-sync.ts create mode 100644 packages/testkit/test/autonomy-levels.test.ts diff --git a/AGENTS.md b/AGENTS.md index 21d2a368..2452db23 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,21 @@ PM двигает карточки на доске (веб, `/p/`): «В р сбрасывается ответом человека), задача в `review` → сообщение «готово к ревью» с «Принять» (`acceptTask` → `done`). Агенты мержат свои PR после зелёного e2e. +**Автономность проекта (PEP-23/24/25)**: настройки в `settings` (`project.autonomy:`, без +колонок; нет строки = «ручной», как до PEP-23), `core/autonomy.ts` (`getAutonomy`/`setAutonomy`, +уровни manual/assisted/auto + поля pick/wipLimit/proposal/merge/close/closeAfterHours/idlePush/ +idlePushHours/quietFrom/quietTo). `runner/autonomy.ts` `autonomyTick` из `tick` вачдога: +автомерж стори в ревью (`autoMergeTask`; конфликт → агенту rebase, один раз на head SHA; +конвейер → вопрос PM с «Принять»), закрытие (`after_merge` / `after_hours` через `acceptTask`), +диспетчер (WIP = сессии стори в работе, порядок — номер; при лимите/исчерпанном пуле — +ничего) и пуш «Агенты простаивают» (`onIdleAnswer`: Взять / Следующую / Не сейчас; состояние +`autonomy.idle:`, тихие часы, не чаще `idlePushHours`). Хук в режиме merge=auto не шлёт +«готово к ревью». `acceptTask` после мержа — `syncWorkspace` (fetch, ff main, удаляет локальную +ветку стори; только чистая копия на main/ветке стори и без активных сессий; +`PEPPA_WORKSPACE_SYNC=off`). Веб «⋯ Настройки проекта» → «Автономность», MCP +`get_project_settings`/`update_project_settings`, CLI `peppa project autonomy`. MCP агента: +proposal=pm → `update_task in_progress` из backlog/proposing отклоняется. + ## Пеппа ведётся через Пеппу Пеппа — проект `PEP` в самой Пеппе (`.peppa/project.json`, MCP `peppa` из `.mcp.json`). diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 5418fb8b..c35d9033 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -1,6 +1,9 @@ "use server"; import { + setAutonomy, + type AutonomyLevel, + type AutonomySettings, linkEgovIin, createEpic, createTask, @@ -235,6 +238,33 @@ export async function setProjectVisibilityAction(f: FormData) { }); } +/** PEP-23: project autonomy — a preset level, or the individual settings (owner or member). */ +export async function setAutonomyAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const level = str(f, "level"); + if (level) { + await setAutonomy(db, p.id, { level: level as AutonomyLevel }); + return; + } + const hour = (k: string) => (str(f, k) === "" ? null : Number(str(f, k))); + const quiet = f.get("quiet") === "on"; + await setAutonomy(db, p.id, { + pick: str(f, "pick") as AutonomySettings["pick"], + wipLimit: Number(str(f, "wipLimit")), + proposal: str(f, "proposal") as AutonomySettings["proposal"], + merge: str(f, "merge") as AutonomySettings["merge"], + close: str(f, "close") as AutonomySettings["close"], + closeAfterHours: Number(str(f, "closeAfterHours")), + idlePush: f.get("idlePush") === "on", + idlePushHours: Number(str(f, "idlePushHours")), + quietFrom: quiet ? hour("quietFrom") : null, + quietTo: quiet ? hour("quietTo") : null, + }); + }); +} + export async function removeProjectMember(f: FormData) { const user = await requireUser(); await attempt(f, async () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index e682313f..403c56f6 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -17,6 +17,7 @@ const TOOLS: Array<[string, string]> = [ ["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"], ["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"], ["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"], + ["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое"], ["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"], ]; @@ -31,6 +32,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [ { title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" }, { title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" }, { title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" }, + { title: "Автономность", say: "Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR", how: "update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»" }, { title: "Видимость репозитория", say: "Сделай репозиторий PAY приватным", how: "set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»" }, { title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»" }, { title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" }, @@ -96,6 +98,19 @@ export default async function Help() { +
+

+ У каждого проекта — уровень автономности («⋯ Настройки проекта» → «Автономность», MCP update_project_settings, + CLI peppa project autonomy KEY). Ручной (по умолчанию): вы двигаете карточки и принимаете стори.{" "} + С подсказками: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками + «Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. Автомат: Пеппа сама берёт следующую стори из + бэклога (по номеру, одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент + сам делает rebase. Настройки можно комбинировать: одобрять каждый proposal, мержить сам, но закрывать вручную или «само через N + часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт + вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main. +

+
+

Каждый PR агента проверяет Gitea Actions: install, lint,{" "} diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 8972c29e..f50ebfe6 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,13 +1,14 @@ import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket } from "lucide-react"; import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner"; -import { getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; +import { getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Board, type Card } from "@/components/Board"; import { Hidden, SessionCard } from "@/components/cards"; import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common"; import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents"; +import { AutonomyPanel } from "@/components/Autonomy"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input, NativeSelect, Textarea } from "@/components/ui/input"; @@ -89,7 +90,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] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([])]); + const [pool, pools, autonomy] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id)]); // Epic filter (PEP-66): only an open epic of this project filters; anything else shows all. const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null; const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`); @@ -148,6 +149,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr )} + + + + diff --git a/apps/web/components/Autonomy.tsx b/apps/web/components/Autonomy.tsx new file mode 100644 index 00000000..f154da80 --- /dev/null +++ b/apps/web/components/Autonomy.tsx @@ -0,0 +1,90 @@ +// PEP-23: project autonomy in «⋯ Настройки проекта» — preset levels and the individual settings. +import { AUTONOMY_LEVEL_HINT, AUTONOMY_LEVEL_RU, AUTONOMY_LEVELS, autonomyLevel, type AutonomyLevel, type AutonomySettings } from "@peppa/core"; +import { setAutonomyAction } from "@/app/(app)/actions"; +import { Hidden } from "@/components/cards"; +import { Button } from "@/components/ui/button"; +import { Input, Label, NativeSelect } from "@/components/ui/input"; + +export function AutonomyPanel({ projectId, settings, back }: { projectId: number; settings: AutonomySettings; back: string }) { + const current = autonomyLevel(settings); + const s = settings; + return ( +

+
+ {(Object.keys(AUTONOMY_LEVELS) as AutonomyLevel[]).map((level) => ( +
+ + + + ))} + {current === "custom" && ( + + )} +
+

{current === "custom" ? "Своя комбинация настроек ниже." : AUTONOMY_LEVEL_HINT[current]}

+
+ Настроить подробно +
+ + + + + + + + + + +
+ с + до +
+ + +
+

PR, меняющий конвейер (.gitea/, checks, deploy), сам не мержится и не закрывается — его принимает PM.

+
+ ); +} diff --git a/openspec/changes/pep-23-autonomy/design.md b/openspec/changes/pep-23-autonomy/design.md new file mode 100644 index 00000000..b12bc8b5 --- /dev/null +++ b/openspec/changes/pep-23-autonomy/design.md @@ -0,0 +1,90 @@ +# Design: автономность проекта (PEP-23/24/25) + +## Хранение — `settings`, без миграции +Настройки — JSON в `settings` под ключом `project.autonomy:`. Нет строки = +«Ручной» (ровно поведение до PEP-23); сохранение «Ручного» без отличий удаляет строку. +Почему не колонки в `projects`: параллельно идут другие стори с миграциями (PEP-39 и др.), +а координатору не нужно применять миграцию до перезапуска сервисов — код со старой базой +работает сразу. Состояние диспетчера (`autonomy.idle:`: открытый вопрос, время +пуша, «не сейчас до», «бэклог пуст сообщён», пауза после неудачного запуска) и автомержа +(`autonomy.merge:`: head SHA, по которому уже спросили про конвейер / попросили +rebase, PR, по которому уже отправлено «смержено, принять?») — там же. + +## Уровни и поля +| Поле | Ручной | С подсказками | Автомат | +|---|---|---|---| +| pick (кто берёт) | pm | pm | auto | +| wipLimit | 1 | 1 | 1 | +| proposal | agent | agent | agent | +| merge | manual | manual | auto | +| close | pm | pm | after_merge | +| idlePush | нет | да | да | + +Остальное: `closeAfterHours` 24, `idlePushHours` 4, тихие часы 22–9 (локальное время машины). +Любая другая комбинация показывается как «Свой». WIP по умолчанию 1: агенты проекта +работают в одной рабочей копии, параллельные стори в ней мешают друг другу (лимит до 5 — +для проектов, где агенты работают в своих worktree). + +## Порядок стори +В модели нет приоритета и позиции на доске — следующая стори = наименьший номер в бэклоге. +Появятся приоритеты — меняется одна сортировка в `dispatch`. + +## Где работает +`autonomyTick` вызывается из `tick` вачдога (каждые 30 с) и пропускает проекты с «Ручным» +без запросов в Gitea. Для каждого проекта: автомерж стори в ревью → автозакрытие по +времени → диспетчер. Порядок важен: закрытая в этом же тике стори освобождает WIP, и +следующая берётся сразу. + +«Работающий агент» (WIP) — активная сессия, чья стори в `proposing` / `awaiting_approval` / +`in_progress` / `blocked`. Сессия стори в ревью (ждёт «Принять») слот не занимает, иначе при +«PM принимает» диспетчер вставал бы до приёмки. + +## Пуш при простое +Вопрос (kind `question`, привязан к предлагаемой стори) с вариантами +«▶️ Взять KEY / ⏭ Следующую / 💤 Не сейчас (N ч)». Ответ из любого канала (Telegram-кнопки, +веб, MCP `answer_question`) идёт через `answerAndDeliver` → новый реестр `onAnswer` → +`onIdleAnswer`. «Следующую» — сразу вопрос про следующую по номеру (по кругу), «Не сейчас» +и любой другой текст — тишина на `idlePushHours`. Если агент заработал (PM сам двинул +карточку) или бэклог опустел — открытый вопрос закрывается системой. Лимит: раннер проекта +`rate_limited` или все подписки пула проекта не годятся (`projectPoolExhausted`) — нет ни +запуска, ни пуша. + +## Автомерж и закрытие +- Стори в ревью без PR — мержить нечего, сразу «после мержа». +- `prGate` не пройден: конфликт (`mergeable === false`) → агенту сообщение «rebase на свежий + main, force-with-lease, снова review» и стори в `in_progress` (живому раннеру — в терминал, + иначе новый раннер с этим промптом); один раз на head SHA. Красные/идущие проверки — их + уже ведёт обратная связь CI (PEP-57). +- Проверки зелёные → `autoMergeTask`: PR с изменением конвейера не мержится; вопрос PM теперь + `attention` по стори в ревью, т.е. сообщение ревью с кнопкой «Принять» (мержит + `mergeTaskPr`, который конвейер не проверяет — решение PM). +- После мержа: `after_merge` — открытые вопросы стори закрываются, стори `done` (раннер + останавливается), рабочая копия синхронизируется, людям проекта — короткое сообщение в + Telegram (без вопроса). `pm` / `after_hours` — одно сообщение «готово к ревью · PR смержен». +- `after_hours`: сообщение ревью без ответа N часов → `acceptTask(…, "system")`. Изменение + конвейера так не закрывается никогда (вопрос PM). Замечание PM отвечает на сообщение — и + автозакрытие не срабатывает. +- Хук Stop при `merge=auto` не шлёт «готово к ревью»: PM услышит только если автомерж + невозможен (конвейер) или по настройке закрытия. + +## Рабочая копия (PEP-25) +`syncWorkspace` после «Принять» и автозакрытия: только если в проекте нет активных сессий, +дерево чистое и копия на основной ветке или на ветке этой стори: fetch, checkout main, +`merge --ff-only origin/main`, удалить локальные `task/…` (`branch -d`, только слитые). +Иначе ничего не трогает. `PEPPA_WORKSPACE_SYNC=off` выключает. Ветку на сервере удаляет +Gitea (`delete_branch_after_merge`, уже было). + +## Одобрение proposal +`proposal=pm`: строка в стартовом промпте и раздел «Автономность проекта» + другой «Следующий +шаг» в `get_task`; MCP `update_task(status: in_progress)` из `backlog`/`proposing` отклоняется +(из `awaiting_approval` — как и раньше). Одобрение PM переводит стори в `in_progress` само. + +## Моки +Gitea — `MockGitea`, агенты — `mock-claude`. Мок-агент подставляет `"$TASK"` в аргументах MCP +ключом стори из стартового промпта: один сценарий на все стори проекта (тест диспетчера). + +## Не сделано / дальше +- Приоритеты и ручной порядок бэклога (диспетчер берёт по номеру). +- Пуш при простое уходит обычным вопросом (бот рисует варианты кнопками); отдельной + «не сейчас на N часов» с выбором N нет — N из настроек. +- Ротация подписок при лимите — PEP-39. diff --git a/openspec/changes/pep-23-autonomy/proposal.md b/openspec/changes/pep-23-autonomy/proposal.md new file mode 100644 index 00000000..7643cac6 --- /dev/null +++ b/openspec/changes/pep-23-autonomy/proposal.md @@ -0,0 +1,42 @@ +# PEP-23 · PEP-24 · PEP-25: автономность проекта, диспетчер бэклога, приёмка = мерж + +## Why +Эпик «Автономная фабрика»: проект должен доделываться сам — стори берутся из бэклога, +проверяются, мержатся и закрываются по настройкам проекта; PM нужен только на стопперы. +Простоя нет: либо агент работает, либо PM получил пуш. Сейчас всё это делает PM руками: +двигает карточки, жмёт «Принять», а при простое Пеппа молчит. + +## What Changes +- **PEP-23 — настройки автономности проекта**: уровни «Ручной» (по умолчанию = поведение до + PEP-23), «С подсказками», «Автомат» и отдельные настройки: кто берёт стори (PM / Пеппа, + WIP-лимит), одобрение proposal (только стопперы / каждый), мерж (по «Принять» / авто после + зелёных проверок), закрытие (PM / сразу после мержа / само через N часов без замечаний), + пуш при простое (частота, тихие часы). Веб «⋯ Настройки проекта» → «Автономность», MCP + `get_project_settings` / `update_project_settings`, CLI `peppa project autonomy`. Агент + получает настройки в стартовом промпте и в `get_task`; при «PM одобряет каждый proposal» + MCP не даёт агенту самому перейти в `in_progress`. +- **PEP-24 — диспетчер бэклога** в `tick` вачдога: при «Пеппа берёт сама» — следующая стори + по номеру, пока не заполнен WIP-лимит; иначе (при включённом пуше) — один вопрос PM + «Агенты простаивают. Взять PEP-7?» с кнопками «Взять / Следующую / Не сейчас», не чаще + раза в N часов, не в тихие часы. Во время лимита (раннер проекта `rate_limited` или пул + подписок исчерпан) ничего не запускается и не предлагается. Неудачный запуск — стори + обратно в бэклог, PM одно сообщение, пауза 30 мин. Пустой бэклог в авто-режиме — одно + сообщение до появления новой стори. +- **PEP-25 — приёмка = мерж**: «Принять» уже мержит PR (PEP-57) с удалением ветки; теперь + ещё подтягивает рабочую копию проекта на свежий main (`syncWorkspace`). При «мерж авто» + Пеппа сама мержит зелёный PR без конфликтов (`autoMergeTask`), при конфликте просит + агента сделать rebase (один раз на head-коммит), PR с изменением конвейера ждёт «Принять» + PM (теперь это сообщение ревью с кнопкой). Хук в этом режиме не шлёт «готово к ревью». + +## Capabilities +- New: `project-autonomy`. + +## Impact +- Код: `core/autonomy.ts` (новый), `core/subscriptions.ts` (`projectPoolExhausted`), + `core/tasks.ts` (`TaskDetails.autonomy`), `runner/autonomy.ts`, `runner/workspace-sync.ts` + (новые), `runner/watchdog.ts`, `runner/flow.ts`, `runner/hook.ts`, `runner/sessions.ts` + (обработчики ответов `onAnswer`, `resolveTaskById` экспортирован), `runner/ci-feedback.ts`, + MCP (агент и PM), CLI, веб, `/help`, `template/RULES.md`, мок-агент (`$TASK` в аргументах). +- Данные: без миграций — настройки и состояние в `settings` + (`project.autonomy:`, `autonomy.idle:`, `autonomy.merge:`). +- Живая система: после мержа у всех проектов «Ручной» — ничего не начинает запускаться само. diff --git a/openspec/changes/pep-23-autonomy/specs/project-autonomy/spec.md b/openspec/changes/pep-23-autonomy/specs/project-autonomy/spec.md new file mode 100644 index 00000000..c2f7a444 --- /dev/null +++ b/openspec/changes/pep-23-autonomy/specs/project-autonomy/spec.md @@ -0,0 +1,89 @@ +## ADDED Requirements + +### Requirement: Уровни автономности проекта +У каждого проекта SHALL быть настройки автономности: кто берёт стори из бэклога (PM или +Пеппа, WIP-лимит), нужно ли одобрение PM каждого proposal, мерж PR (по «Принять» или +автоматически), закрытие стори (PM, сразу после мержа, само через N часов без замечаний) и +пуш при простое (частота, тихие часы). Уровни «Ручной», «С подсказками», «Автомат» задают +наборы этих настроек; другая комбинация — «Свой». Проект без настроек SHALL вести себя как +«Ручной» — так же, как до появления настроек. Настройки меняют владелец и участники в вебе, +через MCP `update_project_settings` и CLI. + +#### Scenario: Проект без настроек +- **WHEN** у проекта никогда не меняли автономность и в бэклоге есть стори +- **THEN** ничего не запускается само и PM не получает пушей + +#### Scenario: Уровень и отдельная настройка +- **WHEN** PM выбирает «Автомат», затем включает одобрение каждого proposal +- **THEN** уровень показывается как «Свой», остальные настройки «Автомата» сохраняются + +### Requirement: Одобрение каждого proposal +Если в проекте PM одобряет каждый proposal, агент SHALL получить это в стартовом промпте и +в `get_task`, а MCP SHALL отклонить переход стори агентом из `backlog`/`proposing` в +`in_progress`; стори переходит в `in_progress` одобрением PM. + +#### Scenario: Агент пытается начать Apply сам +- **WHEN** агент после proposal вызывает `update_task(status: in_progress)` +- **THEN** вызов отклонён с указанием запросить одобрение; после `request_approval` и ответа «ок» стори в `in_progress` + +### Requirement: Диспетчер бэклога +Вачдог SHALL для проектов, где стори берёт Пеппа, запускать агентов на следующие стори +бэклога (наименьший номер), пока число работающих агентов проекта меньше WIP-лимита. +Работающий агент — активная сессия стори в `proposing`, `awaiting_approval`, `in_progress` +или `blocked`. Во время лимита (раннер проекта `rate_limited` или пул подписок проекта без +пригодных подписок) диспетчер SHALL ничего не запускать. Неудачный запуск SHALL вернуть +стори в бэклог, сообщить PM один раз и не повторять попытку 30 минут. + +#### Scenario: Автомат проходит бэклог без человека +- **WHEN** проект в «Автомате», в бэклоге две стори, агент доводит первую до ревью +- **THEN** первая мержится и закрывается, и в том же тике вачдога агент берёт вторую + +#### Scenario: Лимит +- **WHEN** раннер проекта упёрся в лимит подписки +- **THEN** новые стори не запускаются и PM не получает пуш о простое + +### Requirement: Пуш при простое +Если стори берёт PM, пуш включён, ни один агент проекта не работает, а в бэклоге есть стори, +PM SHALL получить один вопрос «Агенты простаивают. Взять в работу KEY?» с вариантами +«Взять», «Следующую», «Не сейчас» — не чаще раза в N часов, не в тихие часы и не во время +лимита. «Взять» запускает агента, «Следующую» сразу предлагает следующую стори, «Не сейчас» +выключает пуши на N часов. Если агент заработал или бэклог опустел, открытый вопрос +закрывается сам. + +#### Scenario: Простой +- **WHEN** в проекте «С подсказками» нет работающих агентов, в бэклоге PEP-7 +- **THEN** PM получает один вопрос с кнопками; повторный тик вачдога второго не создаёт + +#### Scenario: Тихие часы +- **WHEN** условия простоя наступили в 23:00 при тихих часах 22–9 +- **THEN** пуш уходит не раньше 9:00 + +### Requirement: Приёмка мержит PR и обновляет рабочую копию +«Принять» SHALL мержить PR стори (зелёные проверки, без конфликтов), Gitea удаляет ветку, а +рабочая копия проекта SHALL подтянуть основную ветку — только если в проекте нет активных +сессий, дерево чистое и копия на основной ветке или на ветке этой стори; иначе копия не +трогается. + +#### Scenario: Копия на ветке стори +- **WHEN** PR стори смержен, рабочая копия чистая и на ветке `task/KEY-N` +- **THEN** копия переключается на основную ветку, догоняет её, локальная ветка стори удаляется + +### Requirement: Автомерж и автозакрытие +При «мерж авто» Пеппа SHALL мержить PR стори в ревью после зелёных проверок головного +коммита и без конфликтов; хук не шлёт PM «готово к ревью». При конфликте агент SHALL +получить просьбу сделать rebase (один раз на головной коммит). PR, меняющий конвейер, SHALL +не мержиться и не закрываться автоматически: PM получает одно сообщение ревью с кнопкой +«Принять». После мержа стори закрывается по настройке: сразу, по «Принять» PM или сама +через N часов без замечаний. + +#### Scenario: Зелёный PR +- **WHEN** стори в ревью, проверки PR зелёные, конфликтов нет, закрытие «сразу после мержа» +- **THEN** PR смержен, стори в «Готово», её раннер остановлен + +#### Scenario: Конфликт +- **WHEN** PR стори конфликтует с основной веткой +- **THEN** стори возвращается в работу, агент получает просьбу о rebase + +#### Scenario: Закрытие по времени +- **WHEN** закрытие «через 2 часа», сообщение ревью без ответа 2 часа +- **THEN** стори принимается автоматически (PR мержится), ответ — «Принято автоматически» diff --git a/openspec/changes/pep-23-autonomy/tasks.md b/openspec/changes/pep-23-autonomy/tasks.md new file mode 100644 index 00000000..7dae9b06 --- /dev/null +++ b/openspec/changes/pep-23-autonomy/tasks.md @@ -0,0 +1,25 @@ +# Tasks + +## 1. Настройки (PEP-23) +- [x] 1.1 `core/autonomy.ts`: поля, уровни, `getAutonomy`/`setAutonomy` (в `settings`), валидация, тихие часы, описание +- [x] 1.2 Агент: строка в стартовом промпте, раздел и «следующий шаг» в `get_task`, гвард MCP при proposal=pm +- [x] 1.3 Веб «⋯ Настройки проекта» → «Автономность» (уровни + подробно), server action +- [x] 1.4 MCP PM `get_project_settings` / `update_project_settings`, инструкции сервера, `/help` +- [x] 1.5 CLI `peppa project autonomy [уровень] [key=value…]` +- [x] 1.6 `template/RULES.md`, `AGENTS.md` + +## 2. Диспетчер (PEP-24) +- [x] 2.1 `runner/autonomy.ts` `autonomyTick` в `tick` вачдога +- [x] 2.2 Авто: WIP-лимит, порядок по номеру, лимит/пул → пауза, неудачный старт → бэклог + сообщение + 30 мин +- [x] 2.3 Пуш при простое: вопрос с кнопками, дедуп, частота, тихие часы, «Следующую»/«Не сейчас»/«Взять» (`onAnswer` в `answerAndDeliver`) +- [x] 2.4 Пустой бэклог в авто — одно сообщение + +## 3. Приёмка = мерж (PEP-25) +- [x] 3.1 Автомерж стори в ревью, rebase при конфликте, вопрос с «Принять» при изменении конвейера +- [x] 3.2 Закрытие: after_merge / pm / after_hours (без автозакрытия конвейера) +- [x] 3.3 Хук: без «готово к ревью» при merge=auto +- [x] 3.4 `syncWorkspace` после «Принять» и автозакрытия + +## 4. Тесты и документация +- [x] 4.1 `packages/testkit/test/autonomy-levels.test.ts` (17 сценариев), `$TASK` в мок-агенте +- [x] 4.2 typecheck, весь e2e diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index a79cf379..4d4663df 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -3,6 +3,10 @@ import { parseArgs } from "node:util"; import { resolve } from "node:path"; import { backupDb, + describeAutonomy, + getAutonomy, + setAutonomy, + type AutonomyPatch, createGoal, createProject, createTask, @@ -58,6 +62,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project create [--existing] [--private] (repo in peppa-bot's Gitea namespace) peppa project add [--owner peppa] [--repo ] [--path ] (register only) peppa project owner + peppa project autonomy [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes) peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) peppa project list peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) @@ -246,6 +251,33 @@ async function main(): Promise { if (failed) process.exitCode = 1; break; } + case "project autonomy": { + // PEP-23: peppa project autonomy [manual|assisted|auto] [key=value…] + const [key, ...rest] = args; + if (!key) throw new PeppaError("usage: peppa project autonomy [manual|assisted|auto] [pick=pm|auto wipLimit=N proposal=agent|pm merge=manual|auto close=pm|after_merge|after_hours closeAfterHours=N idlePush=on|off idlePushHours=N quiet=22-9|off]"); + const p = await getProject(db, key); + if (rest.length) { + const patch: AutonomyPatch = {}; + for (const arg of rest) { + if (["manual", "assisted", "auto"].includes(arg)) { + patch.level = arg as AutonomyPatch["level"]; + continue; + } + const [k, v = ""] = arg.split("="); + if (k === "quiet") { + const m = /^(\d+)-(\d+)$/.exec(v); + patch.quietFrom = m ? Number(m[1]) : null; + patch.quietTo = m ? Number(m[2]) : null; + } else if (k === "idlePush") patch.idlePush = v === "on" || v === "true"; + else if (k === "wipLimit" || k === "closeAfterHours" || k === "idlePushHours") patch[k] = Number(v); + else if (k === "pick" || k === "proposal" || k === "merge" || k === "close") (patch as Record)[k] = v; + else throw new PeppaError(`unknown setting: ${k}`); + } + await setAutonomy(db, p.id, patch); + } + console.log(`${p.key}\n${describeAutonomy(await getAutonomy(db, p.id))}`); + break; + } case "project list": for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`); break; diff --git a/packages/core/src/autonomy.ts b/packages/core/src/autonomy.ts new file mode 100644 index 00000000..83f62cf2 --- /dev/null +++ b/packages/core/src/autonomy.ts @@ -0,0 +1,160 @@ +// Project autonomy (PEP-23): who takes stories from the backlog, whether the PM approves +// proposals, how PRs are merged and how stories are closed, and idle pushes (PEP-24). +// Stored in `settings` (`project.autonomy:`), no schema change; a project without a +// row is "manual" — exactly the behaviour before PEP-23. +import type { Db } from "@peppa/db"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +export type PickMode = "pm" | "auto"; +export type ProposalMode = "agent" | "pm"; +export type MergeMode = "manual" | "auto"; +export type CloseMode = "pm" | "after_merge" | "after_hours"; + +export interface AutonomySettings { + /** Who takes stories from the backlog: the PM (board) or the dispatcher (watchdog). */ + pick: PickMode; + /** Stories the dispatcher keeps in work at once (agents share the project's working copy). */ + wipLimit: number; + /** "pm": every proposal needs the PM's approval; "agent": only architectural stoppers. */ + proposal: ProposalMode; + /** "auto": a green PR without conflicts and pipeline changes is merged by Peppa. */ + merge: MergeMode; + /** When a story in review becomes Done. */ + close: CloseMode; + closeAfterHours: number; + /** Push to the PM when no agent works and the backlog is not empty (PM picks). */ + idlePush: boolean; + /** Not more often than this per project; also the "not now" snooze. */ + idlePushHours: number; + /** Quiet hours (local time, 0–23): no idle pushes from `quietFrom` to `quietTo`. Null = none. */ + quietFrom: number | null; + quietTo: number | null; +} + +export type AutonomyLevel = "manual" | "assisted" | "auto"; + +const BASE: AutonomySettings = { + pick: "pm", + wipLimit: 1, + proposal: "agent", + merge: "manual", + close: "pm", + closeAfterHours: 24, + idlePush: false, + idlePushHours: 4, + quietFrom: 22, + quietTo: 9, +}; + +/** Presets shown as levels; any other combination is "custom". */ +export const AUTONOMY_LEVELS: Record = { + // Before PEP-23: the PM moves cards and accepts; nothing starts by itself. + manual: BASE, + // The PM still decides, but Peppa pushes when agents idle with a non-empty backlog. + assisted: { ...BASE, idlePush: true }, + // Backlog → Done without a human: dispatcher, auto-merge, closing after the merge. + auto: { ...BASE, pick: "auto", merge: "auto", close: "after_merge", idlePush: true }, +}; + +export const AUTONOMY_LEVEL_RU: Record = { + manual: "Ручной", + assisted: "С подсказками", + auto: "Автомат", + custom: "Свой", +}; + +export const AUTONOMY_LEVEL_HINT: Record = { + manual: "PM двигает карточки и принимает стори; при простое Пеппа молчит.", + assisted: "PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас».", + auto: "Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера.", +}; + +const key = (projectId: number) => `project.autonomy:${projectId}`; + +export function autonomyLevel(s: AutonomySettings): AutonomyLevel | "custom" { + for (const [name, preset] of Object.entries(AUTONOMY_LEVELS) as Array<[AutonomyLevel, AutonomySettings]>) { + if ((Object.keys(BASE) as Array).every((k) => preset[k] === s[k])) return name; + } + return "custom"; +} + +export async function getAutonomy(db: Db, projectId: number): Promise { + const stored = await getSetting>(db, key(projectId)); + return normalize({ ...BASE, ...(stored ?? {}) }); +} + +export type AutonomyPatch = Partial & { level?: AutonomyLevel }; + +const intIn = (v: unknown, min: number, max: number, name: string): number => { + const n = Number(v); + if (!Number.isInteger(n) || n < min || n > max) throw new PeppaError(`${name}: целое от ${min} до ${max}`); + return n; +}; + +function normalize(s: AutonomySettings): AutonomySettings { + const oneOf = (v: unknown, all: readonly T[], name: string): T => { + if (!all.includes(v as T)) throw new PeppaError(`${name}: одно из ${all.join(", ")}`); + return v as T; + }; + const hour = (v: unknown, name: string) => (v === null || v === undefined || v === "" ? null : intIn(v, 0, 23, name)); + const quietFrom = hour(s.quietFrom, "quietFrom"); + const quietTo = hour(s.quietTo, "quietTo"); + return { + pick: oneOf(s.pick, ["pm", "auto"], "pick"), + wipLimit: intIn(s.wipLimit, 1, 5, "wipLimit"), + proposal: oneOf(s.proposal, ["agent", "pm"], "proposal"), + merge: oneOf(s.merge, ["manual", "auto"], "merge"), + close: oneOf(s.close, ["pm", "after_merge", "after_hours"], "close"), + closeAfterHours: intIn(s.closeAfterHours, 1, 24 * 14, "closeAfterHours"), + idlePush: Boolean(s.idlePush), + idlePushHours: intIn(s.idlePushHours, 1, 24 * 7, "idlePushHours"), + // Both or none: half a range means nothing. + quietFrom: quietFrom != null && quietTo != null ? quietFrom : null, + quietTo: quietFrom != null && quietTo != null ? quietTo : null, + }; +} + +/** + * Changes a project's autonomy: a preset `level` first, then individual fields on top. + * Manual without overrides removes the row (back to "never configured"). + */ +export async function setAutonomy(db: Db, projectId: number, patch: AutonomyPatch): Promise { + const { level, ...fields } = patch; + if (level && !(level in AUTONOMY_LEVELS)) throw new PeppaError(`Уровень: одно из ${Object.keys(AUTONOMY_LEVELS).join(", ")}`); + const base = level ? AUTONOMY_LEVELS[level] : await getAutonomy(db, projectId); + const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)); + const next = normalize({ ...base, ...defined }); + if (JSON.stringify(next) === JSON.stringify(BASE)) await deleteSetting(db, key(projectId)); + else await setSetting(db, key(projectId), next); + return next; +} + +/** True inside the quiet hours (local time of the machine Peppa runs on). */ +export function inQuietHours(s: Pick, now: Date): boolean { + if (s.quietFrom == null || s.quietTo == null || s.quietFrom === s.quietTo) return false; + const h = now.getHours(); + return s.quietFrom < s.quietTo ? h >= s.quietFrom && h < s.quietTo : h >= s.quietFrom || h < s.quietTo; +} + +/** One-paragraph description for the PM (web, MCP, CLI). */ +export function describeAutonomy(s: AutonomySettings): string { + const level = autonomyLevel(s); + const lines = [ + `Уровень: ${AUTONOMY_LEVEL_RU[level]}`, + `Стори из бэклога берёт: ${s.pick === "auto" ? `Пеппа сама (одновременно до ${s.wipLimit})` : "PM"}`, + `Proposal: ${s.proposal === "pm" ? "каждый одобряет PM" : "без одобрения, кроме архитектурных стопперов"}`, + `Мерж PR: ${s.merge === "auto" ? "автоматически после зелёных проверок (кроме изменений конвейера)" : "по «Принять»"}`, + `Закрытие: ${s.close === "pm" ? "PM принимает" : s.close === "after_merge" ? "сразу после мержа" : `само через ${s.closeAfterHours} ч без замечаний`}`, + `Пуш при простое: ${s.idlePush ? `да, не чаще раза в ${s.idlePushHours} ч${s.quietFrom != null ? `, тихие часы ${s.quietFrom}:00–${s.quietTo}:00` : ""}` : "нет"}`, + ]; + return lines.join("\n"); +} + +/** The extra instruction for agents of a project (appended to the start prompt and get_task). */ +export function agentAutonomyNote(s: AutonomySettings): string | null { + const notes: string[] = []; + if (s.proposal === "pm") notes.push("В этом проекте PM одобряет каждый proposal: после proposal — peppa.request_approval и конец хода, Apply только после одобрения."); + if (s.merge === "auto") notes.push("PR мержит Пеппа сама после зелёных проверок; не мержи его сам. Если Пеппа попросит ребейз — rebase на основную ветку и force-push в ту же ветку."); + return notes.length ? notes.join("\n") : null; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 8a0aea00..ffadff13 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -25,3 +25,4 @@ export * from "./reviews.ts"; export * from "./webpush.ts"; export * from "./notifications.ts"; export * from "./digest.ts"; +export * from "./autonomy.ts"; diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts index 5b8d8e45..4c3f9670 100644 --- a/packages/core/src/subscriptions.ts +++ b/packages/core/src/subscriptions.ts @@ -268,3 +268,13 @@ export async function projectPool(db: Db, projectId: number): Promise { + const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId)); + if (p?.poolId == null) return false; + return !(await poolSubscriptions(db, p.poolId)).some((s) => isUsable(s, now)); +} diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index fd9c116b..36041584 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -7,6 +7,7 @@ import { getGoal, getProject, type Goal, type Project } from "./projects.ts"; import { incidentForTask, type Incident } from "./incidents.ts"; import { taskCiSummary, type CiSummary } from "./ci.ts"; import { latestReview, type CodeReview } from "./reviews.ts"; +import { getAutonomy, type AutonomySettings } from "./autonomy.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -131,6 +132,8 @@ export interface TaskDetails { ci: CiSummary; /** Latest review by the project's reviewer agent (PEP-26), if any. */ review: CodeReview | null; + /** The project's autonomy settings (PEP-23): agents follow them. */ + autonomy: AutonomySettings; } export async function getTaskDetails(db: Db, ref: TaskRef): Promise { @@ -143,7 +146,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise .orderBy(desc(events.id)) .limit(20); const incident = await incidentForTask(db, ref.task.id); - return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id) }; + return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id) }; } export interface NewQuestion { diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts index a57631eb..1de888bf 100644 --- a/packages/mcp/src/format.ts +++ b/packages/mcp/src/format.ts @@ -1,4 +1,4 @@ -import { formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core"; +import { agentAutonomyNote, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core"; const NEXT_STEP: Record = { backlog: "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → если нет архитектурных решений, сразу update_task(status: in_progress) и Apply в этом же ходе.", @@ -41,7 +41,14 @@ export function formatTask(d: TaskDetails): string { lines.push("", "## Последний прогресс"); for (const e of progress.slice(-5)) lines.push(`- ${e.createdAt.toISOString().slice(0, 16)} ${(e.payload as { text: string }).text}`); } - lines.push("", "## Следующий шаг", "", NEXT_STEP[task.status]); + // PEP-23: the project's autonomy changes the next step (PM approves every proposal). + const pmApproves = d.autonomy?.proposal === "pm" && (task.status === "backlog" || task.status === "proposing"); + const next = pmApproves + ? "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → в этом проекте PM одобряет каждый proposal: request_approval и конец хода. Apply — только после одобрения." + : NEXT_STEP[task.status]; + lines.push("", "## Следующий шаг", "", next); + const note = d.autonomy ? agentAutonomyNote(d.autonomy) : null; + if (note) lines.push("", "## Автономность проекта", "", note); return lines.join("\n"); } diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index be92198b..c20943e4 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -7,6 +7,7 @@ import { createTask, findProjectFile, getIncident, + getAutonomy, getProject, getTaskDetails, incidentStatuses, @@ -132,6 +133,11 @@ tool( if (status === "in_progress" && ref.task.status === "awaiting_approval") { throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress."); } + // PEP-23: a project where the PM approves every proposal — Apply only after the approval + // (the PM's answer moves the story to in_progress itself). + if (status === "in_progress" && (ref.task.status === "backlog" || ref.task.status === "proposing") && (await getAutonomy(db, ref.project.id)).proposal === "pm") { + throw new PeppaError("In this project the PM approves every proposal: call request_approval with the proposal summary and end your turn."); + } if (status === "review" && ref.task.status !== "review") { // PEP-57: review only with green checks of the PR head (the PR given now counts). const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } }); diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index aa32f29a..df86650e 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -3,6 +3,9 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { createEpic, + describeAutonomy, + getAutonomy, + setAutonomy, createTask, getEpic, updateEpic, @@ -54,6 +57,7 @@ Good habits: - Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user. - Projects can be shared: add_member / remove_member (owner only); members can do everything else. Repos are public by default; set_project_visibility (owner only) makes one private or public again. - CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks. +- Autonomy (get_project_settings / update_project_settings): manual by default; "auto" lets Peppa take stories from the backlog, merge green PRs and close stories itself; "assisted" only pushes the user when agents idle. Change it only when the user asks. - Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`; export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { @@ -189,6 +193,49 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ }, ); + // PEP-23: autonomy of a project — levels and individual settings (owner or member). + tool("get_project_settings", "A project's autonomy settings: who takes stories from the backlog, PM approval of proposals, merge and closing mode, idle pushes.", { project: projectArg }, true, async ({ project }) => { + const p = await ownedProject(project); + return describeAutonomy(await getAutonomy(db, p.id)); + }); + + tool( + "update_project_settings", + "Change a project's autonomy. level: manual (the user moves cards and accepts; default), assisted (as manual + a push when agents idle with a non-empty backlog), auto (Peppa takes stories from the backlog itself, merges green PRs and closes stories after the merge). Individual fields override the level. Only when the user asks.", + { + project: projectArg, + level: z.enum(["manual", "assisted", "auto"]).optional(), + pick: z.enum(["pm", "auto"]).optional().describe("Who takes stories from the backlog"), + wip_limit: z.number().int().min(1).max(5).optional().describe("Stories in work at once when pick=auto"), + proposal: z.enum(["agent", "pm"]).optional().describe("pm = the user approves every proposal"), + merge: z.enum(["manual", "auto"]).optional().describe("auto = merge green PRs without conflicts (pipeline changes always need the user)"), + close: z.enum(["pm", "after_merge", "after_hours"]).optional(), + close_after_hours: z.number().int().min(1).max(336).optional(), + idle_push: z.boolean().optional().describe("Push the user when no agent works and the backlog is not empty"), + idle_push_hours: z.number().int().min(1).max(168).optional(), + quiet_from: z.number().int().min(0).max(23).nullable().optional(), + quiet_to: z.number().int().min(0).max(23).nullable().optional(), + }, + false, + async (a) => { + const p = await ownedProject(a.project); + const s = await setAutonomy(db, p.id, { + level: a.level, + pick: a.pick, + wipLimit: a.wip_limit, + proposal: a.proposal, + merge: a.merge, + close: a.close, + closeAfterHours: a.close_after_hours, + idlePush: a.idle_push, + idlePushHours: a.idle_push_hours, + quietFrom: a.quiet_from, + quietTo: a.quiet_to, + }); + return `${p.key}:\n${describeAutonomy(s)}`; + }, + ); + tool( "list_tasks", "List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column.", diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts new file mode 100644 index 00000000..f964e17f --- /dev/null +++ b/packages/runner/src/autonomy.ts @@ -0,0 +1,332 @@ +// Autonomous factory (PEP-23/24/25), run from the watchdog tick: +// - auto-merge of green review PRs and closing by the project's settings (PEP-25); +// - closing a story N hours after "ready for review" without comments (PEP-23); +// - the backlog dispatcher: either an agent works, or the PM got a push (PEP-24). +// Everything here is driven by core/autonomy.ts settings; "manual" (default) does nothing. +import { + answerQuestion, + askPm, + askPmProject, + enqueueTelegram, + getAutonomy, + getSetting, + giteaForBot, + inQuietHours, + listProjects, + listSessions, + listTasks, + pipelineChanges, + prGate, + projectPoolExhausted, + questionRecipients, + raiseSessionQuestion, + setSetting, + taskPrNumber, + type AutonomySettings, + type GiteaClient, + type Project, + type Question, + type SessionView, + type Task, + type TaskRef, +} from "@peppa/core"; +import { questions, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, eq, isNull } from "drizzle-orm"; +import { acceptTask, moveTask } from "./flow.ts"; +import { autoMergeTask } from "./ci-feedback.ts"; +import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts"; +import { syncWorkspace } from "./workspace-sync.ts"; + +export interface AutonomyTickOptions { + now?: Date; + log?: (m: string) => void; + gitea?: GiteaClient; +} + +/** Statuses in which a session counts as an agent at work (WIP) for the dispatcher. */ +const WORKING: Task["status"][] = ["proposing", "awaiting_approval", "in_progress", "blocked"]; +/** After a failed automatic start, the dispatcher waits this long before trying again. */ +export const DISPATCH_RETRY_MS = 30 * 60_000; + +export const IDLE_TAKE = "▶️ Взять"; +export const IDLE_NEXT = "⏭ Следующую"; +export const IDLE_SNOOZE = "💤 Не сейчас"; + +interface IdleState { + /** The open "agents are idle" question. */ + questionId?: number | null; + /** When the last idle push went out (ms). */ + at?: number; + snoozeUntil?: number; + /** Auto mode: the PM was told the backlog is empty (until a story appears). */ + emptyNotified?: boolean; + /** Auto mode: no new start attempts before this (ms) after a failed one. */ + failUntil?: number; +} +const idleKey = (projectId: number) => `autonomy.idle:${projectId}`; +const getIdle = async (db: Db, projectId: number) => (await getSetting(db, idleKey(projectId))) ?? {}; +const setIdle = (db: Db, projectId: number, s: IdleState) => setSetting(db, idleKey(projectId), s); + +/** Per story: what the auto-merge already did for its PR (no repeated questions/rebase requests). */ +interface MergeState { + /** Head SHA whose pipeline change the PM was asked about. */ + pipelineSha?: string; + /** Head SHA the agent was asked to rebase. */ + rebaseSha?: string; + /** PR (or "no-pr") for which the "merged, accept?" message was raised. */ + reviewFor?: string; +} +const mergeKey = (taskId: number) => `autonomy.merge:${taskId}`; + +const refOf = (project: Project, task: Task): TaskRef => ({ project, task, key: formatTaskKey(project.key, task.number) }); + +export async function autonomyTick(db: Db, opts: AutonomyTickOptions = {}): Promise { + const log = opts.log ?? (() => {}); + const now = opts.now ?? new Date(); + for (const project of await listProjects(db)) { + const a = await getAutonomy(db, project.id); + if (a.pick === "pm" && a.merge === "manual" && a.close === "pm" && !a.idlePush) continue; // manual + try { + if (a.merge === "auto") await autoMergeReviews(db, project, a, opts.gitea, log); + if (a.close === "after_hours") await autoCloseReviews(db, project, a, now, opts.gitea, log); + await dispatch(db, project, a, now, log); + } catch (e) { + log(`autonomy ${project.key}: ${(e as Error).message}`); + } + } +} + +// ── PEP-25: auto-merge and closing ───────────────────────────────────────────── + +async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, client: GiteaClient | undefined, log: (m: string) => void) { + for (const task of await listTasks(db, { projectId: project.id, statuses: ["review"] })) { + const ref = refOf(project, task); + const state = (await getSetting(db, mergeKey(task.id))) ?? {}; + if (!taskPrNumber(project, task.prUrl)) { + await afterMerge(db, ref, a, state, log); + continue; + } + const gitea = client ?? giteaForBot(); + const gate = await prGate(ref, gitea); + if (!gate.pull || gate.pull.merged) { + await afterMerge(db, ref, a, state, log); + continue; + } + const sha = gate.pull.head.sha; + if (!gate.ok) { + // Conflicts: the agent rebases itself (once per head commit). Red/pending: CI feedback. + if (gate.pull.mergeable === false && state.rebaseSha !== sha) { + await setSetting(db, mergeKey(task.id), { ...state, rebaseSha: sha }); + await requestRebase(db, ref); + log(`${ref.key}: conflicts — rebase requested`); + } + continue; + } + if (state.pipelineSha === sha) continue; // the PM reviews this pipeline change + const r = await autoMergeTask(db, ref, gitea); + if (r.merged) { + log(`${ref.key}: PR auto-merged`); + await afterMerge(db, ref, a, state, log); + } else if (r.reason) { + await setSetting(db, mergeKey(task.id), { ...state, pipelineSha: sha }); + log(`${ref.key}: not auto-merged — ${r.reason}`); + } + } +} + +async function requestRebase(db: Db, ref: TaskRef) { + const text = `Пеппа не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review).`; + const session = (await listSessions(db, { active: true, taskId: ref.task.id }))[0]; + if (session) { + await sendToSession(db, session.id, text).catch(() => {}); + await moveTask(db, ref, "in_progress"); + } else { + await moveTask(db, ref, "in_progress", { prompt: text }); + } +} + +/** The PR is merged (or there is none): close the story or ask the PM, by `close`. */ +async function afterMerge(db: Db, ref: TaskRef, a: AutonomySettings, state: MergeState, log: (m: string) => void) { + if (a.close === "after_merge") { + await closeStory(db, ref, "✅ Закрыто автоматически: PR смержен"); + await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `🤖 ${ref.key} «${ref.task.title}»: PR смержен, стори закрыта автоматически.`); + log(`${ref.key}: closed after merge`); + return; + } + const pr = ref.task.prUrl ?? "no-pr"; + if (state.reviewFor === pr) return; + await setSetting(db, mergeKey(ref.task.id), { ...state, reviewFor: pr }); + const text = `✅ Стори ${ref.key} готова к ревью${ref.task.prUrl ? ` · PR смержен автоматически: ${ref.task.prUrl}` : ""}${ + a.close === "after_hours" ? `\nЗакроется сама через ${a.closeAfterHours} ч, если не будет замечаний.` : "" + }`; + const session = (await listSessions(db, { active: true, taskId: ref.task.id }))[0]; + if (session) await raiseSessionQuestion(db, session, "attention", text); + else await askPm(db, ref, { kind: "attention", text }); +} + +/** Done: pending questions of the story are closed, its agent stopped, the working copy updated. */ +async function closeStory(db: Db, ref: TaskRef, answer: string) { + const open = await db.select().from(questions).where(and(eq(questions.taskId, ref.task.id), isNull(questions.answeredAt))); + for (const q of open) await answerQuestion(db, q.id, answer, "system").catch(() => {}); + await moveTask(db, ref, "done"); + await syncWorkspace(db, ref).catch(() => "failed"); +} + +/** close = after_hours: "ready for review" unanswered for N hours → accepted (merged if needed). */ +async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, now: Date, client: GiteaClient | undefined, log: (m: string) => void) { + const cutoff = now.getTime() - a.closeAfterHours * 3_600_000; + for (const task of await listTasks(db, { projectId: project.id, statuses: ["review"] })) { + const [q] = await db + .select() + .from(questions) + .where(and(eq(questions.taskId, task.id), eq(questions.kind, "attention"), isNull(questions.answeredAt))); + if (!q || q.createdAt.getTime() > cutoff) continue; + const ref = refOf(project, task); + // A pipeline change is never accepted without the PM, however long it waits. + const state = (await getSetting(db, mergeKey(task.id))) ?? {}; + if (state.pipelineSha) continue; + if (taskPrNumber(project, task.prUrl)) { + const gitea = client ?? giteaForBot(); + const gate = await prGate(ref, gitea).catch(() => null); + if (gate?.pull && !gate.pull.merged && (await pipelineChanges(ref, gate.pull, gitea)).length) { + await setSetting(db, mergeKey(task.id), { ...state, pipelineSha: gate.pull.head.sha }); + await askPm(db, ref, { kind: "question", text: `⚠️ ${ref.key}: PR меняет конвейер (.gitea/, checks/deploy) — сам не закрою, нужно ваше «Принять».` }); + continue; + } + } + try { + await acceptTask(db, q.id, "system", `✅ Принято автоматически: ${a.closeAfterHours} ч без замечаний`); + await notifyPm(db, project.id, `auto:accepted:${q.id}`, `🤖 ${ref.key} «${task.title}» закрыта автоматически: ${a.closeAfterHours} ч без замечаний.`); + log(`${ref.key}: closed after ${a.closeAfterHours}h`); + } catch (e) { + const key = `auto:closefail:${q.id}`; + if (!(await getSetting(db, key))) { + await setSetting(db, key, true); + await askPm(db, ref, { kind: "question", text: `⚠️ ${ref.key}: не получилось закрыть автоматически — ${(e as Error).message}` }); + } + log(`${ref.key}: auto-close failed — ${(e as Error).message}`); + } + } +} + +/** A plain Telegram message (no question, nothing to answer) to the project's people. */ +async function notifyPm(db: Db, projectId: number, dedupeKey: string, text: string) { + for (const u of await questionRecipients(db, projectId)) { + await enqueueTelegram(db, { dedupeKey: `${dedupeKey}:${u.id}`, method: "sendMessage", params: { chat_id: u.telegramChatId, text } }); + } +} + +// ── PEP-24: dispatcher ───────────────────────────────────────────────────────── + +async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date, log: (m: string) => void) { + const sessions = (await listSessions(db, { active: true })).filter((s) => s.projectId === project.id); + const working = await workingSessions(db, sessions); + const backlog = await listTasks(db, { projectId: project.id, statuses: ["backlog"] }); + const state = await getIdle(db, project.id); + + // Someone works or nothing is left: an open "agents are idle" question is moot. + if ((working.length > 0 || !backlog.length) && state.questionId) { + await answerQuestion(db, state.questionId, "(неактуально: агент уже работает или бэклог пуст)", "system").catch(() => {}); + state.questionId = null; + await setIdle(db, project.id, state); + } + if (backlog.length && state.emptyNotified) { + state.emptyNotified = false; + await setIdle(db, project.id, state); + } + // Limits: never start or offer while the project's agents can't run. + const limited = sessions.some((s) => s.status === "rate_limited") || (await projectPoolExhausted(db, project.id, now)); + + if (a.pick === "auto") { + if (limited || (state.failUntil ?? 0) > now.getTime()) return; + let slots = a.wipLimit - working.length; + for (const task of backlog) { + if (slots <= 0) break; + const ref = refOf(project, task); + try { + const r = await moveTask(db, ref, "in_progress", { prompt: "Стори взята из бэклога автоматически (автономность проекта). Работай по правилам до PR и review." }); + log(`${ref.key}: dispatched (session #${r.started})`); + slots--; + } catch (e) { + // Back to the backlog: the card must not hang in "in progress" without an agent. + const fresh = await resolveTaskById(db, task.id).catch(() => null); + if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {}); + await setIdle(db, project.id, { ...state, failUntil: now.getTime() + DISPATCH_RETRY_MS }); + await askPmProject(db, project, { + kind: "attention", + text: `⚠️ ${project.name}: диспетчер не смог запустить агента на ${ref.key} — ${(e as Error).message}\nПовторю через ${DISPATCH_RETRY_MS / 60_000} мин.`, + }); + log(`${ref.key}: dispatch failed — ${(e as Error).message}`); + return; + } + } + if (!backlog.length && working.length === 0 && a.idlePush && !state.emptyNotified) { + await setIdle(db, project.id, { ...state, emptyNotified: true }); + await askPmProject(db, project, { kind: "attention", text: `📭 ${project.name}: бэклог пуст — агентам нечего делать. Добавьте стори, и Пеппа возьмёт их сама.` }); + } + return; + } + + if (!a.idlePush || working.length > 0 || !backlog.length || limited || state.questionId) return; + if (inQuietHours(a, now)) return; + if ((state.snoozeUntil ?? 0) > now.getTime()) return; + if (state.at && now.getTime() - state.at < a.idlePushHours * 3_600_000) return; + await offerStory(db, project, backlog[0]!, now); + log(`${project.key}: idle push (${formatTaskKey(project.key, backlog[0]!.number)})`); +} + +/** Sessions that hold a WIP slot: their story is being worked on (not in review). */ +async function workingSessions(db: Db, sessions: SessionView[]): Promise { + const out: SessionView[] = []; + for (const s of sessions) { + if (!s.taskId) continue; + const ref = await resolveTaskById(db, s.taskId).catch(() => null); + if (ref && WORKING.includes(ref.task.status)) out.push(s); + } + return out; +} + +async function offerStory(db: Db, project: Project, task: Task, now: Date) { + const a = await getAutonomy(db, project.id); + const ref = refOf(project, task); + const left = (await listTasks(db, { projectId: project.id, statuses: ["backlog"] })).length; + const q = await askPm(db, ref, { + kind: "question", + text: `😴 ${project.name}: агенты простаивают, в бэклоге ${left}. Взять в работу ${ref.key} «${task.title}»?`, + options: [`${IDLE_TAKE} ${ref.key}`, IDLE_NEXT, `${IDLE_SNOOZE} (${a.idlePushHours} ч)`], + }); + const state = await getIdle(db, project.id); + await setIdle(db, project.id, { ...state, questionId: q.id, at: now.getTime() }); +} + +/** The PM's answer to an "agents are idle" push (Telegram buttons, web, MCP). */ +export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise { + const state = await getIdle(db, q.projectId); + if (!state.questionId || state.questionId !== q.id || !q.taskId) return false; + const ref = await resolveTaskById(db, q.taskId); + const a = await getAutonomy(db, q.projectId); + const now = Date.now(); + const text = answer.trim(); + if (text.startsWith(IDLE_NEXT)) { + const backlog = await listTasks(db, { projectId: q.projectId, statuses: ["backlog"] }); + const next = backlog.find((t) => t.number > ref.task.number) ?? backlog[0]; + await setIdle(db, q.projectId, { ...state, questionId: null }); + if (next) await offerStory(db, ref.project, next, new Date(now)); + return true; + } + if (text.startsWith(IDLE_TAKE)) { + await setIdle(db, q.projectId, { ...state, questionId: null }); + if (ref.task.status !== "backlog") return true; // already moved by someone + try { + await moveTask(db, ref, "in_progress"); + } catch (e) { + await askPmProject(db, ref.project, { kind: "attention", text: `⚠️ ${ref.key} не запущена: ${(e as Error).message}` }); + } + return true; + } + // "Not now" (or any other text): quiet for idlePushHours. + await setIdle(db, q.projectId, { ...state, questionId: null, snoozeUntil: now + a.idlePushHours * 3_600_000 }); + return true; +} +onAnswer(onIdleAnswer); diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 190a0891..8bf13aff 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -230,9 +230,10 @@ export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = g if (!gate.ok) return { merged: false, reason: gate.reason }; const changes = await pipelineChanges(ref, gate.pull, gitea); if (changes.length) { + // An "attention" on a story in review is its review message: the PM gets «Принять» (merges). await askPm(db, ref, { - kind: "question", - text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}`, + kind: "attention", + text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}\n«Принять» смержит PR.`, }); return { merged: false, reason: "изменение конвейера требует ревью PM" }; } diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 3d66c4e6..ca3e2555 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -5,6 +5,7 @@ import { formatTaskKey } from "@peppa/shared"; import { eq } from "drizzle-orm"; import { startSession, stopSession, type StartOptions } from "./sessions.ts"; import { mergeTaskPr } from "./ci-feedback.ts"; +import { syncWorkspace } from "./workspace-sync.ts"; export type BoardColumn = "backlog" | "in_progress" | "review" | "done"; @@ -61,9 +62,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta /** * "Accept" on a ready-for-review message: the task's PR is merged (green checks, no - * conflicts — otherwise nothing changes and the PM sees why), task done, session stopped. + * conflicts — otherwise nothing changes and the PM sees why; Gitea deletes the branch), + * task done, session stopped, the working copy fast-forwarded to main. */ -export async function acceptTask(db: Db, questionId: number, via: NonNullable): Promise { +export async function acceptTask(db: Db, questionId: number, via: NonNullable, answer = "✅ Принято"): Promise { const q = await getQuestion(db, questionId); if (!q.taskId) throw new PeppaError("Вопрос не привязан к стори"); if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${q.answer}`); @@ -75,8 +77,10 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable {}); return ref; } diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index ba974385..0221ef4f 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -7,6 +7,7 @@ import { appendFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { answerQuestion, + getAutonomy, getQuestion, getReviewSettings, latestReview, @@ -184,6 +185,12 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: return null; } const [task] = s.taskId ? await db.select().from(tasks).where(eq(tasks.id, s.taskId)) : []; + if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto") { + // PEP-25: Peppa merges this PR itself (watchdog); the PM hears only if it can't. + await logSessionEvent(db, s, "awaiting_automerge", { pr: task.prUrl }); + await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); + return null; + } if (task?.status === "review") { // PEP-26: what the reviewer agent said (approved, findings left after the limit, failed). const settings = await getReviewSettings(db, task.projectId); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 783e6467..bd5a52f8 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -21,3 +21,5 @@ export * from "./code.ts"; export * from "./terminal.ts"; export * from "./claude-print.ts"; export * from "./reviewer.ts"; +export * from "./autonomy.ts"; +export * from "./workspace-sync.ts"; diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 7668e4df..f6c73efc 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -1,7 +1,9 @@ import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { + agentAutonomyNote, answerQuestion, + getAutonomy, getSubscription, pickSubscription, createSession, @@ -56,7 +58,9 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider, subscriptionId: sub?.id ?? null }); const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`; await updateSession(db, session.id, { tmuxName }); - const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n"); + // PEP-23: the project's autonomy (PM approves proposals, Peppa merges) goes into the prompt. + const note = agentAutonomyNote(await getAutonomy(db, ref.project.id)); + const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, opts.prompt].filter(Boolean).join("\n\n"); return launch(db, await getSession(db, session.id), cwd, { ...opts, prompt }); } @@ -161,6 +165,13 @@ export async function stopSession(db: Db, sessionId: number): Promise { await logSessionEvent(db, s, "stopped"); } +/** Handlers that consume an answer themselves (true = handled, not typed into a session). */ +export type AnswerHandler = (db: Db, q: Question, answer: string) => Promise; +const answerHandlers: AnswerHandler[] = []; +export function onAnswer(h: AnswerHandler) { + answerHandlers.push(h); +} + 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" }; @@ -193,6 +204,8 @@ export async function answerAndDeliver( message = `Ответ PM на вопрос #${q.id}: ${answer}`; } + // Other answer handlers (PEP-24: "agents are idle" push). + for (const h of answerHandlers) if (await h(db, q, answer)) return { delivered: true, question: q }; // "Deploy to prod" on a "staging updated" message (PEP-57). if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q }; // A task question asked outside a session (red CI, a manual session) goes to the agent @@ -213,7 +226,7 @@ export async function answerAndDeliver( return { delivered: true, question: q }; } -async function resolveTaskById(db: Db, taskId: number) { +export async function resolveTaskById(db: Db, taskId: number) { const [row] = await db .select({ key: projects.key, number: tasks.number }) .from(tasks) diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 7f6616f6..ef2b3164 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -20,6 +20,7 @@ import { monitorTick } from "./monitor.ts"; import { incidentTick } from "./incidents.ts"; import { pollChecks } from "./ci-feedback.ts"; import { reviewTick } from "./reviewer.ts"; +import { autonomyTick } from "./autonomy.ts"; export interface WatchdogOptions { /** Current time (tests move it instead of waiting). */ @@ -51,6 +52,8 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise { log(`session #${s.id}: ${(e as Error).message}`); } } + // Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher. + 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}`)); // Daily digest at each user's time (PEP-29); a no-op outside their window. diff --git a/packages/runner/src/workspace-sync.ts b/packages/runner/src/workspace-sync.ts new file mode 100644 index 00000000..c0c740fb --- /dev/null +++ b/packages/runner/src/workspace-sync.ts @@ -0,0 +1,31 @@ +// PEP-25: after a story is accepted/merged, the project's working copy follows main. +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { listSessions, type TaskRef } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { git } from "./git.ts"; + +/** + * Brings the project's working copy to the merged main: fetch, and — when no agent works + * there, the tree is clean and it is on main or on the story's branch — checkout main, + * fast-forward, delete the merged local story branch. Anything else is left alone. + * `PEPPA_WORKSPACE_SYNC=off` disables it. + */ +export async function syncWorkspace(db: Db, ref: TaskRef): Promise<"synced" | "busy" | "dirty" | "other_branch" | "no_git" | "off"> { + if (process.env.PEPPA_WORKSPACE_SYNC === "off") return "off"; + const dir = ref.project.workspacePath; + if (!existsSync(join(dir, ".git"))) return "no_git"; + if ((await listSessions(db, { active: true })).some((s) => s.projectId === ref.project.id)) return "busy"; + const def = ref.project.defaultBranch; + const branch = (await git(dir, "rev-parse", "--abbrev-ref", "HEAD")).stdout.trim(); + const storyBranch = `task/${ref.key}`.toLowerCase(); + if (branch !== def && !branch.toLowerCase().startsWith(storyBranch)) return "other_branch"; + if ((await git(dir, "status", "--porcelain")).stdout.trim()) return "dirty"; + await git(dir, "fetch", "--prune", "origin"); + if (branch !== def) await git(dir, "checkout", def); + await git(dir, "merge", "--ff-only", `origin/${def}`); + const local = (await git(dir, "branch", "--format=%(refname:short)")).stdout.split("\n").map((b) => b.trim()); + for (const b of local.filter((b) => b.toLowerCase().startsWith(storyBranch))) await git(dir, "branch", "-d", b).catch(() => {}); + return "synced"; +} + diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index 9d19f8e5..6ce62d68 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -141,7 +141,14 @@ function mcpCommand(): string { return process.env.PEPPA_MOCK_MCP_BIN ?? cfg.mcpServers?.peppa?.command ?? "peppa-mcp"; } -async function callMcp(tool: string, toolArgs: Record) { +// "$TASK" in MCP args = the story the runner started this agent on ("Работай над стори KEY-N"), +// so one scenario serves every story of a project (PEP-24 dispatcher tests). +const startTask = /стори ([A-Z][A-Z0-9]*-\d+)/.exec(args.prompt ?? "")?.[1] ?? null; +const withTask = (v: Record) => + Object.fromEntries(Object.entries(v).map(([k, x]) => [k, x === "$TASK" && startTask ? startTask : x])); + +async function callMcp(tool: string, rawArgs: Record) { + const toolArgs = withTask(rawArgs); if (!mcp) { mcp = new Client({ name: `mock-${provider}`, version: "0" }); await mcp.connect(new StdioClientTransport({ command: mcpCommand(), cwd, env: process.env as Record })); diff --git a/packages/testkit/test/autonomy-levels.test.ts b/packages/testkit/test/autonomy-levels.test.ts new file mode 100644 index 00000000..b3fc10eb --- /dev/null +++ b/packages/testkit/test/autonomy-levels.test.ts @@ -0,0 +1,375 @@ +// PEP-23/24/25, spec project-autonomy: levels, dispatcher (no idle without a push), +// auto-merge and closing, working copy after the merge — mock-claude runners, mock Gitea. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; +import { projects } from "@peppa/db"; +import { eq } from "drizzle-orm"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-auto-")), "gitea")); +const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; +const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" }; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +const projectOf = (p: TestProject) => core.getProject(db, p.key); +const taskOf = async (key: string) => (await core.resolveTask(db, key)).task; +const openQuestions = async (projectId: number) => core.pendingQuestions(db, projectId); +const activeOf = async (projectId: number) => (await core.listSessions(db, { active: true })).filter((s) => s.projectId === projectId); +const autonomy = (now = new Date()) => runner.autonomyTick(db, { now }); +/** Settings without quiet hours: tests run at any time of day. */ +const NO_QUIET = { quietFrom: null, quietTo: null } as const; + +describe("autonomy settings", () => { + test("a project without settings is manual; presets and custom combinations; validation", async () => { + const p = await projectOf(await project({ turns: [] })); + const s = await core.getAutonomy(db, p.id); + assert.equal(core.autonomyLevel(s), "manual"); + assert.deepEqual({ pick: s.pick, merge: s.merge, close: s.close, idlePush: s.idlePush }, { pick: "pm", merge: "manual", close: "pm", idlePush: false }); + + const auto = await core.setAutonomy(db, p.id, { level: "auto" }); + assert.equal(core.autonomyLevel(auto), "auto"); + assert.deepEqual({ pick: auto.pick, merge: auto.merge, close: auto.close }, { pick: "auto", merge: "auto", close: "after_merge" }); + const custom = await core.setAutonomy(db, p.id, { proposal: "pm", close: "after_hours", closeAfterHours: 6 }); + assert.equal(core.autonomyLevel(custom), "custom"); + assert.equal(custom.pick, "auto", "fields override the current settings"); + assert.match(core.describeAutonomy(custom), /каждый одобряет PM[\s\S]*через 6 ч/); + await assert.rejects(core.setAutonomy(db, p.id, { wipLimit: 0 }), /wipLimit/); + await assert.rejects(core.setAutonomy(db, p.id, { merge: "yolo" as never }), /merge/); + + await core.setAutonomy(db, p.id, { level: "manual" }); + assert.equal(await core.getSetting(db, `project.autonomy:${p.id}`), null, "manual = no row, as before PEP-23"); + }); + + test("quiet hours wrap over midnight", () => { + const q = { quietFrom: 22, quietTo: 9 }; + assert.equal(core.inQuietHours(q, new Date(2026, 10, 14, 23, 30)), true); + assert.equal(core.inQuietHours(q, new Date(2026, 10, 14, 8, 59)), true); + assert.equal(core.inQuietHours(q, new Date(2026, 10, 14, 12, 0)), false); + assert.equal(core.inQuietHours({ quietFrom: null, quietTo: null }, new Date(2026, 10, 14, 23)), false); + }); +}); + +describe("dispatcher", () => { + test("manual (default): nothing starts by itself and the PM gets no push", async () => { + const tp = await project({ turns: [] }); + const p = await projectOf(tp); + await runner.tick(db, { intervalMs: 0, stallMs: 60_000 }); + assert.equal((await activeOf(p.id)).length, 0); + assert.equal((await openQuestions(p.id)).length, 0); + assert.equal((await taskOf(tp.taskKey)).status, "backlog"); + }); + + test("auto: backlog → work → review → merged → done → next story, without a human; then 'backlog empty' once", async () => { + const tp = await project({ turns: [[{ mcp: "update_task", args: { task: "$TASK", status: "review" } }, { say: "Готово, PR открыт." }]] }); + const p = await projectOf(tp); + const second = await core.createTask(db, { projectId: p.id, title: "вторая стори" }); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + + // The watchdog tick runs the dispatcher: the lowest number first, WIP 1. + await runner.tick(db, { intervalMs: 0, stallMs: 600_000 }); + let active = await activeOf(p.id); + assert.equal(active.length, 1); + assert.equal(active[0]!.taskKey, tp.taskKey); + assert.equal((await taskOf(second.key)).status, "backlog", "WIP limit 1: the second story waits"); + + await waitFor("first story in review", async () => (await taskOf(tp.taskKey)).status === "review"); + await waitFor("agent finished its turn", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input"); + assert.equal((await openQuestions(p.id)).length, 0, "merge=auto: no 'ready for review' for the PM"); + + await autonomy(); + assert.equal((await taskOf(tp.taskKey)).status, "done", "no PR → nothing to merge → closed after merge"); + assert.equal((await core.getSession(db, active[0]!.id)).status, "done", "its agent stopped"); + active = await activeOf(p.id); + assert.equal(active[0]?.taskKey, second.key, "the next story was taken in the same tick"); + + await waitFor("second story in review", async () => (await taskOf(second.key)).status === "review"); + await waitFor("second agent idle", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input"); + await autonomy(); + assert.equal((await taskOf(second.key)).status, "done"); + const empty = (await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")); + assert.equal(empty.length, 1); + await autonomy(); + assert.equal((await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")).length, 1, "told once"); + }); + + test("auto: nothing starts while a runner of the project is rate-limited or its pool is exhausted", async () => { + const tp = await project({ turns: [] }); + const p = await projectOf(tp); + const other = await core.createTask(db, { projectId: p.id, title: "другая" }); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + // A rate-limited runner on another story of the project. + const s = await core.createSession(db, { projectId: p.id, taskId: other.task.id }); + await core.updateSession(db, s.id, { status: "rate_limited", resumeAt: new Date(Date.now() + 3_600_000) }); + await autonomy(); + assert.equal((await taskOf(tp.taskKey)).status, "backlog"); + await core.updateSession(db, s.id, { status: "done" }); + + const sub = await core.createSubscription(db, { provider: "claude", name: `mock-sub-${p.key}`, authKind: "oauth", secret: "mock-token" }); + await core.updateSubscription(db, sub.id, { status: "limited", limitedUntil: new Date(Date.now() + 3_600_000) }); + const pool = await core.createPool(db, { name: `mock-pool-${p.key}`, subscriptionIds: [sub.id] }); + await core.setProjectPool(db, p.id, pool.id); + assert.equal(await core.projectPoolExhausted(db, p.id), true); + await autonomy(); + assert.equal((await taskOf(tp.taskKey)).status, "backlog"); + assert.equal((await openQuestions(p.id)).length, 0, "no push during a limit either"); + }); + + test("auto: a failed start puts the story back, tells the PM once and backs off", async () => { + const tp = await project({ turns: [] }); + const p = await projectOf(tp); + await db.update(projects).set({ workspacePath: "/nonexistent/mock-ws" }).where(eq(projects.id, p.id)); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + const now = new Date(); + await autonomy(now); + assert.equal((await taskOf(tp.taskKey)).status, "backlog"); + const qs = await openQuestions(p.id); + assert.equal(qs.length, 1); + assert.match(qs[0]!.text, /не смог запустить агента/); + await autonomy(new Date(now.getTime() + 60_000)); + assert.equal((await openQuestions(p.id)).length, 1, "no retry storm within the back-off"); + }); + + test("assisted: idle push with buttons — no duplicates; Next offers the next story; Not now snoozes; Take starts", async () => { + const tp = await project({ turns: [[{ say: "работаю" }]] }); + const p = await projectOf(tp); + const second = await core.createTask(db, { projectId: p.id, title: "вторая" }); + await core.setAutonomy(db, p.id, { level: "assisted", ...NO_QUIET }); + + await autonomy(); + let [q] = await openQuestions(p.id); + assert.ok(q, "pushed"); + assert.match(q.text, /агенты простаивают/); + assert.match(q.text, new RegExp(`Взять в работу ${tp.taskKey}`)); + assert.equal(q.options?.length, 3); + await autonomy(); + assert.equal((await openQuestions(p.id)).length, 1, "one open push at a time"); + + await runner.answerAndDeliver(db, q.id, runner.IDLE_NEXT, "telegram"); + [q] = await openQuestions(p.id); + assert.match(q!.text, new RegExp(`Взять в работу ${second.key}`), "Next → the next story right away"); + + await runner.answerAndDeliver(db, q!.id, q!.options![2]!, "telegram"); + assert.equal((await openQuestions(p.id)).length, 0); + await autonomy(); + assert.equal((await openQuestions(p.id)).length, 0, "Not now → quiet for idlePushHours"); + await autonomy(new Date(Date.now() + 5 * 3_600_000)); + [q] = await openQuestions(p.id); + assert.ok(q, "pushed again after the snooze"); + + await runner.answerAndDeliver(db, q.id, q.options![0]!, "web"); + assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "Take → the story is in work"); + const active = await activeOf(p.id); + assert.equal(active.length, 1); + await autonomy(); + assert.equal((await openQuestions(p.id)).filter((x) => x.text.includes("простаивают")).length, 0, "an agent works: no push"); + await runner.stopSession(db, active[0]!.id); + }); + + test("assisted: no push in quiet hours, nor more often than idlePushHours; a manual move closes the push", async () => { + const tp = await project({ turns: [[{ say: "работаю" }]] }); + const p = await projectOf(tp); + await core.setAutonomy(db, p.id, { level: "assisted", quietFrom: 22, quietTo: 9, idlePushHours: 4 }); + await autonomy(new Date(2026, 10, 14, 23, 0)); + assert.equal((await openQuestions(p.id)).length, 0, "quiet hours"); + await autonomy(new Date(2026, 10, 14, 10, 0)); + const [q] = await openQuestions(p.id); + assert.ok(q); + // The PM starts the story from the board instead: the push is moot. + const { started } = await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "in_progress"); + await autonomy(new Date(2026, 10, 14, 10, 1)); + assert.equal((await core.getQuestion(db, q.id)).answeredVia, "system"); + await runner.stopSession(db, started!); + await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "backlog"); + await autonomy(new Date(2026, 10, 14, 11, 0)); + assert.equal((await openQuestions(p.id)).length, 0, "not more often than every 4 h"); + await autonomy(new Date(2026, 10, 14, 14, 1)); + assert.equal((await openQuestions(p.id)).length, 1); + }); +}); + +interface PrTask { + tp: TestProject; + proj: Awaited>; + pr: { number: number }; + push(files?: Record): string; + green(sha: string): void; +} + +/** A story in review with an open PR (task/-1) in mock Gitea. */ +async function prTask(level: Parameters[2]): Promise { + const tp = await project({ turns: [] }); + const proj = await projectOf(tp); + const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS }); + writeFileSync(join(tp.dir, ".peppa/project.json"), pj); + gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); + gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; + let n = 0; + const push = (files: Record = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n), ...files }); + const sha = push(); + const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); + const green = (s: string) => { + for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success"); + }; + green(sha); + await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); + await core.setAutonomy(db, proj.id, { ...level, ...NO_QUIET }); + return { tp, proj, pr, push, green }; +} + +const pull = (t: PrTask) => gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[t.pr.number - 1]!; + +describe("auto-merge and closing", () => { + test("merge=auto, close=after_merge: a green PR is merged and the story closed", async () => { + const t = await prTask({ merge: "auto", close: "after_merge" }); + await autonomy(); + assert.equal(pull(t).merged, true); + assert.equal((await taskOf(t.tp.taskKey)).status, "done"); + }); + + test("merge=auto, close=pm: merged, then 'ready for review' with Accept → done", async () => { + const t = await prTask({ merge: "auto", close: "pm" }); + await autonomy(); + assert.equal(pull(t).merged, true); + assert.equal((await taskOf(t.tp.taskKey)).status, "review"); + const [q] = await openQuestions(t.proj.id); + assert.match(q!.text, /PR смержен автоматически/); + assert.ok(await runner.isReviewQuestion(db, q!)); + await autonomy(); + assert.equal((await openQuestions(t.proj.id)).length, 1, "asked once"); + await runner.acceptTask(db, q!.id, "telegram"); + assert.equal((await taskOf(t.tp.taskKey)).status, "done"); + }); + + test("pending checks: nothing merged yet", async () => { + const t = await prTask({ merge: "auto", close: "after_merge" }); + t.push(); // new head without statuses + await autonomy(); + assert.equal(pull(t).merged, false); + assert.equal((await taskOf(t.tp.taskKey)).status, "review"); + }); + + test("conflicts: the agent is asked to rebase (once per head commit)", async () => { + const t = await prTask({ merge: "auto", close: "after_merge" }); + pull(t).mergeable = false; + await autonomy(); + assert.equal(pull(t).merged, false); + assert.equal((await taskOf(t.tp.taskKey)).status, "in_progress", "back to work"); + const [s] = await activeOf(t.proj.id); + assert.ok(s, "an agent was started for the rebase"); + const ev = await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase")); + assert.match(String(ev.prompt), /force-with-lease/); + await runner.stopSession(db, s!.id); + }); + + test("pipeline change: not merged, the PM gets one review message with Accept", async () => { + const t = await prTask({ merge: "auto", close: "after_merge" }); + t.green(t.push({ ".gitea/workflows/ci.yml": "on: push\n" })); + await autonomy(); + await autonomy(); + assert.equal(pull(t).merged, false); + const qs = (await openQuestions(t.proj.id)).filter((q) => q.text.includes("меняет конвейер")); + assert.equal(qs.length, 1, "asked once per head commit"); + assert.ok(await runner.isReviewQuestion(db, qs[0]!), "with «Принять»"); + await runner.acceptTask(db, qs[0]!.id, "web"); + assert.equal(pull(t).merged, true, "the PM's Accept merges it"); + }); + + test("close=after_hours: 'ready for review' without comments for N hours → accepted (PR merged)", async () => { + const t = await prTask({ close: "after_hours", closeAfterHours: 2 }); + const q = await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" }); + await autonomy(new Date(Date.now() + 3_600_000)); + assert.equal((await taskOf(t.tp.taskKey)).status, "review", "not yet"); + await autonomy(new Date(Date.now() + 2 * 3_600_000 + 60_000)); + assert.equal((await taskOf(t.tp.taskKey)).status, "done"); + assert.equal(pull(t).merged, true); + assert.match((await core.getQuestion(db, q.id)).answer ?? "", /автоматически/); + }); + + test("close=after_hours never accepts a pipeline change by itself", async () => { + const t = await prTask({ close: "after_hours", closeAfterHours: 1 }); + t.green(t.push({ ".gitea/peppa-check.sh": "exit 0\n" })); + await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" }); + await autonomy(new Date(Date.now() + 2 * 3_600_000)); + assert.equal((await taskOf(t.tp.taskKey)).status, "review"); + assert.equal(pull(t).merged, false); + assert.ok((await openQuestions(t.proj.id)).some((q) => q.text.includes("меняет конвейер"))); + }); +}); + +describe("proposal approval and the working copy", () => { + test("proposal=pm: the agent can't start Apply itself; the prompt says to request approval", async () => { + const tp = await project({ + turns: [ + [ + { mcp: "update_task", args: { task: "$TASK", status: "proposing", openspec_change: "x-1" } }, + { mcp: "update_task", args: { task: "$TASK", status: "in_progress" } }, + { mcp: "request_approval", args: { task: "$TASK", summary: "Proposal: сделать X без новых зависимостей" } }, + ], + ], + }); + const p = await projectOf(tp); + await core.setAutonomy(db, p.id, { proposal: "pm" }); + const sid = await tp.start(); + const refused = await tp.waitLog("refused apply", (e) => e.ev === "mcp" && e.tool === "update_task" && e.isError === true); + assert.match(String(refused.text), /approves every proposal/); + assert.ok(tp.log().some((e) => e.ev === "prompt" && String(e.prompt).includes("PM одобряет каждый proposal"))); + const q = await tp.waitQuestion(sid, "approval"); + assert.equal((await taskOf(tp.taskKey)).status, "awaiting_approval"); + await runner.answerAndDeliver(db, q.id, "ок", "web"); + assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "the PM's approval starts Apply"); + await runner.stopSession(db, sid); + }); + + test("syncWorkspace: the working copy on the story branch goes to the merged main; the local branch is deleted", async () => { + const root = mkdtempSync(join(tmpdir(), "peppa-sync-")); + const g = (cwd: string, ...a: string[]) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); + const origin = join(root, "origin.git"); + execFileSync("git", ["init", "--bare", "-b", "main", origin], { stdio: "ignore" }); + const ws = join(root, "ws"); + execFileSync("git", ["clone", origin, ws], { stdio: "ignore" }); + g(ws, "checkout", "-b", "main"); + writeFileSync(join(ws, "a.txt"), "1"); + g(ws, "add", "."); + g(ws, "commit", "-m", "init"); + g(ws, "push", "-u", "origin", "main"); + const tp = await project({ turns: [] }); + const p = await projectOf(tp); + await db.update(projects).set({ workspacePath: ws }).where(eq(projects.id, p.id)); + g(ws, "checkout", "-b", `task/${tp.taskKey}`); + writeFileSync(join(ws, "b.txt"), "2"); + g(ws, "add", "b.txt"); + g(ws, "commit", "-m", "story"); + g(ws, "push", "origin", `task/${tp.taskKey}`); + // The PR is merged on the server: main gets the story's commit. + g(ws, "push", "origin", `task/${tp.taskKey}:main`); + const ref = await core.resolveTask(db, tp.taskKey); + assert.equal(await runner.syncWorkspace(db, ref), "synced"); + assert.equal(g(ws, "rev-parse", "--abbrev-ref", "HEAD"), "main"); + assert.equal(g(ws, "rev-parse", "HEAD"), g(ws, "rev-parse", "origin/main")); + assert.equal(g(ws, "branch", "--list", `task/${tp.taskKey}`), "", "merged local branch deleted"); + + // Another branch or uncommitted changes: left alone. + g(ws, "checkout", "-b", "feature/other"); + assert.equal(await runner.syncWorkspace(db, ref), "other_branch"); + g(ws, "checkout", "main"); + writeFileSync(join(ws, "a.txt"), "dirty"); + assert.equal(await runner.syncWorkspace(db, ref), "dirty"); + }); +}); + diff --git a/template/RULES.md b/template/RULES.md index 664746c9..2b8052d8 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -64,7 +64,18 @@ PM отвечает только на **архитектурные стоппе - Запушь ветку и открой PR в Gitea (ссылка на стори и резюме change). - `peppa.update_task` → `status: review`, `pr_url: …` и закончи ход. PM получит «готово к ревью»: кнопка «Принять» закрывает стори, текстом — замечания, их доделываешь. -- Статус `done` ставит только PM. +- Статус `done` ставит только PM (или Пеппа по настройкам автономности проекта). + +### Автономность проекта +- У проекта есть настройки автономности (PM меняет их в вебе). Что касается тебя, Пеппа + добавляет в стартовый промпт и в `get_task` (раздел «Автономность проекта»): + - «PM одобряет каждый proposal» — после proposal `request_approval` и конец хода; + `update_task(status: in_progress)` из proposing в таком проекте отклоняется. + - «PR мержит Пеппа» — не мержи PR сам; после зелёных проверок Пеппа смержит его и закроет + стори. Попросит rebase из-за конфликтов — rebase на свежую основную ветку, проверки, + `git push --force-with-lease` в ту же ветку, снова `status: review`. +- Стори может взять в работу сама Пеппа («Стори взята из бэклога автоматически») — работай + как обычно. ## CI: проверки перед PR -- 2.45.2 From 7d1e354096e5867847f8f26c6418bab268fca6c5 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 04:46:28 +0500 Subject: [PATCH 002/472] PEP-23: archive OpenSpec change pep-23-autonomy (spec project-autonomy) Co-Authored-By: Claude Opus 5.5 --- .../2026-11-14-pep-23-autonomy}/design.md | 0 .../2026-11-14-pep-23-autonomy}/proposal.md | 0 .../specs/project-autonomy/spec.md | 0 .../2026-11-14-pep-23-autonomy}/tasks.md | 0 openspec/specs/project-autonomy/spec.md | 94 +++++++++++++++++++ 5 files changed, 94 insertions(+) rename openspec/changes/{pep-23-autonomy => archive/2026-11-14-pep-23-autonomy}/design.md (100%) rename openspec/changes/{pep-23-autonomy => archive/2026-11-14-pep-23-autonomy}/proposal.md (100%) rename openspec/changes/{pep-23-autonomy => archive/2026-11-14-pep-23-autonomy}/specs/project-autonomy/spec.md (100%) rename openspec/changes/{pep-23-autonomy => archive/2026-11-14-pep-23-autonomy}/tasks.md (100%) create mode 100644 openspec/specs/project-autonomy/spec.md diff --git a/openspec/changes/pep-23-autonomy/design.md b/openspec/changes/archive/2026-11-14-pep-23-autonomy/design.md similarity index 100% rename from openspec/changes/pep-23-autonomy/design.md rename to openspec/changes/archive/2026-11-14-pep-23-autonomy/design.md diff --git a/openspec/changes/pep-23-autonomy/proposal.md b/openspec/changes/archive/2026-11-14-pep-23-autonomy/proposal.md similarity index 100% rename from openspec/changes/pep-23-autonomy/proposal.md rename to openspec/changes/archive/2026-11-14-pep-23-autonomy/proposal.md diff --git a/openspec/changes/pep-23-autonomy/specs/project-autonomy/spec.md b/openspec/changes/archive/2026-11-14-pep-23-autonomy/specs/project-autonomy/spec.md similarity index 100% rename from openspec/changes/pep-23-autonomy/specs/project-autonomy/spec.md rename to openspec/changes/archive/2026-11-14-pep-23-autonomy/specs/project-autonomy/spec.md diff --git a/openspec/changes/pep-23-autonomy/tasks.md b/openspec/changes/archive/2026-11-14-pep-23-autonomy/tasks.md similarity index 100% rename from openspec/changes/pep-23-autonomy/tasks.md rename to openspec/changes/archive/2026-11-14-pep-23-autonomy/tasks.md diff --git a/openspec/specs/project-autonomy/spec.md b/openspec/specs/project-autonomy/spec.md new file mode 100644 index 00000000..313ec266 --- /dev/null +++ b/openspec/specs/project-autonomy/spec.md @@ -0,0 +1,94 @@ +# project-autonomy Specification + +## Purpose +TBD - created by archiving change pep-23-autonomy. Update Purpose after archive. + +## Requirements + +### Requirement: Уровни автономности проекта +У каждого проекта SHALL быть настройки автономности: кто берёт стори из бэклога (PM или +Пеппа, WIP-лимит), нужно ли одобрение PM каждого proposal, мерж PR (по «Принять» или +автоматически), закрытие стори (PM, сразу после мержа, само через N часов без замечаний) и +пуш при простое (частота, тихие часы). Уровни «Ручной», «С подсказками», «Автомат» задают +наборы этих настроек; другая комбинация — «Свой». Проект без настроек SHALL вести себя как +«Ручной» — так же, как до появления настроек. Настройки меняют владелец и участники в вебе, +через MCP `update_project_settings` и CLI. + +#### Scenario: Проект без настроек +- **WHEN** у проекта никогда не меняли автономность и в бэклоге есть стори +- **THEN** ничего не запускается само и PM не получает пушей + +#### Scenario: Уровень и отдельная настройка +- **WHEN** PM выбирает «Автомат», затем включает одобрение каждого proposal +- **THEN** уровень показывается как «Свой», остальные настройки «Автомата» сохраняются + +### Requirement: Одобрение каждого proposal +Если в проекте PM одобряет каждый proposal, агент SHALL получить это в стартовом промпте и +в `get_task`, а MCP SHALL отклонить переход стори агентом из `backlog`/`proposing` в +`in_progress`; стори переходит в `in_progress` одобрением PM. + +#### Scenario: Агент пытается начать Apply сам +- **WHEN** агент после proposal вызывает `update_task(status: in_progress)` +- **THEN** вызов отклонён с указанием запросить одобрение; после `request_approval` и ответа «ок» стори в `in_progress` + +### Requirement: Диспетчер бэклога +Вачдог SHALL для проектов, где стори берёт Пеппа, запускать агентов на следующие стори +бэклога (наименьший номер), пока число работающих агентов проекта меньше WIP-лимита. +Работающий агент — активная сессия стори в `proposing`, `awaiting_approval`, `in_progress` +или `blocked`. Во время лимита (раннер проекта `rate_limited` или пул подписок проекта без +пригодных подписок) диспетчер SHALL ничего не запускать. Неудачный запуск SHALL вернуть +стори в бэклог, сообщить PM один раз и не повторять попытку 30 минут. + +#### Scenario: Автомат проходит бэклог без человека +- **WHEN** проект в «Автомате», в бэклоге две стори, агент доводит первую до ревью +- **THEN** первая мержится и закрывается, и в том же тике вачдога агент берёт вторую + +#### Scenario: Лимит +- **WHEN** раннер проекта упёрся в лимит подписки +- **THEN** новые стори не запускаются и PM не получает пуш о простое + +### Requirement: Пуш при простое +Если стори берёт PM, пуш включён, ни один агент проекта не работает, а в бэклоге есть стори, +PM SHALL получить один вопрос «Агенты простаивают. Взять в работу KEY?» с вариантами +«Взять», «Следующую», «Не сейчас» — не чаще раза в N часов, не в тихие часы и не во время +лимита. «Взять» запускает агента, «Следующую» сразу предлагает следующую стори, «Не сейчас» +выключает пуши на N часов. Если агент заработал или бэклог опустел, открытый вопрос +закрывается сам. + +#### Scenario: Простой +- **WHEN** в проекте «С подсказками» нет работающих агентов, в бэклоге PEP-7 +- **THEN** PM получает один вопрос с кнопками; повторный тик вачдога второго не создаёт + +#### Scenario: Тихие часы +- **WHEN** условия простоя наступили в 23:00 при тихих часах 22–9 +- **THEN** пуш уходит не раньше 9:00 + +### Requirement: Приёмка мержит PR и обновляет рабочую копию +«Принять» SHALL мержить PR стори (зелёные проверки, без конфликтов), Gitea удаляет ветку, а +рабочая копия проекта SHALL подтянуть основную ветку — только если в проекте нет активных +сессий, дерево чистое и копия на основной ветке или на ветке этой стори; иначе копия не +трогается. + +#### Scenario: Копия на ветке стори +- **WHEN** PR стори смержен, рабочая копия чистая и на ветке `task/KEY-N` +- **THEN** копия переключается на основную ветку, догоняет её, локальная ветка стори удаляется + +### Requirement: Автомерж и автозакрытие +При «мерж авто» Пеппа SHALL мержить PR стори в ревью после зелёных проверок головного +коммита и без конфликтов; хук не шлёт PM «готово к ревью». При конфликте агент SHALL +получить просьбу сделать rebase (один раз на головной коммит). PR, меняющий конвейер, SHALL +не мержиться и не закрываться автоматически: PM получает одно сообщение ревью с кнопкой +«Принять». После мержа стори закрывается по настройке: сразу, по «Принять» PM или сама +через N часов без замечаний. + +#### Scenario: Зелёный PR +- **WHEN** стори в ревью, проверки PR зелёные, конфликтов нет, закрытие «сразу после мержа» +- **THEN** PR смержен, стори в «Готово», её раннер остановлен + +#### Scenario: Конфликт +- **WHEN** PR стори конфликтует с основной веткой +- **THEN** стори возвращается в работу, агент получает просьбу о rebase + +#### Scenario: Закрытие по времени +- **WHEN** закрытие «через 2 часа», сообщение ревью без ответа 2 часа +- **THEN** стори принимается автоматически (PR мержится), ответ — «Принято автоматически» -- 2.45.2 From 5465238d1a62fd782b0064eb6b76fdd8a928ceea 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 04:49:22 +0500 Subject: [PATCH 003/472] PEP-23: MCP tool list and update_project_settings in the remote MCP test Co-Authored-By: Claude Opus 5.5 --- packages/testkit/test/oauth.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 938844f5..60641496 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -99,7 +99,7 @@ describe("PM tools over MCP", () => { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); @@ -124,6 +124,11 @@ describe("PM tools over MCP", () => { assert.ok((await s.call("answer_question", { question_id: q.id, answer: "x" })).isError); assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/); + // PEP-23: autonomy settings of the project; strangers can't touch them. + assert.match((await call("get_project_settings", { project: p.key })).text, /Уровень: Ручной/); + assert.match((await call("update_project_settings", { project: p.key, level: "auto", proposal: "pm" })).text, /Уровень: Свой[\s\S]*каждый одобряет PM/); + assert.ok((await s.call("update_project_settings", { project: p.key, level: "manual" })).isError); + await call("update_project_settings", { project: p.key, level: "manual" }); }); }); -- 2.45.2 From 4c001ba5f64aa5cf42d077b0bf10e359da8499c9 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 05:25:52 +0500 Subject: [PATCH 004/472] PEP-23: inAutonomyQuietHours (PEP-29 owns inQuietHours for user notification prefs) Co-Authored-By: Claude Opus 5.5 --- packages/core/src/autonomy.ts | 2 +- packages/runner/src/autonomy.ts | 4 ++-- packages/testkit/test/autonomy-levels.test.ts | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/core/src/autonomy.ts b/packages/core/src/autonomy.ts index 83f62cf2..48427d8a 100644 --- a/packages/core/src/autonomy.ts +++ b/packages/core/src/autonomy.ts @@ -131,7 +131,7 @@ export async function setAutonomy(db: Db, projectId: number, patch: AutonomyPatc } /** True inside the quiet hours (local time of the machine Peppa runs on). */ -export function inQuietHours(s: Pick, now: Date): boolean { +export function inAutonomyQuietHours(s: Pick, now: Date): boolean { if (s.quietFrom == null || s.quietTo == null || s.quietFrom === s.quietTo) return false; const h = now.getHours(); return s.quietFrom < s.quietTo ? h >= s.quietFrom && h < s.quietTo : h >= s.quietFrom || h < s.quietTo; diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index f964e17f..af6f7ed8 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -11,7 +11,7 @@ import { getAutonomy, getSetting, giteaForBot, - inQuietHours, + inAutonomyQuietHours, listProjects, listSessions, listTasks, @@ -269,7 +269,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date } if (!a.idlePush || working.length > 0 || !backlog.length || limited || state.questionId) return; - if (inQuietHours(a, now)) return; + if (inAutonomyQuietHours(a, now)) return; if ((state.snoozeUntil ?? 0) > now.getTime()) return; if (state.at && now.getTime() - state.at < a.idlePushHours * 3_600_000) return; await offerStory(db, project, backlog[0]!, now); diff --git a/packages/testkit/test/autonomy-levels.test.ts b/packages/testkit/test/autonomy-levels.test.ts index b3fc10eb..3c9afa09 100644 --- a/packages/testkit/test/autonomy-levels.test.ts +++ b/packages/testkit/test/autonomy-levels.test.ts @@ -58,10 +58,10 @@ describe("autonomy settings", () => { test("quiet hours wrap over midnight", () => { const q = { quietFrom: 22, quietTo: 9 }; - assert.equal(core.inQuietHours(q, new Date(2026, 10, 14, 23, 30)), true); - assert.equal(core.inQuietHours(q, new Date(2026, 10, 14, 8, 59)), true); - assert.equal(core.inQuietHours(q, new Date(2026, 10, 14, 12, 0)), false); - assert.equal(core.inQuietHours({ quietFrom: null, quietTo: null }, new Date(2026, 10, 14, 23)), false); + assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 23, 30)), true); + assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 8, 59)), true); + assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 12, 0)), false); + assert.equal(core.inAutonomyQuietHours({ quietFrom: null, quietTo: null }, new Date(2026, 10, 14, 23)), false); }); }); -- 2.45.2 From c7283063c91643e68f0de184b047c5f0fcf5969c 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 04:43:53 +0500 Subject: [PATCH 005/472] PEP-39: rotate a limited session to a free subscription of the pool at the turn boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Limit marks the subscription «лимит до …»; the watchdog relaunches the session on another usable subscription of the same provider (Claude/OpenCode resume the conversation, Codex starts afresh), threshold banner switches after the turn, max 3 switches/hour, simple fairness between projects, subscription_switched events + Telegram message, web shows subscription and switch history. Migration 0004 (sessions.rotate_reason). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- apps/web/app/(app)/help/page.tsx | 2 +- apps/web/app/(app)/subscriptions/page.tsx | 7 +- apps/web/app/(app)/t/[key]/page.tsx | 3 +- apps/web/components/RunnerConsole.tsx | 48 +- apps/web/components/cards.tsx | 4 +- openspec/changes/pep-39-rotation/design.md | 89 + openspec/changes/pep-39-rotation/proposal.md | 45 + .../specs/agent-credentials/spec.md | 20 + .../specs/subscription-rotation/spec.md | 63 + .../specs/web-workspace/spec.md | 13 + openspec/changes/pep-39-rotation/tasks.md | 17 + packages/core/src/notifications.ts | 22 + packages/core/src/sessions.ts | 13 +- packages/core/src/subscriptions.ts | 123 +- packages/core/src/telegram.ts | 1 + packages/db/migrations/0006_rotation.sql | 1 + .../db/migrations/meta/0006_snapshot.json | 2974 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 2 + packages/runner/src/hook.ts | 10 +- packages/runner/src/index.ts | 1 + packages/runner/src/limits.ts | 13 +- packages/runner/src/rotation.ts | 113 + packages/runner/src/sessions.ts | 2 +- packages/runner/src/watchdog.ts | 62 +- packages/testkit/src/mock-agent.ts | 20 +- packages/testkit/src/scenario.ts | 5 +- packages/testkit/test/limits.test.ts | 2 +- packages/testkit/test/rotation.test.ts | 228 ++ 30 files changed, 3866 insertions(+), 46 deletions(-) create mode 100644 openspec/changes/pep-39-rotation/design.md create mode 100644 openspec/changes/pep-39-rotation/proposal.md create mode 100644 openspec/changes/pep-39-rotation/specs/agent-credentials/spec.md create mode 100644 openspec/changes/pep-39-rotation/specs/subscription-rotation/spec.md create mode 100644 openspec/changes/pep-39-rotation/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-39-rotation/tasks.md create mode 100644 packages/db/migrations/0006_rotation.sql create mode 100644 packages/db/migrations/meta/0006_snapshot.json create mode 100644 packages/runner/src/rotation.ts create mode 100644 packages/testkit/test/rotation.test.ts diff --git a/AGENTS.md b/AGENTS.md index 2452db23..d1e75f7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,7 @@ - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `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/` - **Локальные пользователи (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-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). Провайдер 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-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-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`) diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 403c56f6..da9ae610 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -69,7 +69,7 @@ export default async function Help() {
  • ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите (Gitea, eGov или логин и пароль) и нажмите «Разрешить». В чате включите коннектор Peppa.
  • Codex, Claude и другие MCP-клиенты: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.
  • Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в Настройках.
  • -
  • Подписки — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой.
  • +
  • Подписки — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; свободных нет — ждёт сброса и продолжает сам.
  • diff --git a/apps/web/app/(app)/subscriptions/page.tsx b/apps/web/app/(app)/subscriptions/page.tsx index d87bd4be..3bc65279 100644 --- a/apps/web/app/(app)/subscriptions/page.tsx +++ b/apps/web/app/(app)/subscriptions/page.tsx @@ -82,7 +82,10 @@ function SubscriptionCard({ s, login, pools }: { s: SubscriptionView; login: Pen {PROVIDER_NAMES[s.provider]} {s.name} - сессий сейчас: {s.activeSessions} + + сессий сейчас: {s.activeSessions} + {s.projectSessions.length > 0 && <> ({s.projectSessions.map((p) => `${p.key}${p.n > 1 ? ` ×${p.n}` : ""}`).join(", ")})} +
    {s.authKind === "api_key" ? `API-ключ${s.keyProvider ? ` ${s.keyProvider}` : ""}` : s.authKind === "device" ? "вход ChatGPT" : "токен Claude"} @@ -176,7 +179,7 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
    Подписки}> - Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт первую свободную активную подписку из пула проекта или из выбранных при запуске. Раздел видят только суперадмины. + Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт свободную активную подписку из пула проекта или из выбранных при запуске, а при лимите переключается на другую свободную подписку пула. Раздел видят только суперадмины. {addedSub && Подписка «{addedSub.name}» добавлена{addedSub.status === "active" ? " и активна" : ""}} diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index 9c208264..8be73a92 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -5,6 +5,7 @@ import { FINISHED_SESSION_STATUSES, getEpic, isSuperadmin, latestReview, listPoo import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Hidden, QuestionCard, SessionCard } from "@/components/cards"; +import { eventLine } from "@/components/RunnerConsole"; import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common"; import { Button } from "@/components/ui/button"; import { Input, NativeSelect } from "@/components/ui/input"; @@ -87,7 +88,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom {events.map((e) => (
  • {ago(e.createdAt)} {e.type}{" "} - {e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""} + {eventLine(e)}
  • ))} diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx index b6f582cc..2f01b341 100644 --- a/apps/web/components/RunnerConsole.tsx +++ b/apps/web/components/RunnerConsole.tsx @@ -24,6 +24,27 @@ export function LimitNote({ s }: { s: SessionView }) { ); } +interface SwitchPayload { + fromName?: string | null; + toName?: string | null; + reason?: "limit" | "threshold"; + carried?: "resume" | "fresh"; +} + +/** «Claude A → Claude B · лимит · разговор продолжен» for a subscription_switched event (PEP-39). */ +export function switchText(payload: unknown): string { + const p = (payload ?? {}) as SwitchPayload; + return `${p.fromName ?? "?"} → ${p.toName ?? "?"} · ${p.reason === "threshold" ? "порог использования" : "лимит"} · ${p.carried === "fresh" ? "запуск заново" : "разговор продолжен"}`; +} + +/** One line of a session's event log: type + the human part for known types. */ +export function eventLine(e: { type: string; payload: unknown }): string { + if (e.type === "progress") return (e.payload as { text: string }).text; + if (e.type === "subscription_switched") return switchText(e.payload); + if (e.type === "task_updated") return JSON.stringify((e.payload as { to: unknown }).to); + return ""; +} + /** `selected`: "wide" — picked by default, highlighted only where the side panel is visible. */ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) { const limited = s.status === "rate_limited"; @@ -58,7 +79,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href )} - {s.projectKey} · {s.provider}{s.subscriptionName ? ` · ${s.subscriptionName}` : ""} · #{s.id} · {s.tmuxName} + {s.projectKey} · {s.provider}{s.subscriptionName ? ` · ${s.subscriptionName}` : ""}{s.subscriptionSwitches > 0 ? ` (↻${s.subscriptionSwitches})` : ""} · #{s.id} · {s.tmuxName} {ago(s.lastActivityAt)} {limited && ( @@ -94,8 +115,12 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }: авто-продолжений сегодня: {s.limitResumes} из {MAX_LIMIT_RESUMES_PER_DAY} + {s.rotateReason === "limit" && переключается на свободную подписку пула…}

    )} + {s.rotateReason === "threshold" && ( +

    Подписка подходит к лимиту — после этого хода переключится на свободную.

    + )}
    @@ -106,7 +131,10 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }:
    Агент
    {PROVIDER_NAMES[s.provider]} · поколение {s.generation}
    Подписка
    -
    {s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
    +
    + {s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")} + {s.subscriptionSwitches > 0 && · переключений {s.subscriptionSwitches}} +
    Запущен
    {ago(s.startedAt)}
    Активность
    @@ -135,13 +163,27 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }: )} + {events.some((e) => e.type === "subscription_switched") && ( + +
      + {events + .filter((e) => e.type === "subscription_switched") + .map((e) => ( +
    1. + {ago(e.createdAt)} {switchText(e.payload)} +
    2. + ))} +
    +
    + )} + {events.length > 0 && (
      {events.map((e) => (
    1. {ago(e.createdAt)} {e.type}{" "} - {e.type === "progress" ? (e.payload as { text: string }).text : ""} + {eventLine(e)}
    2. ))}
    diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index efabdcab..67a0ae6a 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -125,7 +125,9 @@ export function SessionCard({ s, back, showTitle = false, terminal = false }: { {s.taskKey ? {s.taskKey} : {s.projectKey}} {showTitle && s.taskTitle && {s.taskTitle}} - #{s.id} · {s.provider} · пок. {s.generation} · {ago(s.lastActivityAt)} + #{s.id} · {s.provider} + {s.subscriptionName && <> · {s.subscriptionName}} + {s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}} · пок. {s.generation} · {ago(s.lastActivityAt)} diff --git a/openspec/changes/pep-39-rotation/design.md b/openspec/changes/pep-39-rotation/design.md new file mode 100644 index 00000000..f8abe33d --- /dev/null +++ b/openspec/changes/pep-39-rotation/design.md @@ -0,0 +1,89 @@ +# Design: PEP-39 — ротация по пулу подписок + +## Где решается + +Всё решает вачдог (`tick`), хуки только ставят флаги. Так переключение происходит в одном +месте, на одном процессе, и его можно гонять в тестах через `tick(db, { now })`. + +- `recordLimit` (хук StopFailure / баннер в вачдоге) как раньше считает `resume_at`, а ещё + помечает подписку сессии `limited` до времени сброса (неизвестно — до `now + проба`). + Если ротация возможна (есть кандидат и бюджет), ставит `sessions.rotate_reason = 'limit'` + и не шлёт PM «остановлен по лимиту» — вместо него придёт «переключил». +- Порог: вачдог видит на экране предупреждение (`approaching usage limit`, `N% of your … + limit`, N ≥ 85) → `rotate_reason = 'threshold'`, событие `usage_threshold`. Stop-хук + при `rotate_reason` не делает авто-подталкивание и не шлёт «закончила ход» — ход + заканчивается, статус `idle`. +- Вачдог, сессия `rate_limited`: + 1. `rotate_reason` есть, или подписка сессии сейчас непригодна и `resume_at` задан → ищем + кандидата; нашли и бюджет есть → `rotateSession`. Не нашли при `rotate_reason` → + флаг снимаем и сообщаем PM «свободных подписок нет, продолжит в HH:MM сам». + 2. Иначе как PEP-56: после `resume_at` — продолжить. + `resume_at = null` (дневной предел PEP-56 исчерпан, нужен человек) — не ротируем. +- Вачдог, `rotate_reason = 'threshold'` и статус `idle`/`waiting_input` без открытых + вопросов, требующих ответа (question/permission/approval) → граница хода → ротация на + подписку без сессий; нет такой — флаг снимаем, работаем дальше. + +## Граница хода + +Переключение = убить tmux и запустить новое поколение. Делаем это только когда ход уже +закончен: после StopFailure (ход оборван лимитом), при баннере лимита (агент стоит), после +Stop/notify (порог). Посреди хода не трогаем — никакого «ретрая вслепую». + +## Кандидаты + +Набор подписок для ротации: пул проекта; если у проекта пула нет (сессия запущена на +отмеченных подписках) — пулы, в которые входит текущая подписка сессии. Без пула и без +подписки (вход машины) ротации нет. Кандидат: тот же провайдер, не текущая подписка, +`isUsable` (активна или лимит уже сброшен), с учётом справедливости; из них — наименее +занятая (по числу активных сессий), при равенстве — меньший id. Для порога — только +подписки без активных сессий. + +## Справедливость (простая) + +Очередь пула = есть активная сессия другого проекта с этим же пулом в статусе +`rate_limited` (ждёт сброса). Если проект уже занимает ≥ K (`PEPPA_POOL_PROJECT_MAX`, 2) +разных подписок пула и очередь есть, свободные (без сессий) подписки ему не отдаются: +- новая сессия делит наименее занятую из уже занятых (раннер не ждёт), а если таких нет + среди пригодных — берёт свободную (лучше, чем отказ); +- ротация такому проекту не достаётся — сессия ждёт сброса, свободная подписка остаётся + ждущему проекту, вачдог переключит его на ближайшем тике. +Без квот, весов и приоритетов — это следующий шаг вместе с расходом по проектам (PEP-43). + +## Предохранители + +- Бюджет: число событий `subscription_switched` сессии за последний час + < `PEPPA_ROTATE_MAX_PER_HOUR` (3). Исчерпан — ждём сброса как PEP-56. +- Лимитная подписка помечена до сброса — на неё не вернёмся раньше времени; если новая + подписка тут же упирается в лимит, она тоже помечается, и следующий шаг — следующая + пригодная или ожидание. +- `PEPPA_ROTATE=off` или `PEPPA_LIMIT_AUTORESUME=off` — ротации нет. + +## Перенос разговора + +- Claude Code: транскрипт лежит локально (`~/.claude/projects`), вход подписки — только + `CLAUDE_CODE_OAUTH_TOKEN`, поэтому `claude --resume ` на другой подписке продолжает + тот же разговор. +- OpenCode: сессии локальные, ключ — env; `--session `. +- Codex: история треда хранится в `CODEX_HOME` аккаунта (у каждой подписки свой), между + аккаунтами не переносится. Ротация Codex = новый запуск без resume (`conversation_id` + сбрасывается) с подсказкой восстановить контекст из `peppa.get_task`, tasks.md и + `git log`/`git diff` рабочей копии. + +## История и сообщения + +- Событие `subscription_switched` {fromId, fromName, toId, toName, reason, carried: + 'resume'|'fresh', limitedUntil}. Отсюда история в «Раннерах», число переключений в + `SessionView.subscriptionSwitches` (подзапрос), события стори. +- PM — сообщение в Telegram всем получателям вопросов проекта (outbox, дедуп по сессии и + поколению), без кнопок и без «ждёт тебя»: решать нечего. Открытые вопросы сессии + закрываются как при resume. + +## Схема + +`sessions.rotate_reason text null` ('limit' | 'threshold'). Остальное — существующие +`subscriptions.status/limited_until` и `events`. + +## Что не делаем + +Реальный процент использования подписки из API (его нет у CLI) — только баннеры CLI; +квоты и приоритеты проектов; перенос треда Codex. diff --git a/openspec/changes/pep-39-rotation/proposal.md b/openspec/changes/pep-39-rotation/proposal.md new file mode 100644 index 00000000..0e56da20 --- /dev/null +++ b/openspec/changes/pep-39-rotation/proposal.md @@ -0,0 +1,45 @@ +# Proposal: PEP-39 — ротация сессии по пулу подписок при лимите + +Задача Пеппы: **PEP-39** (второй этап после PEP-67). + +## Why + +Подписки и пулы уже есть (PEP-67), но раннер, упёршийся в лимит, просто стоит до сброса +(PEP-56), хотя в пуле могут быть свободные подписки. Решение PM (2026-11-13): общий пул +аккаунтов платформы, ротация при лимите по пулу; опыт Cowork — переключать только на +границе хода, не ретраить вслепую, Codex между аккаунтами не переносится. + +## What Changes + +- **Лимит помечает подписку**: StopFailure `rate_limit` или баннер лимита — подписка сессии + получает статус «лимит до <время сброса>» (неизвестно — до пробы PEP-56). На неё не + запускаются новые сессии и на неё не переключаются, пока лимит не сброшен. +- **Ротация**: если в пуле есть другая свободная подписка того же провайдера, вачдог на + ближайшем тике (ход уже оборван лимитом — граница хода) перезапускает сессию на ней: + Claude/OpenCode — продолжение того же разговора (`--resume` / `--session`), Codex — + новый запуск с контекстом из стори (история Codex живёт в `CODEX_HOME` аккаунта и между + аккаунтами не переносится). Свободных нет — как раньше: ждать сброса и продолжать самому; + если подписка в пуле освободится раньше, вачдог переключит на неё. +- **Порог использования**: баннер «approaching usage limit» / «N% of your limit» (N ≥ + `PEPPA_ROTATE_THRESHOLD_PCT`, 85) — сессия помечается «переключить на границе хода»: + Stop-хук не подталкивает её дальше, а после конца хода вачдог переключает её на + полностью свободную подписку пула. Нет такой — работает дальше до настоящего лимита. +- **Предохранители**: не больше `PEPPA_ROTATE_MAX_PER_HOUR` (3) переключений в час на + сессию; ротация только на подписку, которая сейчас пригодна (не «лимит», не «ошибка + входа»); `PEPPA_ROTATE=off` и `PEPPA_LIMIT_AUTORESUME=off` выключают ротацию. +- **Справедливость**: проект, который уже занимает ≥ `PEPPA_POOL_PROJECT_MAX` (2) + подписок пула, не получает ещё одну свободную, пока в этом пуле есть очередь — сессия + другого проекта ждёт сброса лимита. Новая сессия такого проекта делит уже занятую. +- **PM и история**: событие сессии `subscription_switched` (с какой, на какую, почему, + продолжен ли разговор) и сообщение в Telegram «🔁 PEP-42: переключил с подписки A на B». +- **Веб**: «Раннеры» — подписка, «переключится на границе хода», история переключений; + карточка сессии на странице стори — подписка и число переключений; «Подписки» — сессии + по проектам и статус лимита. + +## Impact + +- Схема: `sessions.rotate_reason` (миграция 0004). +- `packages/core` (subscriptions: пометка лимита, выбор для ротации, справедливость; + sessions: число переключений), `packages/runner` (rotation.ts, limits, watchdog, hook), + веб (RunnerConsole, SessionCard, Подписки, события стори), `packages/testkit` + (mock-agent: лимит только на определённом входе; тесты rotation.test.ts). diff --git a/openspec/changes/pep-39-rotation/specs/agent-credentials/spec.md b/openspec/changes/pep-39-rotation/specs/agent-credentials/spec.md new file mode 100644 index 00000000..9474a161 --- /dev/null +++ b/openspec/changes/pep-39-rotation/specs/agent-credentials/spec.md @@ -0,0 +1,20 @@ +# Spec Delta: agent-credentials + +## MODIFIED Requirements + +### Requirement: Подписка сессии +Раннер SHALL при старте брать свободную активную подписку из выбранного набора +(отмеченные подписки или пул из формы запуска, иначе пул проекта) и запоминать её у сессии; +провайдер сессии — провайдер подписки, процесс агента получает вход этой подписки. Resume +SHALL идти на той же подписке, а при лимите сессия может переключиться на другую подписку +пула (ротация). Без пула и выбора сессия запускается на входе машины. + +#### Scenario: Свободная подписка +- **GIVEN** в пуле проекта подписки «A» и «B», на «A» уже работает сессия +- **WHEN** запускается новый раннер проекта +- **THEN** он стартует на подписке «B» + +#### Scenario: Нет активных подписок +- **GIVEN** у всех подписок пула проекта статус «ошибка входа» +- **WHEN** запускается новый раннер +- **THEN** запуск отклонён с сообщением «Нет активных подписок» diff --git a/openspec/changes/pep-39-rotation/specs/subscription-rotation/spec.md b/openspec/changes/pep-39-rotation/specs/subscription-rotation/spec.md new file mode 100644 index 00000000..1b650906 --- /dev/null +++ b/openspec/changes/pep-39-rotation/specs/subscription-rotation/spec.md @@ -0,0 +1,63 @@ +# Spec Delta: subscription-rotation + +## ADDED Requirements + +### Requirement: Лимит помечает подписку +Когда сессия упирается в лимит (StopFailure `rate_limit` или баннер лимита), её подписка +SHALL получать статус «лимит до <время сброса>». Новые сессии и переключения SHALL не +попадать на подписку, пока её лимит не сброшен. + +#### Scenario: Лимит на подписке +- **GIVEN** раннер стори работает на подписке «Claude A» +- **WHEN** Claude сообщает о лимите со временем сброса 17:00 +- **THEN** «Claude A» в «Подписках» показывает «лимит до 17:00», и новый раннер проекта стартует не на ней + +### Requirement: Переключение на свободную подписку пула +Сессия, упёршаяся в лимит, SHALL перезапускаться на другой пригодной подписке того же +провайдера из пула на границе хода: Claude и OpenCode — с продолжением того же разговора, +Codex — новым запуском с подсказкой восстановить контекст из стори (история Codex между +аккаунтами не переносится). Если свободных подписок нет, сессия SHALL ждать сброса и +продолжать сама (как без ротации), а если подписка освободится раньше — переключаться на неё. + +#### Scenario: Есть свободная подписка +- **GIVEN** в пуле проекта подписки Claude «A» и «B», раннер работает на «A» +- **WHEN** на «A» случается лимит +- **THEN** раннер продолжает тот же разговор на «B», PM получает «переключил с подписки A на B» + +#### Scenario: Свободных подписок нет +- **GIVEN** в пуле проекта только подписка «A», раннер на ней упёрся в лимит до 17:00 +- **WHEN** вачдог проверяет раннер +- **THEN** раннер стоит до сброса и продолжает сам после 17:01 + +#### Scenario: Codex +- **GIVEN** в пуле две подписки Codex, раннер Codex упёрся в лимит на первой +- **WHEN** вачдог переключает раннер +- **THEN** он запускается на второй подписке новым запуском без resume, с подсказкой восстановить контекст из стори + +### Requirement: Переключение по порогу использования +Когда CLI предупреждает, что использование подписки подходит к лимиту (не ниже порога, 85 %), +сессия SHALL дожить до конца хода и затем переключиться на подписку пула без сессий; если +такой нет — работать дальше. + +#### Scenario: Предупреждение о пороге +- **GIVEN** раннер на подписке «A», в пуле есть свободная «B» +- **WHEN** на экране появляется «approaching usage limit» и ход заканчивается +- **THEN** раннер не подталкивается дальше, а продолжает разговор на «B» + +### Requirement: Не больше N переключений +Сессия SHALL переключаться не чаще `PEPPA_ROTATE_MAX_PER_HOUR` (3) раз в час и никогда — на +подписку с действующим лимитом или ошибкой входа. Предел исчерпан — сессия ждёт сброса. + +#### Scenario: Предел переключений +- **GIVEN** раннер уже переключался 3 раза за последний час +- **WHEN** он снова упирается в лимит при свободной подписке в пуле +- **THEN** раннер не переключается, а ждёт сброса лимита + +### Requirement: Справедливость между проектами +Проект, уже занимающий не меньше `PEPPA_POOL_PROJECT_MAX` (2) подписок пула, SHALL не +получать ещё одну свободную подписку, пока в пуле ждёт сброса лимита сессия другого проекта. + +#### Scenario: Очередь в пуле +- **GIVEN** проект X занимает 2 подписки пула, сессия проекта Y ждёт сброса лимита, в пуле свободна «C» +- **WHEN** сессия X упирается в лимит +- **THEN** X не переключается на «C», а вачдог отдаёт «C» сессии Y diff --git a/openspec/changes/pep-39-rotation/specs/web-workspace/spec.md b/openspec/changes/pep-39-rotation/specs/web-workspace/spec.md new file mode 100644 index 00000000..ac98dfcc --- /dev/null +++ b/openspec/changes/pep-39-rotation/specs/web-workspace/spec.md @@ -0,0 +1,13 @@ +# Spec Delta: web-workspace + +## ADDED Requirements + +### Requirement: Подписка и переключения сессии в вебе +«Раннеры» SHALL показывать подписку сессии, ожидание переключения на границе хода и историю +переключений (с какой, на какую, почему); карточка сессии на странице стори — подписку и +число переключений; «Подписки» — сколько сессий на подписке по проектам и статус лимита. + +#### Scenario: История переключений +- **GIVEN** раннер переключился с «Claude A» на «Claude B» из-за лимита +- **WHEN** PM открывает его в «Раннерах» +- **THEN** он видит подписку «Claude B» и запись «Claude A → Claude B · лимит» diff --git a/openspec/changes/pep-39-rotation/tasks.md b/openspec/changes/pep-39-rotation/tasks.md new file mode 100644 index 00000000..73d37b04 --- /dev/null +++ b/openspec/changes/pep-39-rotation/tasks.md @@ -0,0 +1,17 @@ +# Tasks: PEP-39 + +## 1. Данные и core +- [x] 1.1 Схема `sessions.rotate_reason` + миграция 0004 +- [x] 1.2 core: пометка лимита подписки, кандидаты для ротации, справедливость в pickSubscription, `subscriptionSwitches` в SessionView, сессии по проектам в listSubscriptions + +## 2. Раннер +- [x] 2.1 rotation.ts: бюджет, выбор кандидата, `rotateSession` (Claude/OpenCode resume, Codex заново), событие, сообщение PM +- [x] 2.2 recordLimit помечает подписку и планирует ротацию; вачдог: ротация, ожидание, порог; Stop-хук не подталкивает при ожидании ротации + +## 3. Моки и тесты +- [x] 3.1 mock-agent: лимит только на входе с подстрокой (`credential`), предупреждение о пороге +- [x] 3.2 testkit rotation.test.ts: переключение Claude с resume, нет свободных, Codex заново, порог, предел, справедливость + +## 4. Веб +- [x] 4.1 Раннеры: подписка, ожидание переключения, история; карточка сессии; события стори; Подписки — сессии по проектам +- [x] 4.2 AGENTS.md diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts index 8b8cdcd0..9774da6a 100644 --- a/packages/core/src/notifications.ts +++ b/packages/core/src/notifications.ts @@ -174,3 +174,25 @@ export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: Not } return out; } + +/** + * An informational message about a project's runner (no buttons, nothing to answer), e.g. + * «переключил на подписку X» (PEP-39): to the project's owner and members by their + * preferences, as a «failures» event (limits belong there). `dedupeKey` makes it once per + * event. Returns how many users got it. + */ +export async function sendProjectMessage(db: Db, projectId: number, text: string, dedupeKey: string, push: { title: string; url: string }): Promise { + let sent = 0; + for (const u of await projectAudience(db, projectId)) { + const r = await deliverToUser(db, u, { + event: "failures", + projectId, + dedupeKey: `${dedupeKey}:${u.telegramChatId}`, + pushKey: `${dedupeKey}:u${u.id}`, + telegram: { params: { text } }, + push: { title: push.title, body: text.slice(0, 200), url: push.url, tag: dedupeKey }, + }); + if (r.telegram || r.push) sent++; + } + return sent; +} diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index 6be52088..47a8f6ac 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -1,6 +1,6 @@ import { events, projects, questions, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm"; +import { and, desc, eq, inArray, isNull, lte, notInArray, sql } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import type { Question, QuestionKind } from "./tasks.ts"; @@ -16,6 +16,8 @@ export interface SessionView extends Session { taskTitle: string | null; /** PEP-67: name of the subscription the session runs on. */ subscriptionName: string | null; + /** PEP-39: how many times the session moved to another subscription (events). */ + subscriptionSwitches: number; } export async function createSession( @@ -71,7 +73,7 @@ export async function listUserSessions(db: Db, userId: number, opts: { filter?: export async function updateSession( db: Db, id: number, - patch: Partial>, + patch: Partial>, ): Promise { const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning(); if (!row) throw new PeppaError(`Session #${id} not found`); @@ -162,20 +164,23 @@ export async function raiseSessionQuestion( function sessionQuery(db: Db) { return db - .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, subscriptionName: subscriptions.name }) + .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, subscriptionName: subscriptions.name, + switches: sql`(select count(*) from events e where e.session_id = ${sessions.id} and e.type = 'subscription_switched')`, + }) .from(sessions) .innerJoin(projects, eq(sessions.projectId, projects.id)) .leftJoin(tasks, eq(sessions.taskId, tasks.id)) .leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id)); } -function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; subscriptionName: string | null }): SessionView { +function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; subscriptionName: string | null; switches: number }): SessionView { return { ...r.session, projectKey: r.projectKey, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, subscriptionName: r.subscriptionName, + subscriptionSwitches: Number(r.switches ?? 0), }; } diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts index 4c3f9670..a545d113 100644 --- a/packages/core/src/subscriptions.ts +++ b/packages/core/src/subscriptions.ts @@ -1,8 +1,10 @@ // Agent subscriptions and pools (PEP-67): superadmins keep the accounts agents run on // (Claude Code, Codex, OpenCode) and group them into pools; a runner takes the first free -// active subscription of the chosen set. Rotation on limits and fairness — PEP-39. +// active subscription of the chosen set. PEP-39: a limit marks the subscription, the +// watchdog moves the session to another usable subscription of the pool (rotation), with a +// simple fairness rule between projects sharing a pool. import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db"; -import { and, asc, count, eq, inArray, notInArray } from "drizzle-orm"; +import { and, asc, eq, inArray, notInArray } from "drizzle-orm"; import { decrypt, encrypt } from "./crypto.ts"; import { PeppaError } from "./errors.ts"; import { isSuperadmin } from "./monitor.ts"; @@ -26,6 +28,8 @@ export const OPENCODE_KEY_ENV: Record = { export interface SubscriptionView extends Subscription { createdByLogin: string | null; activeSessions: number; + /** PEP-39: active sessions on it per project. */ + projectSessions: Array<{ key: string; n: number }>; poolIds: number[]; } @@ -41,13 +45,28 @@ export async function requireSuperadmin(db: Db, user: Pick | null // ── subscriptions ──────────────────────────────────────────────────────────────── -async function activeSessionCounts(db: Db): Promise> { - const rows = await db - .select({ id: sessions.subscriptionId, n: count() }) +interface ActiveRow { + sessionId: number; + subscriptionId: number | null; + projectId: number; + projectKey: string; + status: (typeof sessions.$inferSelect)["status"]; + resumeAt: Date | null; +} + +/** Sessions not finished yet, with their subscription and project. */ +async function activeRows(db: Db): Promise { + return db + .select({ sessionId: sessions.id, subscriptionId: sessions.subscriptionId, projectId: sessions.projectId, projectKey: projects.key, status: sessions.status, resumeAt: sessions.resumeAt }) .from(sessions) - .where(notInArray(sessions.status, FINISHED_SESSION_STATUSES)) - .groupBy(sessions.subscriptionId); - return new Map(rows.filter((r) => r.id != null).map((r) => [r.id!, r.n])); + .innerJoin(projects, eq(sessions.projectId, projects.id)) + .where(notInArray(sessions.status, FINISHED_SESSION_STATUSES)); +} + +function countBySubscription(rows: ActiveRow[]): Map { + const m = new Map(); + for (const r of rows) if (r.subscriptionId != null) m.set(r.subscriptionId, (m.get(r.subscriptionId) ?? 0) + 1); + return m; } export async function listSubscriptions(db: Db): Promise { @@ -56,12 +75,19 @@ export async function listSubscriptions(db: Db): Promise { .from(subscriptions) .leftJoin(users, eq(subscriptions.createdBy, users.id)) .orderBy(asc(subscriptions.id)); - const counts = await activeSessionCounts(db); + const active = await activeRows(db); + const counts = countBySubscription(active); const members = await db.select().from(subscriptionPoolMembers); + const perProject = (id: number) => { + const m = new Map(); + for (const a of active) if (a.subscriptionId === id) m.set(a.projectKey, (m.get(a.projectKey) ?? 0) + 1); + return [...m].map(([key, n]) => ({ key, n })).sort((a, b) => a.key.localeCompare(b.key)); + }; return rows.map((r) => ({ ...r.s, createdByLogin: r.login, activeSessions: counts.get(r.s.id) ?? 0, + projectSessions: perProject(r.s.id), poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId), })); } @@ -225,12 +251,13 @@ export interface PickOptions { /** * The subscription a new runner starts on: the first free usable one of the chosen set * (ticked subscriptions, else the chosen pool, else the project's pool), by id; if all are - * busy — the least busy one (the runner never waits; fairness is PEP-39). Null when nothing + * busy — the least busy one (the runner never waits); fairness: poolRestricted. Null when nothing * is chosen and the project has no pool: the agent runs on this machine's own login. */ export async function pickSubscription(db: Db, o: PickOptions): Promise { let candidates: Subscription[]; let source: string; + let poolIdUsed: number | null = null; if (o.subscriptionIds?.length) { candidates = await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)).orderBy(asc(subscriptions.id)); source = "отмеченных"; @@ -239,6 +266,7 @@ export async function pickSubscription(db: Db, o: PickOptions): Promise isUsable(s, o.now)); if (!usable.length) throw new PeppaError(`Нет активных подписок среди ${source}${candidates.length ? "" : " (пул пуст)"} — проверьте их в «Подписках»`); - const counts = await activeSessionCounts(db); - return usable.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best)); + const active = await activeRows(db); + const counts = countBySubscription(active); + // Fairness (PEP-39): a project already holding K subscriptions of the pool while another + // project waits for a limit reset shares a busy subscription instead of taking a free one. + if (poolIdUsed != null && (await poolRestricted(db, poolIdUsed, o.projectId, active))) { + const shared = usable.filter((s) => (counts.get(s.id) ?? 0) > 0); + if (shared.length) return leastBusy(shared, counts); + } + return leastBusy(usable, counts); +} + +const leastBusy = (list: Subscription[], counts: Map) => + list.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best)); + +/** K for the fairness rule: subscriptions of one pool a project may hold while others wait. */ +export const poolProjectMax = () => Number(process.env.PEPPA_POOL_PROJECT_MAX ?? 2); + +/** + * True when the project already holds ≥ K distinct subscriptions of the pool and the pool + * has a queue: a session of another project waits for a limit reset on one of its + * subscriptions (rate_limited with an automatic resume time). + */ +async function poolRestricted(db: Db, poolId: number, projectId: number, active: ActiveRow[]): Promise { + const memberIds = new Set((await db.select().from(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.poolId, poolId))).map((m) => m.subscriptionId)); + const held = new Set(active.filter((a) => a.projectId === projectId && a.subscriptionId != null && memberIds.has(a.subscriptionId)).map((a) => a.subscriptionId)); + if (held.size < poolProjectMax()) return false; + return active.some((a) => a.projectId !== projectId && a.status === "rate_limited" && a.resumeAt != null && a.subscriptionId != null && memberIds.has(a.subscriptionId)); +} + +/** A limit hit on the subscription: «лимит до …» until it resets (PEP-39). */ +export async function markSubscriptionLimited(db: Db, id: number, until: Date, note?: string | null): Promise { + const cur = await getSubscription(db, id).catch(() => null); + if (!cur || cur.status === "pending" || cur.status === "auth_error") return; + // Never shorten a known later reset (two sessions report the same limit). + if (cur.status === "limited" && cur.limitedUntil && cur.limitedUntil > until) return; + await updateSubscription(db, id, { status: "limited", limitedUntil: until, lastError: note ? note.slice(0, 300) : cur.lastError }); +} + +export interface RotationOptions { + now?: Date; + /** Threshold rotation: only subscriptions nobody runs on. */ + onlyIdle?: boolean; +} + +/** + * Where a session may move (PEP-39): another usable subscription of the same provider in + * the project's pool — or, without one, in the pools holding the session's subscription — + * the least busy one (free first), honouring the fairness rule. Null: nowhere to go. + */ +export async function rotationCandidate( + db: Db, + s: { projectId: number; provider: SubscriptionProvider; subscriptionId: number | null }, + o: RotationOptions = {}, +): Promise { + if (s.subscriptionId == null) return null; + const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, s.projectId)); + const poolIds = + p?.poolId != null + ? [p.poolId] + : (await db.select().from(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.subscriptionId, s.subscriptionId))).map((m) => m.poolId); + if (!poolIds.length) return null; + const active = await activeRows(db); + const counts = countBySubscription(active); + const found = new Map(); + for (const poolId of poolIds) { + let list = (await poolSubscriptions(db, poolId)).filter((x) => x.provider === s.provider && x.id !== s.subscriptionId && isUsable(x, o.now)); + if (o.onlyIdle) list = list.filter((x) => !counts.get(x.id)); + // Fair share: a project over K while others wait gets no free subscription here. + if (list.length && (await poolRestricted(db, poolId, s.projectId, active))) list = list.filter((x) => (counts.get(x.id) ?? 0) > 0); + for (const x of list) found.set(x.id, x); + } + const list = [...found.values()].sort((a, b) => a.id - b.id); + return list.length ? leastBusy(list, counts) : null; } /** Claude token for one-off calls on behalf of a project (incident triage): the project's pool. */ diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts index 05e1e8fe..72dbe607 100644 --- a/packages/core/src/telegram.ts +++ b/packages/core/src/telegram.ts @@ -157,3 +157,4 @@ export async function answeredQuestionMessages(db: Db, since: Date) { .innerJoin(questions, eq(telegramOutbox.questionId, questions.id)) .where(and(eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), gt(questions.answeredAt, since))); } + diff --git a/packages/db/migrations/0006_rotation.sql b/packages/db/migrations/0006_rotation.sql new file mode 100644 index 00000000..10726f1b --- /dev/null +++ b/packages/db/migrations/0006_rotation.sql @@ -0,0 +1 @@ +ALTER TABLE `sessions` ADD `rotate_reason` text; \ No newline at end of file diff --git a/packages/db/migrations/meta/0006_snapshot.json b/packages/db/migrations/meta/0006_snapshot.json new file mode 100644 index 00000000..5302520d --- /dev/null +++ b/packages/db/migrations/meta/0006_snapshot.json @@ -0,0 +1,2974 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "b6495e1a-6087-42fb-a94f-3e6942582651", + "prevId": "01595f06-03c2-470a-8d64-60ecf41afd6d", + "tables": { + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "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 + } + }, + "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 f19de56e..d8790d22 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1794614987778, "tag": "0005_push_notifications", "breakpoints": true + }, + { + "idx": 6, + "version": "6", + "when": 1794615712278, + "tag": "0006_rotation", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index daf06b76..85de53c7 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -254,6 +254,8 @@ export const sessions = sqliteTable("sessions", { limitResumes: integer("limit_resumes").notNull().default(0), limitResumesDay: text("limit_resumes_day"), limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }), + // PEP-39: switch to another subscription of the pool at the turn boundary ("limit" | "threshold"). + rotateReason: text("rotate_reason", { enum: ["limit", "threshold"] }), status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"), lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }), startedAt: createdAt(), diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index 0221ef4f..ccd7bb6b 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -180,6 +180,12 @@ const NUDGE = (key: string) => */ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise { await logSessionEvent(db, s, "turn_end", { text }); + // PEP-39: the subscription is near its limit — end the turn here (no nudge, no ping); + // the watchdog moves the session to a free subscription at this boundary. + if (s.rotateReason && (await pendingSessionQuestions(db, s.id)).length === 0) { + await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); + return null; + } if ((await pendingSessionQuestions(db, s.id)).length > 0) { await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; @@ -279,7 +285,9 @@ async function handle(event: string, input: HookInput): Promise { await logSessionEvent(db, s, "stop_failure", { error: input.error, details: input.error_details }); if (limited) { // Stores when to continue; the watchdog resumes the runner then (PEP-56). - await raiseSessionQuestion(db, s, "attention", await recordLimit(db, s, input.error_details ?? input.last_assistant_message ?? "")); + // PEP-39: null = another subscription of the pool is free, the watchdog switches to it. + const msg = await recordLimit(db, s, input.error_details ?? input.last_assistant_message ?? ""); + if (msg) await raiseSessionQuestion(db, s, "attention", msg); break; } await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now }); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index bd5a52f8..5bcce6b5 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -23,3 +23,4 @@ export * from "./claude-print.ts"; export * from "./reviewer.ts"; export * from "./autonomy.ts"; export * from "./workspace-sync.ts"; +export * from "./rotation.ts"; diff --git a/packages/runner/src/limits.ts b/packages/runner/src/limits.ts index 5cf01575..0ad7b521 100644 --- a/packages/runner/src/limits.ts +++ b/packages/runner/src/limits.ts @@ -1,6 +1,7 @@ // Usage limits (PEP-56): when does the agent's limit reset, and what to tell the PM. -import { updateSession, type SessionView } from "@peppa/core"; +import { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core"; import type { Db } from "@peppa/db"; +import { planRotation } from "./rotation.ts"; export const LIMIT_RESUME_GRACE_MS = 60_000; export const MAX_LIMIT_RESUMES_PER_DAY = 6; @@ -37,9 +38,11 @@ const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, loc /** * The runner hit a usage limit: store when to continue (reset time, or a probe if - * unknown / the limit came back right after an auto-resume). Returns the PM's message. + * unknown / the limit came back right after an auto-resume) and mark its subscription + * «лимит до …» (PEP-39). Returns the PM's message — or null when another subscription of + * the pool is free: the watchdog switches to it (`rotate_reason`) and reports that instead. */ -export async function recordLimit(db: Db, s: SessionView, text: string, now = new Date()): Promise { +export async function recordLimit(db: Db, s: SessionView, text: string, now = new Date()): Promise { const who = s.taskKey ?? `Раннер ${s.id}`; const day = today(now); const resumesToday = s.limitResumesDay === day ? s.limitResumes : 0; @@ -55,13 +58,17 @@ export async function recordLimit(db: Db, s: SessionView, text: string, now = ne } const capped = resumesToday >= MAX_LIMIT_RESUMES_PER_DAY; const auto = limitAutoResumeEnabled() && !capped; + if (s.subscriptionId != null) await markSubscriptionLimited(db, s.subscriptionId, reset ?? resumeAt!, text); + const rotate = auto && !!(await planRotation(db, s, "limit", now)); await updateSession(db, s.id, { status: "rate_limited", resumeAt: auto ? resumeAt : null, limitProbeMin: auto ? probe : null, limitResumes: resumesToday, limitResumesDay: day, + rotateReason: rotate ? "limit" : null, }); + if (rotate) return null; if (!auto) { return capped ? `${who}: снова лимит, автопродолжений сегодня уже ${MAX_LIMIT_RESUMES_PER_DAY} — нужен ты. Нажми «Перезапустить», когда лимит сбросится.` diff --git a/packages/runner/src/rotation.ts b/packages/runner/src/rotation.ts new file mode 100644 index 00000000..2ebc5cd0 --- /dev/null +++ b/packages/runner/src/rotation.ts @@ -0,0 +1,113 @@ +// Subscription rotation (PEP-39): a session that hit a usage limit — or got close to it — +// moves to another usable subscription of its pool at a turn boundary, continuing the same +// conversation where the CLI allows it. Decided by the watchdog; hooks only set flags. +import { + expireSessionQuestions, + getSession, + getSubscription, + logSessionEvent, + rotationCandidate, + sendProjectMessage, + updateSession, + type SessionView, + type Subscription, +} from "@peppa/core"; +import { events, type Db } from "@peppa/db"; +import { and, count, eq, gte } from "drizzle-orm"; +import * as tmux from "./tmux.ts"; + +export const SWITCH_EVENT = "subscription_switched"; +export const ROTATE_WINDOW_MS = 60 * 60_000; +export const maxRotationsPerHour = () => Number(process.env.PEPPA_ROTATE_MAX_PER_HOUR ?? 3); +export const rotateThresholdPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85); +export const rotationEnabled = () => process.env.PEPPA_ROTATE !== "off" && process.env.PEPPA_LIMIT_AUTORESUME !== "off"; + +export type RotateReason = "limit" | "threshold"; + +/** Switches of this session within the last hour (events written by rotateSession). */ +export async function rotationsLastHour(db: Db, sessionId: number, now = new Date()): Promise { + const [row] = await db + .select({ n: count() }) + .from(events) + .where(and(eq(events.sessionId, sessionId), eq(events.type, SWITCH_EVENT), gte(events.createdAt, new Date(now.getTime() - ROTATE_WINDOW_MS)))); + return row?.n ?? 0; +} + +/** + * The subscription the session would move to now, or null: rotation off, no subscription + * (this machine's login), no pool, nothing usable, or the hourly budget is spent. + */ +export async function planRotation(db: Db, s: SessionView, reason: RotateReason, now = new Date()): Promise { + if (!rotationEnabled() || s.subscriptionId == null) return null; + if ((await rotationsLastHour(db, s.id, now)) >= maxRotationsPerHour()) return null; + return rotationCandidate(db, s, { now, onlyIdle: reason === "threshold" }); +} + +const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }); + +/** + * Relaunches the session on `target`: Claude Code and OpenCode continue the same + * conversation (transcripts are local, only the login changes); Codex keeps its threads in + * the account's CODEX_HOME, so it starts afresh and rebuilds context from the story. + * Call only at a turn boundary — the agent process is killed. + */ +export async function rotateSession(db: Db, s: SessionView, target: Subscription, reason: RotateReason, now = new Date()): Promise { + const from = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null; + const carried = s.provider === "codex" || !s.conversationId ? "fresh" : "resume"; + if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName); + await expireSessionQuestions(db, s.id, "(неактуально: раннер переключён на другую подписку)"); + await updateSession(db, s.id, { + subscriptionId: target.id, + rotateReason: null, + resumeAt: null, + limitProbeMin: null, + ...(carried === "fresh" ? { conversationId: null } : {}), + }); + await logSessionEvent(db, s, SWITCH_EVENT, { + fromId: from?.id ?? s.subscriptionId, + fromName: from?.name ?? s.subscriptionName, + toId: target.id, + toName: target.name, + reason, + carried, + limitedUntil: from?.status === "limited" ? from.limitedUntil : null, + }); + const who = s.taskKey ?? `Раннер ${s.id}`; + const prompt = + carried === "fresh" + ? `Предыдущий запуск${s.taskKey ? ` над стори ${s.taskKey}` : ""} шёл на другой подписке и ${reason === "limit" ? "упёрся в лимит" : "подошёл к лимиту"}; разговор не перенесён. Восстанови контекст: peppa.get_task, tasks.md активного OpenSpec change, git status, git log и git diff в рабочей копии — и продолжай с того места.` + : `Раннер переключён на другую подписку (${reason === "limit" ? "на прежней лимит" : "прежняя подходит к лимиту"}). Продолжай с того места, где остановился.`; + // Loaded lazily: the hook process imports this module (via limits) and stays light. + const { resumeSession } = await import("./sessions.ts"); + const resumed = await resumeSession(db, s.id, { prompt }); + const why = reason === "limit" ? `лимит${from?.limitedUntil && from.status === "limited" ? ` до ${hhmm(from.limitedUntil)}` : ""}` : "подписка подходит к лимиту"; + const how = carried === "resume" ? "продолжает тот же разговор" : "Codex не переносит разговор между аккаунтами — начал заново с контекстом из стори"; + await sendProjectMessage(db, s.projectId, `🔁 ${who}: переключил с подписки «${from?.name ?? "?"}» на «${target.name}» (${why}), ${how}.`, `rot:${s.id}:g${resumed.generation}`, { + title: `${who}: другая подписка`, + url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}`, + }); + return getSession(db, s.id); +} + +/** + * The turn is over (Stop / StopFailure / limit banner): move the session if it waits for a + * rotation and somewhere to go exists. Returns true when the session was relaunched. + */ +export async function tryRotate(db: Db, s: SessionView, reason: RotateReason, now = new Date(), log: (m: string) => void = () => {}): Promise { + const target = await planRotation(db, s, reason, now); + if (!target) return false; + await rotateSession(db, s, target, reason, now); + log(`#${s.id} ${s.taskKey ?? ""}: subscription ${s.subscriptionName ?? s.subscriptionId} → ${target.name} (${reason})`); + return true; +} + +/** Usage warning on screen: "approaching usage limit", "used 90% of your weekly limit". */ +const WARN_RE = /(approaching (?:your )?(?:usage )?limit|(\d{1,3})\s?% of your [^\n]{0,40}limit|used (\d{1,3})\s?%)/i; + +/** True when the screen shows a usage warning at or above the threshold. */ +export function usageWarning(screen: string): boolean { + const m = WARN_RE.exec(screen); + if (!m) return false; + const pct = Number(m[2] ?? m[3] ?? NaN); + return Number.isNaN(pct) || pct >= rotateThresholdPct(); +} diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index f6c73efc..2df52598 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -95,7 +95,7 @@ async function launch( ): Promise { const generation = s.generation + 1; const rules = await loadSharedRules(); - // The session's subscription (no rotation on resume — PEP-39); none = this machine's login. + // 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; const argv = buildCommand(s.provider, { sessionId: s.id, diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index ef2b3164..f41a3d27 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -16,6 +16,8 @@ import type { Db } from "@peppa/db"; import * as tmux from "./tmux.ts"; import { recordLimit } from "./limits.ts"; import { resumeSession } from "./sessions.ts"; +import { getSubscription, isUsable } from "@peppa/core"; +import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts"; import { monitorTick } from "./monitor.ts"; import { incidentTick } from "./incidents.ts"; import { pollChecks } from "./ci-feedback.ts"; @@ -41,7 +43,8 @@ function screenTail(screen: string, lines: number): string { // Screen hash per session, kept across ticks. const lastScreen = new Map(); -const limitAlerted = new Set(); +const limitAlerted = new Set(); +const thresholdSeen = new Set(); export async function tick(db: Db, opts: WatchdogOptions): Promise { const log = opts.log ?? (() => {}); @@ -62,12 +65,25 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise { async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) { if (s.tmuxName.startsWith("pending-")) return; - // Rate-limited runner: continue it once its limit has reset (PEP-56), whether or not the - // agent process is still alive; until then leave it alone. + const nowDate = opts.now ?? new Date(); + // Rate-limited runner: move it to a free subscription of its pool (PEP-39), else continue + // it once its limit has reset (PEP-56), whether or not the agent process is still alive. if (s.status === "rate_limited" && s.resumeAt) { - if ((opts.now ?? new Date()).getTime() >= s.resumeAt.getTime()) await resumeAfterLimit(db, s, opts.now ?? new Date(), log); + if (await rotateLimited(db, s, nowDate, log)) return; + if (nowDate.getTime() >= s.resumeAt.getTime()) await resumeAfterLimit(db, s, nowDate, log); return; } + // Near the limit: switch once the turn is over and nothing waits for the PM's answer. + if (s.rotateReason === "threshold" && (s.status === "idle" || s.status === "waiting_input")) { + const blocking = (await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention"); + if (!blocking) { + if (!(await tryRotate(db, s, "threshold", nowDate, log))) { + await updateSession(db, s.id, { rotateReason: null }); + await logSessionEvent(db, s, "rotation_skipped", { reason: "threshold", why: "нет свободной подписки" }); + } + return; + } + } const label = `#${s.id} ${s.taskKey ?? ""} (${s.tmuxName})`; if (!(await tmux.hasSession(s.tmuxName))) { @@ -106,12 +122,25 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: } // Fallback for limits that don't come through the StopFailure hook. - if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && !limitAlerted.has(s.id)) { - limitAlerted.add(s.id); + if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && !limitAlerted.has(`${s.id}:${s.generation}`)) { + limitAlerted.add(`${s.id}:${s.generation}`); const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? ""; log(`${label}: usage limit`); await logSessionEvent(db, s, "usage_limit", { line }); - await raiseSessionQuestion(db, s, "attention", await recordLimit(db, s, line, new Date(now))); + const msg = await recordLimit(db, s, line, new Date(now)); + if (msg) await raiseSessionQuestion(db, s, "attention", msg); + return; + } + + // PEP-39: the CLI warns the subscription is close to its limit — switch at the turn end. + if (!s.rotateReason && s.subscriptionId != null && rotationEnabled() && !thresholdSeen.has(`${s.id}:${s.generation}`) && usageWarning(screen)) { + thresholdSeen.add(`${s.id}:${s.generation}`); + const line = screen.split("\n").reverse().find((l) => usageWarning(l))?.trim() ?? ""; + await logSessionEvent(db, s, "usage_threshold", { line }); + if (await planRotation(db, s, "threshold", new Date(now))) { + await updateSession(db, s.id, { rotateReason: "threshold" }); + log(`${label}: near the usage limit, will switch subscription at the turn end`); + } } if (s.status === "running" && now - last > opts.stallMs) { @@ -152,6 +181,25 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS } } +/** + * PEP-39: a rate-limited runner whose subscription is still limited moves to another usable + * subscription of its pool. Asked for by recordLimit (`rotate_reason`), or a subscription + * freed up while it waits. Nowhere to go after a planned switch → tell the PM it waits. + */ +async function rotateLimited(db: Db, s: SessionView, now: Date, log: (m: string) => void): Promise { + if (s.subscriptionId == null) return false; + const sub = await getSubscription(db, s.subscriptionId).catch(() => null); + if (!s.rotateReason && sub && isUsable(sub, now)) return false; + if (await tryRotate(db, s, "limit", now, log)) return true; + if (s.rotateReason) { + await updateSession(db, s.id, { rotateReason: null }); + await logSessionEvent(db, s, "rotation_skipped", { reason: "limit", why: "нет свободной подписки" }); + const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }); + await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Раннер ${s.id}`}: лимит, свободных подписок в пуле нет — продолжит в ${at} сам.`); + } + return false; +} + /** The limit has reset: nudge the live agent, or relaunch it with its conversation. */ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: string) => void) { const day = now.toLocaleDateString("sv-SE"); diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index 6ce62d68..e2e4c1fe 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -270,8 +270,12 @@ async function run(action: Action): Promise { } else { log("ask", { via: "terminal" }); } + } else if ("warn" in action) { + out(`⚠ You've used ${action.warn}% of your weekly limit · resets Mon 9am\n`); + log("warn", { pct: action.warn }); } else if ("limit" in action) { const spec = typeof action.limit === "object" ? action.limit : {}; + if (spec.credential && !(credential() ?? "").includes(spec.credential)) return true; const at = spec.resetInSec != null ? new Date(Date.now() + spec.resetInSec * 1000).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }) : null; const when = spec.reset === "unknown" ? "" : at ? ` resets at ${at}` : " resets 5pm"; if (provider === "claude") { @@ -412,19 +416,21 @@ async function setupToken() { const apiKey = () => process.env.ANTHROPIC_API_KEY ?? process.env.OPENAI_API_KEY ?? process.env.OPENROUTER_API_KEY; +/** The login this run uses: Claude token, Codex auth.json, OpenCode provider key. */ +function credential(): string | undefined { + if (provider === "claude") return process.env.CLAUDE_CODE_OAUTH_TOKEN ?? "mock-machine-login"; + if (provider === "opencode") return apiKey(); + const auth = join(process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex"), "auth.json"); + return existsSync(auth) ? readFileSync(auth, "utf8") : undefined; +} + /** * Trial runs for «Проверить» (`claude -p`, `codex exec`, `opencode run`): the credential's * text decides — "bad" → auth error, "limit" → usage limit banner with a reset time, else ok. */ function probe(): never { const fail = (msg: string) => (process.stderr.write(`${msg}\n`), process.exit(1)); - let cred: string | undefined; - if (provider === "claude") cred = process.env.CLAUDE_CODE_OAUTH_TOKEN ?? "mock-machine-login"; - else if (provider === "opencode") cred = apiKey(); - else { - const auth = join(process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex"), "auth.json"); - cred = existsSync(auth) ? readFileSync(auth, "utf8") : undefined; - } + const cred = credential(); if (!cred) fail(provider === "codex" ? "Not logged in. Run `codex login`." : "Error: no API key configured"); if (cred!.includes("bad")) fail(provider === "claude" ? "Invalid API key · Please run /login" : "Error: 401 Unauthorized: invalid credentials"); if (cred!.includes("limit")) fail(provider === "claude" ? "Claude AI usage limit reached. Your limit resets 5pm" : "You've hit your usage limit. Try again at 5:00 PM."); diff --git a/packages/testkit/src/scenario.ts b/packages/testkit/src/scenario.ts index 847da2dc..3e2f1c3d 100644 --- a/packages/testkit/src/scenario.ts +++ b/packages/testkit/src/scenario.ts @@ -9,7 +9,10 @@ export type Action = | { mcp: string; args?: Record } // call a peppa MCP tool | { permission: { tool: string; input: Record } } // claude: PermissionRequest | { ask: Array<{ question: string; options?: string[] }> } // claude: AskUserQuestion - | { limit: true | { resetInSec?: number; reset?: "unknown" } } // usage limit: StopFailure (claude) / banner only (codex); resetInSec → "resets at HH:MM" + // usage limit: StopFailure (claude) / banner only (codex); resetInSec → "resets at HH:MM"; + // credential → only when the run's login (Claude token, Codex auth.json, OpenCode key) contains it + | { limit: true | { resetInSec?: number; reset?: "unknown"; credential?: string } } + | { warn: number } // usage warning banner: "You've used N% of your weekly limit" | { hang: true } // freeze: no output, no input handling | { crash: number } // exit with this code | { clear: true } // claude: /clear (SessionEnd + SessionStart with a new id) diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts index a10baa05..7fc3a335 100644 --- a/packages/testkit/test/limits.test.ts +++ b/packages/testkit/test/limits.test.ts @@ -122,7 +122,7 @@ describe("Отключение", () => { try { const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached, resets 5pm"); assert.equal((await sess(sid)).resumeAt, null); - assert.match(text, /упёрлась в лимит/); + assert.match(text ?? "", /упёрлась в лимит/); } finally { delete process.env.PEPPA_LIMIT_AUTORESUME; } diff --git a/packages/testkit/test/rotation.test.ts b/packages/testkit/test/rotation.test.ts new file mode 100644 index 00000000..f8095a29 --- /dev/null +++ b/packages/testkit/test/rotation.test.ts @@ -0,0 +1,228 @@ +// PEP-39: a runner that hits a usage limit (or gets close to it) moves to another usable +// subscription of its pool at a turn boundary. Mock CLIs hit the limit only on a login that +// contains a marker (`limit.credential`), like the real one hits it on one account. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { events } from "@peppa/db"; +import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; + +type User = Awaited>; +let pm: User; +const CHAT = 5550039; +before(async () => { + pm = await core.upsertUserFromGitea(db, { id: 39, login: "mock-pm-39" }, { access_token: "x" }); + db.$client.prepare("UPDATE users SET telegram_chat_id = ?, telegram_user_id = ? WHERE id = ?").run(CHAT, CHAT, pm.id); + setDefaultOwner(pm.id); +}); +after(teardown); + +const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag}`; +const claudeSub = (name: string, tag: string) => runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: pm.id }); +const tail = (tag: string) => `…${TOKEN(tag).slice(-4)}`; +const sess = (id: number) => core.getSession(db, id); +const sub = (id: number) => core.getSubscription(db, id); +const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now }); +const starts = (p: { log(): Array<{ ev: string; [k: string]: unknown }> }) => p.log().filter((e) => e.ev === "start"); +let seq = 0; +const poolFor = async (key: string, ids: number[]) => { + const pool = await core.createPool(db, { name: `Пул ${++seq}`, subscriptionIds: ids }); + await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id); + return pool; +}; +const switches = async (sid: number) => + (await db.select().from(events)).filter((e) => e.sessionId === sid && e.type === runner.SWITCH_EVENT).map((e) => e.payload as Record); + +describe("Переключение на свободную подписку пула", () => { + test("Есть свободная подписка: тот же разговор на «B», подписка «A» — «лимит до …», PM получает сообщение", async () => { + const a = await claudeSub("Rot A", "rotlimA"); + const b = await claudeSub("Rot B", "rotokB"); + const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "rotlimA" } }]], resumeTurns: [[{ say: "Продолжаю на B." }]] }); + await poolFor(p.key, [a.id, b.id]); + const sid = await p.start(); + assert.equal((await sess(sid)).subscriptionId, a.id); + await p.waitStatus(sid, "rate_limited"); + const s = await sess(sid); + assert.equal(s.rotateReason, "limit"); + assert.equal((await p.pending(sid)).length, 0, "no «остановлен по лимиту» ping — a switch is coming"); + const la = await sub(a.id); + assert.equal(la.status, "limited"); + assert.ok(Math.abs(la.limitedUntil!.getTime() - (Date.now() + 3600_000)) < 120_000, "limited until the reset time"); + + await tick(); + const start = await p.waitLog("relaunched on B", (e) => e.ev === "start" && e.gen === "2"); + assert.equal(start.resume, s.conversationId, "continues the same conversation"); + assert.equal(start.oauthToken, tail("rotokB")); + await p.waitLog("resumed turn", (e) => e.ev === "action" && JSON.stringify(e.action).includes("Продолжаю на B")); + const after = await sess(sid); + assert.equal(after.subscriptionId, b.id); + assert.equal(after.subscriptionName, "Rot B"); + assert.equal(after.subscriptionSwitches, 1); + assert.equal(after.rotateReason, null); + const [ev] = await switches(sid); + assert.deepEqual({ from: ev!.fromName, to: ev!.toName, reason: ev!.reason, carried: ev!.carried }, { from: "Rot A", to: "Rot B", reason: "limit", carried: "resume" }); + const msg = await core.getOutbox(db, `rot:${sid}:g2:${CHAT}`); + assert.match(String((msg!.params as { text: string }).text), /переключил с подписки «Rot A» на «Rot B» \(лимит до \d\d:\d\d\), продолжает тот же разговор/); + + // A new runner of the project doesn't start on the limited subscription. + const p2 = await project({ turns: [[{ say: "ok" }]] }); + await poolFor(p2.key, [a.id, b.id]); + const s2 = await p2.start(); + assert.equal((await sess(s2)).subscriptionId, b.id); + for (const id of [sid, s2]) await runner.stopSession(db, id); + }); + + test("Свободных нет: ждёт сброса и продолжает сам; освободилась подписка — переключается на неё", async () => { + const a = await claudeSub("Solo A", "sololimA"); + const p = await project({ turns: [[{ limit: { resetInSec: 120, credential: "sololimA" } }], [{ say: "Сам после сброса." }]] }); + const pool = await poolFor(p.key, [a.id]); + const sid = await p.start(); + await p.waitStatus(sid, "rate_limited"); + const s = await sess(sid); + assert.equal(s.rotateReason, null); + assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/); + await tick(); + assert.equal((await sess(sid)).subscriptionId, a.id, "nowhere to go — stays"); + await tickAt(new Date(s.resumeAt!.getTime() + 1000)); + await p.waitLog("continued after reset", (e) => e.ev === "prompt" && String(e.prompt).includes("Лимит сброшен")); + assert.equal((await sess(sid)).subscriptionId, a.id); + await runner.stopSession(db, sid); + + // Same, but a subscription is added to the pool while the runner waits. + const p2 = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "sololimA" } }]], resumeTurns: [[{ say: "На новой." }]] }); + const a2 = await claudeSub("Solo A2", "sololimA2"); + await core.updatePool(db, pool.id, { subscriptionIds: [a2.id] }); + await core.setProjectPool(db, (await core.getProject(db, p2.key)).id, pool.id); + const sid2 = await p2.start(); + await p2.waitStatus(sid2, "rate_limited"); + const fresh = await claudeSub("Solo C", "soloC"); + await core.updatePool(db, pool.id, { subscriptionIds: [a2.id, fresh.id] }); + await tick(); + await p2.waitLog("switched to the new one", (e) => e.ev === "start" && e.gen === "2"); + assert.equal((await sess(sid2)).subscriptionId, fresh.id); + await runner.stopSession(db, sid2); + }); + + test("Codex: новый запуск на второй подписке без resume, с подсказкой восстановить контекст", async () => { + const c1 = await runner.addSubscription(db, { provider: "codex", name: "Codex 1", method: "api_key", secret: "mock-limit-key-rot1", createdBy: pm.id }); + const c2 = await runner.addSubscription(db, { provider: "codex", name: "Codex 2", method: "api_key", secret: "mock-openai-key-rot2", createdBy: pm.id }); + const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "limit" } }, { say: "Начал заново." }]] }); + await poolFor(p.key, [c1.id, c2.id]); + const sid = await p.start({ provider: "codex" }); + assert.equal((await sess(sid)).subscriptionId, c1.id); + await p.waitLog("banner", (e) => e.ev === "limit"); + await waitFor("limit recorded", async () => { + await tick(); + return (await sess(sid)).generation === 2 || (await sess(sid)).rotateReason === "limit"; + }); + await tick(); + const start = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2"); + assert.equal(start.resume, null, "Codex threads don't move between accounts"); + assert.equal(start.codexHome, runner.codexHome(c2.id)); + assert.match(String((start.argv as string[]).at(-1)), /Восстанови контекст/); + const after = await sess(sid); + assert.equal(after.subscriptionId, c2.id); + assert.equal((await switches(sid))[0]!.carried, "fresh"); + assert.match(String(((await core.getOutbox(db, `rot:${sid}:g2:${CHAT}`))!.params as { text: string }).text), /Codex не переносит разговор/); + await runner.stopSession(db, sid); + }); +}); + +describe("Порог использования", () => { + test("Предупреждение: ход доживает до конца без подталкивания, затем тот же разговор на свободной «B»", async () => { + const a = await claudeSub("Warn A", "warnA"); + const b = await claudeSub("Warn B", "warnB"); + const p = await project({ turns: [[{ warn: 90 }, { work: 2500 }, { say: "Ход закончен." }]], resumeTurns: [[{ say: "Дальше на B." }]] }); + await poolFor(p.key, [a.id, b.id]); + const sid = await p.start(); + await p.waitLog("warning on screen", (e) => e.ev === "warn"); + await waitFor("threshold noticed", async () => { + await tick(); + return (await sess(sid)).rotateReason === "threshold"; + }); + await p.waitStatus(sid, "idle"); + assert.equal((await p.pending(sid)).length, 0, "no «закончила ход» ping"); + assert.equal((await sub(a.id)).status, "active", "a warning is not a limit"); + await tick(); + const start = await p.waitLog("relaunched on B", (e) => e.ev === "start" && e.gen === "2"); + assert.equal(start.oauthToken, tail("warnB")); + assert.ok(start.resume); + assert.equal((await switches(sid))[0]!.reason, "threshold"); + await runner.stopSession(db, sid); + }); + + test("Предупреждение ниже порога ничего не меняет", () => { + assert.equal(runner.usageWarning("You've used 50% of your weekly limit"), false); + assert.equal(runner.usageWarning("You've used 92% of your weekly limit"), true); + assert.equal(runner.usageWarning("Approaching usage limit · resets at 5pm"), true); + }); +}); + +describe("Предохранители", () => { + test("Предел переключений: после 3 за час раннер ждёт сброса, а не переключается", async () => { + const a = await claudeSub("Cap A", "caplimA"); + const b = await claudeSub("Cap B", "capB"); + const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 3600, credential: "caplimA" } }]] }); + await poolFor(p.key, [a.id, b.id]); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "attention"); + for (let i = 0; i < runner.maxRotationsPerHour(); i++) await core.logSessionEvent(db, await sess(sid), runner.SWITCH_EVENT, { reason: "limit" }); + await runner.answerAndDeliver(db, q.id, "дальше", "web"); + await p.waitStatus(sid, "rate_limited"); + assert.equal((await sess(sid)).rotateReason, null); + assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/); + await tick(); + assert.equal((await sess(sid)).subscriptionId, a.id); + assert.equal((await sess(sid)).generation, 1); + await runner.stopSession(db, sid); + }); + + test("Выключено (PEPPA_ROTATE=off): нет переключений", async () => { + const a = await claudeSub("Off A", "offA"); + const b = await claudeSub("Off B", "offB"); + const p = await project({ turns: [] }); + await poolFor(p.key, [a.id, b.id]); + const s = await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id, subscriptionId: a.id }); + process.env.PEPPA_ROTATE = "off"; + try { + assert.equal(await runner.planRotation(db, await sess(s.id), "limit"), null); + } finally { + delete process.env.PEPPA_ROTATE; + } + assert.equal((await runner.planRotation(db, await sess(s.id), "limit"))?.id, b.id); + await core.updateSession(db, s.id, { status: "done" }); + }); +}); + +describe("Справедливость между проектами", () => { + test("Проект с 2 подписками пула не получает свободную, пока другой проект ждёт сброса", async () => { + const [a, b, c, d] = [await claudeSub("Fair A", "fairA"), await claudeSub("Fair B", "fairB"), await claudeSub("Fair C", "fairC"), await claudeSub("Fair D", "fairD")]; + const pool = await core.createPool(db, { name: "Общий", subscriptionIds: [a.id, b.id, c.id, d.id] }); + const x = await core.getProject(db, (await project({ turns: [] })).key); + const y = await core.getProject(db, (await project({ turns: [] })).key); + for (const pr of [x, y]) await core.setProjectPool(db, pr.id, pool.id); + + // Y waits for a limit reset on A. + const ys = await core.createSession(db, { projectId: y.id, subscriptionId: a.id }); + await core.updateSession(db, ys.id, { status: "rate_limited", resumeAt: new Date(Date.now() + 3600_000) }); + await core.markSubscriptionLimited(db, a.id, new Date(Date.now() + 3600_000)); + // X holds B and C. + const x1 = await core.createSession(db, { projectId: x.id, subscriptionId: b.id }); + const x2 = await core.createSession(db, { projectId: x.id, subscriptionId: c.id }); + for (const s of [x1, x2]) await core.updateSession(db, s.id, { status: "running" }); + + // A new X runner shares a busy subscription instead of taking the free D. + assert.equal((await core.pickSubscription(db, { projectId: x.id }))!.id, b.id); + // X can't move onto D either; the waiting Y gets it. + assert.notEqual((await core.rotationCandidate(db, { projectId: x.id, provider: "claude", subscriptionId: b.id }))?.id, d.id); + assert.equal((await core.rotationCandidate(db, { projectId: y.id, provider: "claude", subscriptionId: a.id }))?.id, d.id); + + // No queue → the free subscription is X's. + await core.updateSession(db, ys.id, { status: "done" }); + assert.equal((await core.pickSubscription(db, { projectId: x.id }))!.id, d.id); + const view = (await core.listSubscriptions(db)).find((s) => s.id === b.id)!; + assert.deepEqual(view.projectSessions, [{ key: x.key, n: 1 }]); + for (const s of [x1, x2]) await core.updateSession(db, s.id, { status: "done" }); + }); +}); -- 2.45.2 From b3533c73bbb38102aa73c0c45ac0e9b4e46f37e9 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 04:45:31 +0500 Subject: [PATCH 006/472] PEP-39: archive OpenSpec change pep-39-rotation Co-Authored-By: Claude Opus 5.5 --- .../2026-11-14-pep-39-rotation}/design.md | 0 .../2026-11-14-pep-39-rotation}/proposal.md | 0 .../specs/agent-credentials/spec.md | 0 .../specs/subscription-rotation/spec.md | 0 .../specs/web-workspace/spec.md | 0 .../2026-11-14-pep-39-rotation}/tasks.md | 0 openspec/specs/agent-credentials/spec.md | 5 +- openspec/specs/subscription-rotation/spec.md | 66 +++++++++++++++++++ openspec/specs/web-workspace/spec.md | 10 +++ 9 files changed, 79 insertions(+), 2 deletions(-) rename openspec/changes/{pep-39-rotation => archive/2026-11-14-pep-39-rotation}/design.md (100%) rename openspec/changes/{pep-39-rotation => archive/2026-11-14-pep-39-rotation}/proposal.md (100%) rename openspec/changes/{pep-39-rotation => archive/2026-11-14-pep-39-rotation}/specs/agent-credentials/spec.md (100%) rename openspec/changes/{pep-39-rotation => archive/2026-11-14-pep-39-rotation}/specs/subscription-rotation/spec.md (100%) rename openspec/changes/{pep-39-rotation => archive/2026-11-14-pep-39-rotation}/specs/web-workspace/spec.md (100%) rename openspec/changes/{pep-39-rotation => archive/2026-11-14-pep-39-rotation}/tasks.md (100%) create mode 100644 openspec/specs/subscription-rotation/spec.md diff --git a/openspec/changes/pep-39-rotation/design.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/design.md similarity index 100% rename from openspec/changes/pep-39-rotation/design.md rename to openspec/changes/archive/2026-11-14-pep-39-rotation/design.md diff --git a/openspec/changes/pep-39-rotation/proposal.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md similarity index 100% rename from openspec/changes/pep-39-rotation/proposal.md rename to openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md diff --git a/openspec/changes/pep-39-rotation/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/specs/agent-credentials/spec.md similarity index 100% rename from openspec/changes/pep-39-rotation/specs/agent-credentials/spec.md rename to openspec/changes/archive/2026-11-14-pep-39-rotation/specs/agent-credentials/spec.md diff --git a/openspec/changes/pep-39-rotation/specs/subscription-rotation/spec.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/specs/subscription-rotation/spec.md similarity index 100% rename from openspec/changes/pep-39-rotation/specs/subscription-rotation/spec.md rename to openspec/changes/archive/2026-11-14-pep-39-rotation/specs/subscription-rotation/spec.md diff --git a/openspec/changes/pep-39-rotation/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/specs/web-workspace/spec.md similarity index 100% rename from openspec/changes/pep-39-rotation/specs/web-workspace/spec.md rename to openspec/changes/archive/2026-11-14-pep-39-rotation/specs/web-workspace/spec.md diff --git a/openspec/changes/pep-39-rotation/tasks.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md similarity index 100% rename from openspec/changes/pep-39-rotation/tasks.md rename to openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md index a2b59659..532df4b8 100644 --- a/openspec/specs/agent-credentials/spec.md +++ b/openspec/specs/agent-credentials/spec.md @@ -74,10 +74,11 @@ - **THEN** изменение отклонено ### Requirement: Подписка сессии -Раннер SHALL при старте брать первую свободную активную подписку из выбранного набора +Раннер SHALL при старте брать свободную активную подписку из выбранного набора (отмеченные подписки или пул из формы запуска, иначе пул проекта) и запоминать её у сессии; провайдер сессии — провайдер подписки, процесс агента получает вход этой подписки. Resume -SHALL идти на той же подписке. Без пула и выбора сессия запускается на входе машины. +SHALL идти на той же подписке, а при лимите сессия может переключиться на другую подписку +пула (ротация). Без пула и выбора сессия запускается на входе машины. #### Scenario: Свободная подписка - **GIVEN** в пуле проекта подписки «A» и «B», на «A» уже работает сессия diff --git a/openspec/specs/subscription-rotation/spec.md b/openspec/specs/subscription-rotation/spec.md new file mode 100644 index 00000000..6d8cf33d --- /dev/null +++ b/openspec/specs/subscription-rotation/spec.md @@ -0,0 +1,66 @@ +# subscription-rotation Specification + +## Purpose +TBD - created by archiving change pep-39-rotation. Update Purpose after archive. + +## Requirements + +### Requirement: Лимит помечает подписку +Когда сессия упирается в лимит (StopFailure `rate_limit` или баннер лимита), её подписка +SHALL получать статус «лимит до <время сброса>». Новые сессии и переключения SHALL не +попадать на подписку, пока её лимит не сброшен. + +#### Scenario: Лимит на подписке +- **GIVEN** раннер стори работает на подписке «Claude A» +- **WHEN** Claude сообщает о лимите со временем сброса 17:00 +- **THEN** «Claude A» в «Подписках» показывает «лимит до 17:00», и новый раннер проекта стартует не на ней + +### Requirement: Переключение на свободную подписку пула +Сессия, упёршаяся в лимит, SHALL перезапускаться на другой пригодной подписке того же +провайдера из пула на границе хода: Claude и OpenCode — с продолжением того же разговора, +Codex — новым запуском с подсказкой восстановить контекст из стори (история Codex между +аккаунтами не переносится). Если свободных подписок нет, сессия SHALL ждать сброса и +продолжать сама (как без ротации), а если подписка освободится раньше — переключаться на неё. + +#### Scenario: Есть свободная подписка +- **GIVEN** в пуле проекта подписки Claude «A» и «B», раннер работает на «A» +- **WHEN** на «A» случается лимит +- **THEN** раннер продолжает тот же разговор на «B», PM получает «переключил с подписки A на B» + +#### Scenario: Свободных подписок нет +- **GIVEN** в пуле проекта только подписка «A», раннер на ней упёрся в лимит до 17:00 +- **WHEN** вачдог проверяет раннер +- **THEN** раннер стоит до сброса и продолжает сам после 17:01 + +#### Scenario: Codex +- **GIVEN** в пуле две подписки Codex, раннер Codex упёрся в лимит на первой +- **WHEN** вачдог переключает раннер +- **THEN** он запускается на второй подписке новым запуском без resume, с подсказкой восстановить контекст из стори + +### Requirement: Переключение по порогу использования +Когда CLI предупреждает, что использование подписки подходит к лимиту (не ниже порога, 85 %), +сессия SHALL дожить до конца хода и затем переключиться на подписку пула без сессий; если +такой нет — работать дальше. + +#### Scenario: Предупреждение о пороге +- **GIVEN** раннер на подписке «A», в пуле есть свободная «B» +- **WHEN** на экране появляется «approaching usage limit» и ход заканчивается +- **THEN** раннер не подталкивается дальше, а продолжает разговор на «B» + +### Requirement: Не больше N переключений +Сессия SHALL переключаться не чаще `PEPPA_ROTATE_MAX_PER_HOUR` (3) раз в час и никогда — на +подписку с действующим лимитом или ошибкой входа. Предел исчерпан — сессия ждёт сброса. + +#### Scenario: Предел переключений +- **GIVEN** раннер уже переключался 3 раза за последний час +- **WHEN** он снова упирается в лимит при свободной подписке в пуле +- **THEN** раннер не переключается, а ждёт сброса лимита + +### Requirement: Справедливость между проектами +Проект, уже занимающий не меньше `PEPPA_POOL_PROJECT_MAX` (2) подписок пула, SHALL не +получать ещё одну свободную подписку, пока в пуле ждёт сброса лимита сессия другого проекта. + +#### Scenario: Очередь в пуле +- **GIVEN** проект X занимает 2 подписки пула, сессия проекта Y ждёт сброса лимита, в пуле свободна «C» +- **WHEN** сессия X упирается в лимит +- **THEN** X не переключается на «C», а вачдог отдаёт «C» сессии Y diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md index 0c22f752..cd9b4ae3 100644 --- a/openspec/specs/web-workspace/spec.md +++ b/openspec/specs/web-workspace/spec.md @@ -300,3 +300,13 @@ SHALL показывать, на какой подписке работает с - **GIVEN** у отмеченной подписки статус «ошибка входа», других не отмечено - **WHEN** суперадмин запускает агента - **THEN** запуск отклонён с сообщением «Нет активных подписок» + +### Requirement: Подписка и переключения сессии в вебе +«Раннеры» SHALL показывать подписку сессии, ожидание переключения на границе хода и историю +переключений (с какой, на какую, почему); карточка сессии на странице стори — подписку и +число переключений; «Подписки» — сколько сессий на подписке по проектам и статус лимита. + +#### Scenario: История переключений +- **GIVEN** раннер переключился с «Claude A» на «Claude B» из-за лимита +- **WHEN** PM открывает его в «Раннерах» +- **THEN** он видит подписку «Claude B» и запись «Claude A → Claude B · лимит» -- 2.45.2 From 5ff738c9776e8bb0135849be7b48fc88b2f49654 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 05:15:43 +0500 Subject: [PATCH 007/472] PEP-39: migration renumbered to 0005 after PEP-26 Co-Authored-By: Claude Opus 5.5 --- openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md | 2 +- openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md index 0e56da20..c28ec727 100644 --- a/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md +++ b/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md @@ -38,7 +38,7 @@ ## Impact -- Схема: `sessions.rotate_reason` (миграция 0004). +- Схема: `sessions.rotate_reason` (миграция 0005). - `packages/core` (subscriptions: пометка лимита, выбор для ротации, справедливость; sessions: число переключений), `packages/runner` (rotation.ts, limits, watchdog, hook), веб (RunnerConsole, SessionCard, Подписки, события стори), `packages/testkit` diff --git a/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md index 73d37b04..de2b3d66 100644 --- a/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md +++ b/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md @@ -1,7 +1,7 @@ # Tasks: PEP-39 ## 1. Данные и core -- [x] 1.1 Схема `sessions.rotate_reason` + миграция 0004 +- [x] 1.1 Схема `sessions.rotate_reason` + миграция 0005 - [x] 1.2 core: пометка лимита подписки, кандидаты для ротации, справедливость в pickSubscription, `subscriptionSwitches` в SessionView, сессии по проектам в listSubscriptions ## 2. Раннер -- 2.45.2 From 634e40a02c545e2f6792c9f72be1d7a2ba0e0a47 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 05:26:57 +0500 Subject: [PATCH 008/472] PEP-39: migration 0006 after PEP-29; switch message goes through notification preferences (failures event) Co-Authored-By: Claude Opus 5.5 --- openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md | 2 +- openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md index c28ec727..d56973a4 100644 --- a/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md +++ b/openspec/changes/archive/2026-11-14-pep-39-rotation/proposal.md @@ -38,7 +38,7 @@ ## Impact -- Схема: `sessions.rotate_reason` (миграция 0005). +- Схема: `sessions.rotate_reason` (миграция 0006). - `packages/core` (subscriptions: пометка лимита, выбор для ротации, справедливость; sessions: число переключений), `packages/runner` (rotation.ts, limits, watchdog, hook), веб (RunnerConsole, SessionCard, Подписки, события стори), `packages/testkit` diff --git a/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md b/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md index de2b3d66..11865bdf 100644 --- a/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md +++ b/openspec/changes/archive/2026-11-14-pep-39-rotation/tasks.md @@ -1,7 +1,7 @@ # Tasks: PEP-39 ## 1. Данные и core -- [x] 1.1 Схема `sessions.rotate_reason` + миграция 0005 +- [x] 1.1 Схема `sessions.rotate_reason` + миграция 0006 - [x] 1.2 core: пометка лимита подписки, кандидаты для ротации, справедливость в pickSubscription, `subscriptionSwitches` в SessionView, сессии по проектам в listSubscriptions ## 2. Раннер -- 2.45.2 From 4a80d9dc6b4a6f2e4fa403e3d7183b21149622ba 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 05:59:15 +0500 Subject: [PATCH 009/472] PEP-32/33/37: story page tabs, live agent step feed, SSE live updates instead of 5 s polling - PEP-37: change hub (runner/live.ts) woken by notify() (new 'web' subscriber) and PRAGMA data_version; per-scope fingerprints; GET /api/live SSE (no-transform, ping 15 s); LiveRefresh replaces AutoRefresh with a connection indicator and polling fallback - PEP-33: async PostToolUse/PostToolUseFailure hook -> 'step' events (last 200 per session), AgentSteps live feed on the story page and runner panel, tasks.md progress on board cards and the story header - PEP-32: story page header + tabs Proposal/Design/Specs/Tasks/Comments/Tests/Merge request/Activity, safe Markdown renderer, PM comments visible in get_task, edit title/description/epic, accept-and-merge (acceptStory) - OpenSpec changes archived; specs live-updates, agent-steps, story-page Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- apps/web/app/(app)/actions.ts | 43 +- apps/web/app/(app)/help/page.tsx | 2 +- apps/web/app/(app)/p/[key]/page.tsx | 25 +- apps/web/app/(app)/page.tsx | 4 +- apps/web/app/(app)/runners/page.tsx | 8 +- apps/web/app/(app)/t/[key]/page.tsx | 346 +++++++++------ apps/web/app/(app)/t/[key]/tabs.tsx | 406 ++++++++++++++++++ apps/web/app/api/live/route.ts | 21 + apps/web/components/AgentSteps.tsx | 88 ++++ apps/web/components/Board.tsx | 26 ++ apps/web/components/LiveRefresh.tsx | 125 ++++++ apps/web/components/Markdown.tsx | 172 ++++++++ apps/web/components/RunnerConsole.tsx | 13 +- apps/web/components/cards.tsx | 7 +- apps/web/lib/queries.ts | 27 +- .../.openspec.yaml | 2 + .../2026-11-14-pep-32-story-tabs/design.md | 15 + .../2026-11-14-pep-32-story-tabs/proposal.md | 36 ++ .../specs/story-page/spec.md | 52 +++ .../2026-11-14-pep-32-story-tabs/tasks.md | 18 + .../.openspec.yaml | 2 + .../2026-11-14-pep-33-agent-steps/design.md | 15 + .../2026-11-14-pep-33-agent-steps/proposal.md | 31 ++ .../specs/agent-steps/spec.md | 38 ++ .../2026-11-14-pep-33-agent-steps/tasks.md | 19 + .../.openspec.yaml | 2 + .../2026-11-14-pep-37-live-events/design.md | 26 ++ .../2026-11-14-pep-37-live-events/proposal.md | 34 ++ .../specs/live-updates/spec.md | 37 ++ .../2026-11-14-pep-37-live-events/tasks.md | 15 + openspec/specs/agent-steps/spec.md | 43 ++ openspec/specs/live-updates/spec.md | 42 ++ openspec/specs/story-page/spec.md | 57 +++ packages/core/src/index.ts | 2 + packages/core/src/notify.ts | 4 +- packages/core/src/openspec.ts | 167 +++++++ packages/core/src/steps.ts | 98 +++++ packages/core/src/tasks.ts | 42 +- packages/mcp/src/format.ts | 5 + packages/mcp/src/manager.ts | 2 +- packages/runner/src/flow.ts | 16 +- packages/runner/src/hook.ts | 10 + packages/runner/src/index.ts | 1 + packages/runner/src/live.ts | 298 +++++++++++++ packages/runner/src/run-settings.ts | 4 + packages/testkit/test/story-live.test.ts | 251 +++++++++++ 47 files changed, 2525 insertions(+), 175 deletions(-) create mode 100644 apps/web/app/(app)/t/[key]/tabs.tsx create mode 100644 apps/web/app/api/live/route.ts create mode 100644 apps/web/components/AgentSteps.tsx create mode 100644 apps/web/components/LiveRefresh.tsx create mode 100644 apps/web/components/Markdown.tsx create mode 100644 openspec/changes/archive/2026-11-14-pep-32-story-tabs/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-14-pep-32-story-tabs/design.md create mode 100644 openspec/changes/archive/2026-11-14-pep-32-story-tabs/proposal.md create mode 100644 openspec/changes/archive/2026-11-14-pep-32-story-tabs/specs/story-page/spec.md create mode 100644 openspec/changes/archive/2026-11-14-pep-32-story-tabs/tasks.md create mode 100644 openspec/changes/archive/2026-11-14-pep-33-agent-steps/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-14-pep-33-agent-steps/design.md create mode 100644 openspec/changes/archive/2026-11-14-pep-33-agent-steps/proposal.md create mode 100644 openspec/changes/archive/2026-11-14-pep-33-agent-steps/specs/agent-steps/spec.md create mode 100644 openspec/changes/archive/2026-11-14-pep-33-agent-steps/tasks.md create mode 100644 openspec/changes/archive/2026-11-14-pep-37-live-events/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-14-pep-37-live-events/design.md create mode 100644 openspec/changes/archive/2026-11-14-pep-37-live-events/proposal.md create mode 100644 openspec/changes/archive/2026-11-14-pep-37-live-events/specs/live-updates/spec.md create mode 100644 openspec/changes/archive/2026-11-14-pep-37-live-events/tasks.md create mode 100644 openspec/specs/agent-steps/spec.md create mode 100644 openspec/specs/live-updates/spec.md create mode 100644 openspec/specs/story-page/spec.md create mode 100644 packages/core/src/openspec.ts create mode 100644 packages/core/src/steps.ts create mode 100644 packages/runner/src/live.ts create mode 100644 packages/testkit/test/story-live.test.ts diff --git a/AGENTS.md b/AGENTS.md index d1e75f7f..5fb61cbf 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=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один 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` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (PEP-32): шапка (статус, эпик, прогресс tasks.md, «Изменить» — название/описание/эпик, агент и живая сессия с терминалом и лентой шагов) и вкладки `?tab=` Proposal · Design (свой безопасный рендер `components/Markdown.tsx`) · Specs (дельта-спеки change) · Tasks · Comments (вопросы + комментарии PM: событие `pm_comment`, агент видит в `get_task`, флажок «Отправить агенту сейчас») · Tests · Merge request («Принять и смержить» = `acceptStory` в runner/flow.ts) · Activity (с авторами: `payload.login` / сессия / система); change читает `core/openspec.ts` (`readChange`, `parseTasks`, `taskProgress`, и архивный); новый проект. **Живые страницы (PEP-37)**: `LiveRefresh` (вместо `AutoRefresh`, он остался только у подписок) слушает SSE `GET /api/live?scope=home|runners|project:|task:|steps:` и делает `router.refresh()` (ждёт, пока пользователь печатает), индикатор связи, откат на опрос 5 с; хаб `runner/live.ts` (`globalThis`) будят `notify()` (подписчик `web`, сокет `$PEPPA_HOME/web.events.sock`) и `PRAGMA data_version` + `total_changes()` раз в секунду, отпечаток области — один SQL без `last_activity_at`/шагов; заголовки `no-cache, no-transform`, `X-Accel-Buffering: no`, пинг 15 с **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже) - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `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`) @@ -17,6 +17,7 @@ - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` - Терминал в вебе (PEP-9): `runner/terminal.ts` — `TerminalFeed` опрашивает pane (`capture-pane -e` + `display-message`, 250 мс, один цикл на раннер для всех зрителей, `globalThis`), шлёт изменившиеся строки и ушедшие в историю; `terminalInput` (`send-keys -H` / `paste-buffer -p`; только владелец/участник, живая сессия, ≤1 КБ нажатий / 64 КБ вставки, 40 запросов за 5 с, сброс `auto_nudges`, событие `terminal_input` раз в минуту). Веб: `GET/POST /api/runners//terminal` (SSE + JSON, пинг 15 с для Cloudflare), `components/RunnerTerminal.tsx` (xterm.js); pane браузер не ресайзит + - Шаги агента (PEP-33): хуки `PostToolUse`/`PostToolUseFailure` с `async: true` → `peppa-hook tool-use` → `recordStep` (core/steps.ts: событие `step` `{tool, kind, text, ok}`, последние 200 на сессию, `last_activity_at` без `notify()`); шаги исключены из журнала стори, `get_task` и «Событий» раннера; лента — `components/AgentSteps.tsx` (у живой сессии на странице стори и в панели раннера, новые шаги — событием `step` из `/api/live?scope=steps:`); прогресс tasks.md («7/12» и текущий пункт) — на карточках доски «В работе» и в шапке стори. Codex/OpenCode шагов не шлют - хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s-g/settings.json` (`claude --settings`) - `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется - PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index c35d9033..70401e0a 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -38,10 +38,13 @@ import { sendWebPush, setNotifyPrefs, userPushSubscriptions, + addStoryComment, + updateTask, + listSessions, } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; -import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { acceptStory, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -123,6 +126,44 @@ export async function editEpic(f: FormData) { }); } +/** Story page (PEP-32): title, description and epic from the web; no agent is started. */ +export async function editStoryAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await resolveTask(db, str(f, "taskKey")); + await projectForUser(db, user.id, ref.project.id); + const title = str(f, "title"); + if (title.length < 2) throw new PeppaError("Нужно название стори"); + const epic = str(f, "epicId"); + await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login); + }); +} + +/** PM comment on a story (PEP-32): the agent sees it in get_task; optionally typed into the live runner. */ +export async function commentStoryAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await resolveTask(db, str(f, "taskKey")); + await projectForUser(db, user.id, ref.project.id); + const c = await addStoryComment(db, ref, user, String(f.get("text") ?? "")); + if (str(f, "toAgent")) { + const [live] = await listSessions(db, { active: true, taskId: ref.task.id }); + if (!live) throw new PeppaError("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task"); + await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`); + } + }); +} + +/** «Принять и смержить» on the story's merge request tab (PEP-32): the same gate as «Принять». */ +export async function acceptStoryAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await resolveTask(db, str(f, "taskKey")); + await projectForUser(db, user.id, ref.project.id); + await acceptStory(db, ref, "web"); + }); +} + export async function startTaskSession(f: FormData) { const user = await requireUser(); await attempt(f, async () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index da9ae610..ac9331ae 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -8,7 +8,7 @@ const TOOLS: Array<[string, string]> = [ ["create_project", "новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"], ["list_epics / create_epic / update_epic", "эпики проекта (метки стори): завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"], ["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"], - ["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, прогресс"], + ["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, прогресс"], ["create_task / update_task", "завести стори (в Бэклог, с эпиком epic_id); поправить название, описание, эпик"], ["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"], ["set_project_visibility", "сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий"], diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index f50ebfe6..c2ac9c13 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,8 +1,8 @@ import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket } from "lucide-react"; import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner"; -import { getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; -import { AutoRefresh } from "@/components/AutoRefresh"; +import { taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Board, type Card } from "@/components/Board"; import { Hidden, SessionCard } from "@/components/cards"; @@ -98,13 +98,18 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const epicTitle = new Map(epics.map((e) => [e.id, e.title])); const cards: Card[] = tasks .filter((t) => !epicFilter || t.goalId === epicFilter.id) - .map((t) => ({ - key: `${p.key}-${t.number}`, - title: t.title, - status: t.status, - column: columnOf(t.status), - epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null, - })); + .map((t) => { + const pr = columnOf(t.status) === "in_progress" ? taskProgress(p, t.openspecChange) : null; + return { + key: `${p.key}-${t.number}`, + title: t.title, + status: t.status, + column: columnOf(t.status), + epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null, + // PEP-33: tasks.md progress of stories in work. + progress: pr && { done: pr.done, total: pr.total, current: pr.current }, + }; + }); // 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) : []; @@ -284,7 +289,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr return ( - + {created && !error && ( diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 4a9d6330..282423f9 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -1,5 +1,5 @@ import { listUserProjects } from "@peppa/core"; -import { AutoRefresh } from "@/components/AutoRefresh"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { ActivityAside } from "@/components/ActivityAside"; import { ProjectList, QuestionCard, SessionCard } from "@/components/cards"; import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common"; @@ -14,7 +14,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e const [items, sessions, projects] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id)]); return ( }> - + {items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}
    diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx index a7be1542..5a961a88 100644 --- a/apps/web/app/(app)/runners/page.tsx +++ b/apps/web/app/(app)/runners/page.tsx @@ -1,7 +1,7 @@ import Link from "next/link"; import { Search } from "lucide-react"; -import { listUserSessions, RUNNER_FILTERS, type RunnerFilter, type SessionView } from "@peppa/core"; -import { AutoRefresh } from "@/components/AutoRefresh"; +import { listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { Empty, Flash, PageHeader } from "@/components/common"; import { RunnerDetails, RunnerRow } from "@/components/RunnerConsole"; import { Input } from "@/components/ui/input"; @@ -52,12 +52,12 @@ export default async function Runners({ searchParams }: { searchParams: Promise< const selected = (id && all.find((s) => s.id === Number(id))) || shown[0]; const back = url({ ...base, id: selected?.id }); const aside = selected ? ( - + ) : null; return ( - + Агенты в tmux по стори твоих и общих проектов: кто ждёт тебя, кто работает, что готово.
    diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index 8be73a92..f9413c46 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -1,97 +1,117 @@ +// 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 Link from "next/link"; import { notFound } from "next/navigation"; -import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react"; -import { FINISHED_SESSION_STATUSES, getEpic, isSuperadmin, latestReview, listPools, listSubscriptions, projectPool, PROVIDER_NAMES, reviewLabel, taskCiSummary } from "@peppa/core"; -import { AutoRefresh } from "@/components/AutoRefresh"; +import { CircleCheck, CircleX, GitPullRequest, Hourglass, Pencil, Play } from "lucide-react"; +import { + FINISHED_SESSION_STATUSES, + getEpic, + isSuperadmin, + latestReview, + listEpics, + listPools, + listSubscriptions, + parseTasks, + prGate, + projectPool, + PROVIDER_NAMES, + readChange, + reviewLabel, + sessionSteps, + storyComments, + taskCiSummary, + type GateResult, +} from "@peppa/core"; +import { checkRuns } from "@peppa/db"; +import { desc, eq } from "drizzle-orm"; import { PanelSection } from "@/components/ActivityAside"; -import { Hidden, QuestionCard, SessionCard } from "@/components/cards"; -import { eventLine } from "@/components/RunnerConsole"; -import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common"; +import { Hidden, SessionCard } from "@/components/cards"; +import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { Button } from "@/components/ui/button"; -import { Input, NativeSelect } from "@/components/ui/input"; +import { Input, NativeSelect, Textarea } from "@/components/ui/input"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries"; -import { startTaskSession } from "../../actions"; +import { taskActivity, taskForUser } from "@/lib/queries"; +import { cn } from "@/lib/utils"; +import { editStoryAction, startTaskSession } from "../../actions"; +import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs"; const CI_ICON = { success: , failure: , pending: }; -export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) { +/** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */ +async function gateWithTimeout(ref: Parameters[0]): Promise { + return Promise.race([prGate(ref).catch(() => null), new Promise((r) => setTimeout(() => r(null), 5000))]); +} + +export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; tab?: string; edit?: string }> }) { const user = await requireUser(); const { key } = await params; - const { error } = await searchParams; + const sp = await searchParams; const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null); if (!ref) notFound(); const { task, project } = ref; const { questions, sessions, events } = await taskActivity(task.id); - const liveId = sessions.find((s) => !FINISHED_SESSION_STATUSES.includes(s.status))?.id; - const artifacts = openspecArtifacts(project, task.openspecChange); + const live = sessions.find((s) => !FINISHED_SESSION_STATUSES.includes(s.status)) ?? null; + const past = sessions.filter((s) => s !== live); + const change = readChange(project, task.openspecChange); + const progress = change?.tasks ? parseTasks(change.tasks) : null; const ci = await taskCiSummary(db, ref); const review = await latestReview(db, task.id); - const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null; - const back = `/t/${ref.key}`; + const epics = await listEpics(db, project.id); + const epic = task.goalId ? (epics.find((e) => e.id === task.goalId) ?? (await getEpic(db, project.id, task.goalId).catch(() => null))) : null; + const tab: StoryTab = STORY_TABS.find((t) => t.id === sp.tab)?.id ?? (change ? "proposal" : "comments"); + const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`; + const back = tabHref(tab); // PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool. const superadmin = await isSuperadmin(db, user); const pool = await projectPool(db, project.id); const [pools, subs] = superadmin ? await Promise.all([listPools(db), listSubscriptions(db)]) : [[], []]; + const steps = live ? await sessionSteps(db, live.id) : undefined; + + // Only the open tab reads the rest (Gitea for the merge request). + const comments = tab === "comments" ? await storyComments(db, task.id) : []; + 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)) + : []; + const gate = tab === "merge" && task.prUrl ? await gateWithTimeout(ref) : null; + const openQuestions = questions.filter((q) => !q.answeredAt).length; + const counts: Partial> = { + specs: change?.specs.length || undefined, + tasks: progress?.total ? `${progress.done}/${progress.total}` : undefined, + comments: openQuestions || undefined, + }; const aside = (
    -
    + {CI_ICON[ci.state as keyof typeof CI_ICON]} - {ci.runUrl ? {ci.label} : ci.label} + {ci.label} {ci.sha && {ci.sha.slice(0, 7)}} -
    + {task.ciAttempts > 0 &&

    красных подряд: {task.ciAttempts}

    } - {ci.failed.map((f) => ( - - - {f.check} - {f.runUrl && лог} - - } - > - {f.logTail &&
    {f.logTail.split("\n").slice(-60).join("\n")}
    } -
    - ))}
    {review && ( -
    - {review.verdict === "ok" ? : review.verdict === "changes" || review.state === "error" ? : } - {reviewLabel(review)} - {review.sha.slice(0, 7)} -
    - {review.findings.length > 0 && ( -
      - {review.findings.map((f, i) => ( -
    • - {f.file && {f.file}{f.line ? `:${f.line}` : ""} — } - {f.text} -
    • - ))} -
    - )} -

    {ago(review.updatedAt)}

    +

    {reviewLabel(review)}

    +

    + {review.sha.slice(0, 7)} · {ago(review.updatedAt)} +

    )} - + {events.length === 0 ? (

    Событий нет.

    ) : ( -
      - {events.map((e) => ( -
    1. - {ago(e.createdAt)} {e.type}{" "} - {eventLine(e)} -
    2. - ))} -
    + <> + + + Вся активность → + + )}
    @@ -99,8 +119,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom return ( - - + + @@ -121,78 +141,164 @@ export default async function StoryPage({ params, searchParams }: { params: Prom } actions={ - task.prUrl && ( - - ) + {task.prUrl && ( + + )} + } - /> -
    {task.description || Без описания}
    + > + + {task.openspecChange ? ( + + {task.openspecChange} + {change?.archived && в архиве} + + ) : ( + change ещё нет + )} + {progress?.total ? ( + + + + ) : null} + +
    -
    -
    + {sp.edit ? ( + - - - - - - - {superadmin && ( - - - {pools.filter((p) => p.id !== pool?.id).map((p) => ( - + +