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 001/468] 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 002/468] 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 003/468] 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 004/468] 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 005/468] 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) => ( - + +