From 517f65e1ecf7a6366512f790dc83f19cc8524137 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:23:25 +0500 Subject: [PATCH 001/185] PEP-157: CI runner takes four jobs at once instead of two Co-Authored-By: Claude Fable 5.2 --- infra/act-runner/config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/infra/act-runner/config.yaml b/infra/act-runner/config.yaml index 03fe7506..1bb93df3 100644 --- a/infra/act-runner/config.yaml +++ b/infra/act-runner/config.yaml @@ -3,8 +3,8 @@ log: level: info runner: file: .runner - # Mac — и сборка, и стенды: не больше 2 job одновременно на регистрацию. - capacity: 2 + # Mac (24 ядра, 64 ГБ) — и сборка, и стенды. Было 2: при 13 открытых PR очередь проверок росла на часы (PEP-157). + capacity: 4 timeout: 1h fetch_timeout: 5s fetch_interval: 2s -- 2.45.2 From f05a5ee4988a730e73e0bbdec6b34fd9ac7f71df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:15:21 +0500 Subject: [PATCH 002/185] =?UTF-8?q?PEP-157:=20OpenSpec=20change,=20=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0=20capacity=20=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=BD=D0=B5=D1=80=D0=B0=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=BA,=20AGENTS.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 2 +- .../pep-157-ci-runner-capacity/design.md | 11 ++++++++++ .../pep-157-ci-runner-capacity/proposal.md | 14 ++++++++++++ .../specs/peppa-ci/spec.md | 22 +++++++++++++++++++ .../pep-157-ci-runner-capacity/tasks.md | 10 +++++++++ .../testkit/test/ci-runner-config.test.ts | 14 ++++++++++++ 6 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/pep-157-ci-runner-capacity/design.md create mode 100644 openspec/changes/pep-157-ci-runner-capacity/proposal.md create mode 100644 openspec/changes/pep-157-ci-runner-capacity/specs/peppa-ci/spec.md create mode 100644 openspec/changes/pep-157-ci-runner-capacity/tasks.md create mode 100644 packages/testkit/test/ci-runner-config.test.ts diff --git a/AGENTS.md b/AGENTS.md index fbb085b2..77843525 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ - **Сообщение о новом пользователе (PEP-113)**: `core/new-users.ts` `announceNewUser(db, user, via)` — зовут сами функции создания учётки (`registerEgovUser`, `registerGoogleUser`, `createLocalUser`) после успешной вставки; получатели — `platformAdmins` кроме новичка и автора (`currentActor().userId`), событие уведомлений `users` («Новые пользователи (админам)», строка в настройках — только суперадмину, как `monitoring`), ключ outbox `newuser::`, ИИН в текст не идёт, не бросает. Новый способ регистрации — добавить вызов. Тест `new-users.test.ts` - **Канал платформы и дайджест Пеппы (PEP-60)**: `core/platform-channel.ts`, настройки в `settings` `platform.telegram_channel` (Chat ID, `check` — результат `checkPlatformChannel`: Bot API `getMe`→`getChat`→`getChatMember`, «бот не видит канал — добавьте его администратором» / нет права публикации; события releases/services/digest; `digest.time/timezone/users`, личные чаты по умолчанию выкл). В канал пишет только при `check.ok` (`postToChannel`, outbox; сервисные ключи `mon:ch:*` — вачдог доставит сам, если упал бот); неработающий канал вачдог перепроверяет раз в час (`recheckPlatformChannel`). События: `checkServices` — одно «не отвечает» и одно «снова работает — простой N мин» на простой, «перезапущен» при смене процесса без простоя (`monitor.process:`, heartbeat несёт `commit`); `platformBuildTick` (runner/platform-build.ts) — HEAD корня ≠ `platform.build` и входит в `main` → «🚀 Peppa vX · sha» + стори из коммитов (первый раз только запоминает). `platformDigestTick` (вачдог): «Что нового» (done-стори `PEPPA_PLATFORM_KEY`, сборки) + «Сейчас» (версия, сервисы, раннеры, вопросы, лимиты), пустой не шлётся, в канал и пользователям событием уведомлений `platform`. Веб `/platform` (суперадмин), CLI `peppa platform channel chat= [k=v…]|check`, `peppa platform digest [now]`. Мок — каналы в `mock-telegram` (`addChannel`) - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` -- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) +- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/` — `capacity: 4` job одновременно на регистрацию (PEP-157; меняется перезапуском контейнера, тест `ci-runner-config.test.ts`), контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) - **Gitea → Пеппа (PEP-46)**: вебхук подписан на `GITEA_HOOK_EVENTS` (+ issues, issue_comment, pull_request_comment, pull_request_review; обновить у существующих — `peppa ci connect `); `handleGiteaEvent` (runner/gitea-events.ts) определяет событие по форме payload (Gitea 1.22 зовёт и ревью, и комментарий `pull_request_comment`). Issue от владельца/участника (логин Gitea, `users.gitea_id > 0`) → стори в бэклоге (`tasks.gitea_issue`, идемпотентно) + комментарий-ссылка от peppa-bot; чужие игнор; `moveTask(done)` закрывает issue; разовый импорт `peppa project import-issues ` (без проверки автора). Комментарий/ревью «нужны изменения» в PR стори → агенту (живой раннер или новый, из «Ревью» — в работу); одобрения и `GITEA_BOT_LOGIN` (peppa-bot) — игнор. PR смержен руками → стори done, «готово к ревью» закрыт (`acceptTask` терпит гонку с вебхуком) - **Превью на ревью (PEP-44)**: `reviewPreview` (core/preview.ts) — здоровый превью-стенд PR стори из `releases`, дифф `/files`, итог проверок, скриншоты, issue; в «готово к ревью» (Stop-хук, ревьюер), карточке (`components/ReviewPreview.tsx`) и `get_task`. Скриншоты снимает `peppa-deploy.sh preview` (headless Chromium в контейнере `PEPPA_SCREENSHOT_IMAGE`, сеть Traefik, base64 через stdout; страницы `deploy.screenshots`, по умолчанию `["/"]`) → `X-Peppa-Event: screenshots` → `recordScreenshots` (`$PEPPA_HOME/screenshots//`, ≤6×3 МБ, PNG) → `releases.screenshots`; веб `/api/releases//shots/` (владелец/участник) diff --git a/openspec/changes/pep-157-ci-runner-capacity/design.md b/openspec/changes/pep-157-ci-runner-capacity/design.md new file mode 100644 index 00000000..2a3652a6 --- /dev/null +++ b/openspec/changes/pep-157-ci-runner-capacity/design.md @@ -0,0 +1,11 @@ +## Context +`act_runner` в контейнере `peppa-act-runner` держит по демону на регистрацию (`peppa-bot`, `repo-peppa--peppa`), общий конфиг — `infra/act-runner/config.yaml`. `capacity` — число job одновременно на одну регистрацию. + +## Decisions +- **`capacity: 4`**, а не больше: одна проверка платформы (`next build` + e2e) занимает 2–4 ядра и несколько ГБ; две регистрации × 4 = до 8 job на 24 ядрах и 64 ГБ оставляют место живому сайту, агентам и стендам проектов. Наборы e2e изолированы (свой SQLite, tmux, `PEPPA_HOME`), параллельность им не мешает. +- **Тест на значение конфига** (чтение YAML строкой, без новой зависимости): значение — единственная «логика» стори, откат на 2 иначе пройдёт незамеченным. +- Вторую регистрацию или отдельный хост под CI не заводим — это отдельная стори, если четырёх не хватит. + +## Risks +- Конфиг читается демоном при старте: без перезапуска контейнера ничего не меняется. На живой системе значение уже применено (контейнер перезапущен, одновременно идут четыре проверки платформы). +- Файл конфига смонтирован в контейнер как одиночный файл: после того как git переписывает его, внутри контейнера он пропадает до перезапуска — заведена отдельная стори. diff --git a/openspec/changes/pep-157-ci-runner-capacity/proposal.md b/openspec/changes/pep-157-ci-runner-capacity/proposal.md new file mode 100644 index 00000000..a99d4549 --- /dev/null +++ b/openspec/changes/pep-157-ci-runner-capacity/proposal.md @@ -0,0 +1,14 @@ +## Why +При 13 открытых PR и восьми работающих агентах раннер проверок брал по две job на регистрацию: очередь растягивалась на часы, агенты слали PM «проверки 0 из 4». На сервере 24 ядра и 64 ГБ — запас есть. + +## What Changes +- `infra/act-runner/config.yaml`: `runner.capacity` 2 → 4 (на каждую регистрацию раннера). +- Тест, который держит это значение, чтобы его не вернули случайно. + +## Capabilities +### Modified Capabilities +- `peppa-ci`: новое требование — раннер берёт до четырёх проверок одновременно. + +## Impact +- `infra/act-runner/config.yaml`, тест `packages/testkit/test/ci-runner-config.test.ts`, AGENTS.md. +- Живой раннер: значение применяется при перезапуске контейнера `peppa-act-runner` (`scripts/infra-up.sh act-runner` / `docker restart`). diff --git a/openspec/changes/pep-157-ci-runner-capacity/specs/peppa-ci/spec.md b/openspec/changes/pep-157-ci-runner-capacity/specs/peppa-ci/spec.md new file mode 100644 index 00000000..dacd2d5c --- /dev/null +++ b/openspec/changes/pep-157-ci-runner-capacity/specs/peppa-ci/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: Очередь проверок — четыре одновременно +Раннер проверок Пеппы (`infra/act-runner/config.yaml`) SHALL брать до четырёх job одновременно +на каждую регистрацию (`runner.capacity: 4`), чтобы при десятке открытых PR проверки не ждали +в очереди часами. + +#### Scenario: Четыре PR сразу +- **GIVEN** раннер `peppa-trusted` свободен +- **AND** в репозитории `peppa/peppa` одновременно запушены ветки четырёх PR +- **WHEN** Gitea ставит четыре job `peppa-ci / ci` в очередь +- **THEN** все четыре job выполняются одновременно, ни одна не ждёт в очереди + +#### Scenario: Пятая проверка ждёт +- **GIVEN** регистрация раннера выполняет четыре job +- **WHEN** в очередь приходит пятая job этого же репозитория +- **THEN** пятая job остаётся в ожидании, пока не закончится одна из четырёх + +#### Scenario: Значение вернули к двум +- **GIVEN** в `infra/act-runner/config.yaml` записано `capacity: 2` +- **WHEN** запускается тест `ci-runner-config.test.ts` +- **THEN** тест падает с сообщением «runner.capacity must be at least 4» diff --git a/openspec/changes/pep-157-ci-runner-capacity/tasks.md b/openspec/changes/pep-157-ci-runner-capacity/tasks.md new file mode 100644 index 00000000..1693103f --- /dev/null +++ b/openspec/changes/pep-157-ci-runner-capacity/tasks.md @@ -0,0 +1,10 @@ +## 1. Конфиг +- [x] 1.1 `infra/act-runner/config.yaml`: `capacity: 4` с пояснением + +## 2. Проверка +- [x] 2.1 Тест `ci-runner-config.test.ts`: `runner.capacity` не меньше 4 +- [x] 2.2 Живой раннер: контейнер перезапущен, четыре проверки идут одновременно +- [ ] 2.3 lint, typecheck, build, тесты зелёные + +## 3. Завершение +- [ ] 3.1 AGENTS.md и память проекта, архив change, PR diff --git a/packages/testkit/test/ci-runner-config.test.ts b/packages/testkit/test/ci-runner-config.test.ts new file mode 100644 index 00000000..d30c5e56 --- /dev/null +++ b/packages/testkit/test/ci-runner-config.test.ts @@ -0,0 +1,14 @@ +// PEP-157: with capacity 2 the queue of checks grew to hours at 13 open PRs; the host has 24 cores. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { describe, test } from "node:test"; + +const config = readFileSync(new URL("../../../infra/act-runner/config.yaml", import.meta.url), "utf8"); + +describe("PEP-157: очередь проверок — четыре одновременно", () => { + test("Значение вернули к двум: runner.capacity в конфиге раннера не меньше 4", () => { + const runner = config.slice(config.indexOf("\nrunner:")); + const capacity = Number(/^ {2}capacity:\s*(\d+)\s*$/m.exec(runner)?.[1]); + assert.ok(capacity >= 4, `runner.capacity must be at least 4 in infra/act-runner/config.yaml, got ${capacity}`); + }); +}); -- 2.45.2 From 326e2c67e47b2792824451eff0fba845260e140f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:15:56 +0500 Subject: [PATCH 003/185] =?UTF-8?q?PEP-157:=20=D0=B0=D1=80=D1=85=D0=B8?= =?UTF-8?q?=D0=B2=20change,=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82=D1=8C=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 1 + .../design.md | 0 .../proposal.md | 0 .../specs/peppa-ci/spec.md | 0 .../tasks.md | 4 ++-- openspec/specs/peppa-ci/spec.md | 21 +++++++++++++++++++ 6 files changed, 24 insertions(+), 2 deletions(-) rename openspec/changes/{pep-157-ci-runner-capacity => archive/2026-11-16-pep-157-ci-runner-capacity}/design.md (100%) rename openspec/changes/{pep-157-ci-runner-capacity => archive/2026-11-16-pep-157-ci-runner-capacity}/proposal.md (100%) rename openspec/changes/{pep-157-ci-runner-capacity => archive/2026-11-16-pep-157-ci-runner-capacity}/specs/peppa-ci/spec.md (100%) rename openspec/changes/{pep-157-ci-runner-capacity => archive/2026-11-16-pep-157-ci-runner-capacity}/tasks.md (75%) diff --git a/.peppa/memory.md b/.peppa/memory.md index f0980a93..2528baed 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -17,6 +17,7 @@ - Безопасность (PEP-133): git-прокси релея агента (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\` — fetch сворачивает %2e%2e как dot-сегмент; защитные заголовки — headers() в next.config.ts, строгий script-CSP не включён (Next inline-скрипты). - Проверка экранов на `next dev`: открывай `http://localhost:<порт>`, не 127.0.0.1 — иначе dev-скрипты блокируются (allowedDevOrigins), страница без гидрации, кнопки молчат; `PEPPA_WEB_URL` для login-link тот же, ссылка одноразовая. Без playwright-core: `chrome-headless-shell` из `~/Library/Caches/ms-playwright` с `--remote-debugging-port` + CDP через глобальный WebSocket Node. - Живой сайт — `next dev`: всё, что вкладка заставляет сервер писать под `.next`, запускает обновление страниц по кругу; в next.config.ts выключены `logging.browserToTerminal` и `experimental.mcpServer` (PEP-144, тест dev-server-config.test.ts). Тест testkit не импортирует файлы apps/web статически — типы Next ломают ProcessEnv всего пакета; грузить через `import(new URL(…).href)`. +- Раннер проверок (PEP-157): `capacity` в infra/act-runner/config.yaml — на регистрацию, применяется только перезапуском `peppa-act-runner` (убивает идущие проверки); конфиг смонтирован файлом из живой рабочей копии и после git checkout пропадает в контейнере (PEP-162). ## Решения - Продукт по-настоящему (PEP-112): секреты проекта доходят до выкатки сами (хук `deploy-env` → override в `peppa-deploy.sh`); `ANTHROPIC_*/CLAUDE_*/OPENCODE_*` — только продукту; нужное от владельца — `product.needs:` (MCP `declare_needs`); приёмка — `productReviewTick`. После правок `template/` — `scripts/push-template.sh` и `peppa ci connect ` старым проектам. diff --git a/openspec/changes/pep-157-ci-runner-capacity/design.md b/openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/design.md similarity index 100% rename from openspec/changes/pep-157-ci-runner-capacity/design.md rename to openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/design.md diff --git a/openspec/changes/pep-157-ci-runner-capacity/proposal.md b/openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/proposal.md similarity index 100% rename from openspec/changes/pep-157-ci-runner-capacity/proposal.md rename to openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/proposal.md diff --git a/openspec/changes/pep-157-ci-runner-capacity/specs/peppa-ci/spec.md b/openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/specs/peppa-ci/spec.md similarity index 100% rename from openspec/changes/pep-157-ci-runner-capacity/specs/peppa-ci/spec.md rename to openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/specs/peppa-ci/spec.md diff --git a/openspec/changes/pep-157-ci-runner-capacity/tasks.md b/openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/tasks.md similarity index 75% rename from openspec/changes/pep-157-ci-runner-capacity/tasks.md rename to openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/tasks.md index 1693103f..a3020b1c 100644 --- a/openspec/changes/pep-157-ci-runner-capacity/tasks.md +++ b/openspec/changes/archive/2026-11-16-pep-157-ci-runner-capacity/tasks.md @@ -4,7 +4,7 @@ ## 2. Проверка - [x] 2.1 Тест `ci-runner-config.test.ts`: `runner.capacity` не меньше 4 - [x] 2.2 Живой раннер: контейнер перезапущен, четыре проверки идут одновременно -- [ ] 2.3 lint, typecheck, build, тесты зелёные +- [x] 2.3 lint, typecheck, build, тесты зелёные ## 3. Завершение -- [ ] 3.1 AGENTS.md и память проекта, архив change, PR +- [x] 3.1 AGENTS.md и память проекта, архив change, PR diff --git a/openspec/specs/peppa-ci/spec.md b/openspec/specs/peppa-ci/spec.md index 4b054f39..23ca7086 100644 --- a/openspec/specs/peppa-ci/spec.md +++ b/openspec/specs/peppa-ci/spec.md @@ -196,3 +196,24 @@ CI платформы (шаг `lint` в Gitea Actions и первый шаг `sc - **GIVEN** в `packages/core/src/usage-text.ts` строка `tr("{n} токенов")` и комментарий `glossary-ignore: расход видит только инженер` строкой выше - **WHEN** запускается `pnpm lint` - **THEN** код выхода 0 + +### Requirement: Очередь проверок — четыре одновременно +Раннер проверок Пеппы (`infra/act-runner/config.yaml`) SHALL брать до четырёх job одновременно +на каждую регистрацию (`runner.capacity: 4`), чтобы при десятке открытых PR проверки не ждали +в очереди часами. + +#### Scenario: Четыре PR сразу +- **GIVEN** раннер `peppa-trusted` свободен +- **AND** в репозитории `peppa/peppa` одновременно запушены ветки четырёх PR +- **WHEN** Gitea ставит четыре job `peppa-ci / ci` в очередь +- **THEN** все четыре job выполняются одновременно, ни одна не ждёт в очереди + +#### Scenario: Пятая проверка ждёт +- **GIVEN** регистрация раннера выполняет четыре job +- **WHEN** в очередь приходит пятая job этого же репозитория +- **THEN** пятая job остаётся в ожидании, пока не закончится одна из четырёх + +#### Scenario: Значение вернули к двум +- **GIVEN** в `infra/act-runner/config.yaml` записано `capacity: 2` +- **WHEN** запускается тест `ci-runner-config.test.ts` +- **THEN** тест падает с сообщением «runner.capacity must be at least 4» -- 2.45.2 From bfe722d941432566abc76dfe34bad4c17f01d42b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:16:49 +0500 Subject: [PATCH 004/185] PEP-155: proposal Co-Authored-By: Claude Fable 5.2 --- .../pep-155-chat-thread-list/design.md | 41 ++++++++++ .../pep-155-chat-thread-list/proposal.md | 22 ++++++ .../specs/project-chats/spec.md | 76 +++++++++++++++++++ .../changes/pep-155-chat-thread-list/tasks.md | 14 ++++ 4 files changed, 153 insertions(+) create mode 100644 openspec/changes/pep-155-chat-thread-list/design.md create mode 100644 openspec/changes/pep-155-chat-thread-list/proposal.md create mode 100644 openspec/changes/pep-155-chat-thread-list/specs/project-chats/spec.md create mode 100644 openspec/changes/pep-155-chat-thread-list/tasks.md diff --git a/openspec/changes/pep-155-chat-thread-list/design.md b/openspec/changes/pep-155-chat-thread-list/design.md new file mode 100644 index 00000000..55954bb4 --- /dev/null +++ b/openspec/changes/pep-155-chat-thread-list/design.md @@ -0,0 +1,41 @@ +## Context +`chatThreads` отдаёт треды чата по времени последнего сообщения: ключ, заголовок, число сообщений, +открытые вопросы. Страница рисует их узкой колонкой слева. Статус задачи, агент и прочитанное в +список не попадают. + +## Goals / Non-Goals +- Цель: список, по которому продакт за секунду видит, где нужен он сам. +- Не цель: менять проекцию событий (`syncChats`), типы сообщений, Telegram — это соседние задачи эпика. + +## Decisions +- **Отдельный модуль `core/chat-threads.ts`** с одной функцией `projectThreadList(db, user, chat, { q })`. + `chats.ts` правят соседние задачи эпика — меньше конфликтов. Вид — данные без текстов; подписи + групп и статусов — в вебе (`lib/status.ts`). +- **Строки списка — задачи, а не сообщения.** Берём задачи проекта, у которых есть переписка, плюс + задачи в работе без сообщений (у них тред пустой, но агенту уже можно написать). Архивные без + открытого вопроса в список не идут (в поиске находятся). +- **Группа** считается чистой функцией `threadGroup`: + «Ждут вас» — открытый вопрос вида question/approval/permission, либо задача в `review` без + отложенного «Принять» (PEP-127), либо `awaiting_approval`; «Готово» — `done` (и архив в поиске); + «В работе» — остальное. Открытое сообщение `attention` само по себе в «Ждут вас» не переносит: + это уведомление, а не вопрос (кроме «готово» — его покрывает статус `review`). +- **Треды версий и ошибок продукта** (`release:`/`incident:`) в группы задач не попадают; с открытым + вопросом (например «Показать всем?») идут в «Ждут вас», остальные видны в «Событиях агентов». +- **Агент**: живой агент задачи (`taskAgentNames`), иначе агент последнего запуска задачи. +- **Последнее сообщение одной строкой** — `plainLine`: с конца треда первое сообщение, из которого + получается нетехническая строка (без кода, путей, идентификаторов — тот же признак, что у + `plainStep`), иначе пусто, и строку заменяет статус. Текст системных событий переводится в вебе. +- **Непрочитанное** — `settings` `chat.threads.read::` = `{ base, seen: {thread: id} }`. + Первое открытие списка ставит `base` = последний id чата: старая переписка не становится + «непрочитанной» разом. Открытие треда пишет `seen[thread]`. Считаются чужие сообщения с id больше. + Без миграции, как `chat.read:` у обсуждения. +- **Поиск в JS, не в SQL**: `lower()` и `LIKE` в SQLite не сворачивают регистр кириллицы. Название и + ключ сравниваются по задачам проекта, текст — по последним 20 000 сообщениям тредов чата + (хранятся 14 дней). Без новых зависимостей. В выдаче вместо последнего сообщения — найденное. +- **Телефон**: `?list=1` показывает список вместо сообщений на узком экране; без него — открытая + переписка на весь экран и ссылка «← К списку». На широком экране обе колонки видны всегда. + «Готово» — `
`, открыт при поиске или если открытый тред внутри. + +## Risks / Trade-offs +- Поиск по тексту читает до 20 000 строк на запрос — приемлемо: TTL журнала 14 дней, запрос только по вводу. +- Счётчик непрочитанного начинается с нуля у всех после выкладки — осознанно. diff --git a/openspec/changes/pep-155-chat-thread-list/proposal.md b/openspec/changes/pep-155-chat-thread-list/proposal.md new file mode 100644 index 00000000..bab86fe6 --- /dev/null +++ b/openspec/changes/pep-155-chat-thread-list/proposal.md @@ -0,0 +1,22 @@ +## Why +В чате проекта переписка по задачам идёт одним списком по времени: не видно, где ждут ответа +пользователя, что в работе, а что давно принято. У треда нет статуса задачи и не видно, какой +агент над ней работает; найти переписку по слову нельзя (PEP-155, эпик «Понятная переписка»). + +## What Changes +- Список переписки проекта (`/chats/`) сгруппирован: «Ждут вас», «В работе», «Готово» + (свёрнуто, со счётчиком). «Чат с аналитиком» и «События агентов» остаются сверху. +- Строка треда: ключ и название задачи, статус, агент с пиктограммой, последнее сообщение одной + строкой без технического текста, время, счётчик непрочитанного. +- Поиск по ключу, названию задачи и тексту сообщений — на сервере, в пределах проекта. +- Телефон: список одной колонкой; открытая переписка — на весь экран со ссылкой «назад». + +## Capabilities +### Modified Capabilities +- `project-chats`: список переписки проекта — группы, строка треда, поиск, непрочитанное, телефон. + +## Impact +- `packages/core/src/chat-threads.ts` (новый), экспорт из `core/index.ts`; `chatThreads` остаётся. +- `apps/web/app/(app)/chats/[chat]/page.tsx`, новый `components/ChatThreadList.tsx`, переводы en/kk. +- Без миграций: прочитанное — `settings` `chat.threads.read::`. +- Тест `chats.test.ts`. diff --git a/openspec/changes/pep-155-chat-thread-list/specs/project-chats/spec.md b/openspec/changes/pep-155-chat-thread-list/specs/project-chats/spec.md new file mode 100644 index 00000000..0bb44e4f --- /dev/null +++ b/openspec/changes/pep-155-chat-thread-list/specs/project-chats/spec.md @@ -0,0 +1,76 @@ +## ADDED Requirements + +### Requirement: Список переписки по группам +Чат проекта SHALL показывать переписку по задачам тремя группами в порядке «Ждут вас», «В работе», +«Готово». В «Ждут вас» SHALL попадать задачи с открытым вопросом агента и задачи, ждущие «Принять»; +в «Готово» — принятые задачи; в «В работе» — остальные задачи с перепиской или в работе. Группа +«Готово» SHALL быть свёрнута и показывать число тредов. «Чат с аналитиком» и «События агентов» +SHALL оставаться отдельными пунктами над группами. + +#### Scenario: Три группы +- **GIVEN** в проекте PAY задача PAY-1 с открытым вопросом агента «Какой формат даты?» +- **AND** задача PAY-2 в работе, задача PAY-3 ждёт «Принять», задача PAY-4 принята +- **WHEN** пользователь открывает чат проекта PAY +- **THEN** в «Ждут вас» — PAY-1 и PAY-3, в «В работе» — PAY-2 +- **AND** «Готово» свёрнуто, рядом число 1 + +#### Scenario: Уведомление не делает тред ждущим +- **GIVEN** задача PAY-2 в работе, по ней пришло сообщение «Агент перезапущен после сбоя» без вопроса +- **WHEN** пользователь открывает чат проекта PAY +- **THEN** PAY-2 остаётся в «В работе» + +### Requirement: Строка треда +Строка треда SHALL показывать ключ и название задачи, её статус словами, агента задачи с +пиктограммой и кличкой, последнее сообщение одной строкой, время и число непрочитанных сообщений. +Технический текст (код, пути, идентификаторы) в строку последнего сообщения SHALL NOT попадать. + +#### Scenario: Статус и агент +- **GIVEN** задачу PAY-2 «Экспорт в CSV» ведёт агент Шустрик, последнее сообщение — «Экспорт готов наполовину» +- **WHEN** пользователь открывает чат проекта PAY +- **THEN** в строке видно «PAY-2», «Экспорт в CSV», статус «В работе», «агент Шустрик» и «Экспорт готов наполовину» + +#### Scenario: Техническое сообщение не показывается +- **GIVEN** последнее сообщение в треде PAY-2 — «Поправил `src/export.ts`, запустил pnpm test» +- **AND** перед ним — «Экспорт готов наполовину» +- **WHEN** пользователь открывает чат проекта PAY +- **THEN** в строке PAY-2 видно «Экспорт готов наполовину» + +#### Scenario: Непрочитанное +- **GIVEN** пользователь уже открывал чат проекта PAY +- **AND** после этого агент написал два сообщения в треде PAY-2 +- **WHEN** пользователь открывает чат проекта PAY +- **THEN** у PAY-2 счётчик 2 +- **AND** после открытия треда PAY-2 счётчика нет + +### Requirement: Поиск по переписке +Чат проекта SHALL искать треды по ключу задачи, её названию и тексту сообщений в пределах этого +проекта, без учёта регистра. Найденные в «Готово» треды SHALL быть видны без разворачивания. + +#### Scenario: Слово из сообщения +- **GIVEN** в треде принятой задачи PAY-4 есть сообщение «Добавил выгрузку в Эксель» +- **WHEN** пользователь ищет «эксель» +- **THEN** в списке остаётся PAY-4 со строкой «Добавил выгрузку в Эксель» + +#### Scenario: Ничего не найдено +- **GIVEN** в переписке проекта PAY нет слова «самолёт» +- **WHEN** пользователь ищет «самолёт» +- **THEN** видно «Ничего не нашлось. Попробуйте другое слово.» + +#### Scenario: Чужой проект +- **GIVEN** слово «эксель» есть только в переписке проекта SHOP +- **WHEN** пользователь ищет «эксель» в чате проекта PAY +- **THEN** видно «Ничего не нашлось. Попробуйте другое слово.» + +### Requirement: Переписка на телефоне +На узком экране чат проекта SHALL показывать либо список одной колонкой, либо открытую переписку +на весь экран со ссылкой назад к списку. + +#### Scenario: Открытый тред на телефоне +- **GIVEN** экран шириной 375 px и открыт список переписки проекта PAY +- **WHEN** пользователь нажимает на тред PAY-2 +- **THEN** на экране только переписка по PAY-2 и ссылка «← К списку» + +#### Scenario: Широкий экран +- **GIVEN** экран шириной 1280 px +- **WHEN** пользователь открывает тред PAY-2 +- **THEN** список и переписка видны рядом diff --git a/openspec/changes/pep-155-chat-thread-list/tasks.md b/openspec/changes/pep-155-chat-thread-list/tasks.md new file mode 100644 index 00000000..f222037a --- /dev/null +++ b/openspec/changes/pep-155-chat-thread-list/tasks.md @@ -0,0 +1,14 @@ +## 1. Ядро +- [ ] 1.1 `core/chat-threads.ts`: `projectThreadList` — группы, статус, агент, последнее сообщение, открытые вопросы +- [ ] 1.2 Непрочитанное по тредам: `markThreadRead`, базовая отметка при первом открытии +- [ ] 1.3 Поиск по ключу, названию и тексту сообщений + +## 2. Экран +- [ ] 2.1 `ChatThreadList`: группы, строка треда, «Готово» свёрнуто, поиск +- [ ] 2.2 Телефон: список одной колонкой, открытая переписка с «← К списку» +- [ ] 2.3 Переводы en/kk, словарь + +## 3. Проверка +- [ ] 3.1 `chats.test.ts`: группы, строка, непрочитанное, поиск +- [ ] 3.2 Браузер на копии базы: 375 px и 1280 px +- [ ] 3.3 lint, typecheck, тесты, сборка; AGENTS.md, память, архив change -- 2.45.2 From a935a4252849b6d43f2e9425956d0e219fec99ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:17:36 +0500 Subject: [PATCH 005/185] =?UTF-8?q?PEP-154:=20=D0=BF=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=E2=80=94=20=D1=84=D0=B8=D0=BB=D1=8C=D1=82=D1=80=20=D1=81=D0=BB?= =?UTF-8?q?=D1=83=D0=B6=D0=B5=D0=B1=D0=BD=D0=BE=D0=B3=D0=BE=20=D1=82=D0=B5?= =?UTF-8?q?=D0=BA=D1=81=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../pep-154-service-text-filter/design.md | 42 +++++++++++++++++ .../pep-154-service-text-filter/proposal.md | 47 +++++++++++++++++++ .../specs/agent-hooks/spec.md | 25 ++++++++++ .../specs/project-chats/spec.md | 41 ++++++++++++++++ .../specs/service-monitoring/spec.md | 24 ++++++++++ .../pep-154-service-text-filter/tasks.md | 15 ++++++ 6 files changed, 194 insertions(+) create mode 100644 openspec/changes/pep-154-service-text-filter/design.md create mode 100644 openspec/changes/pep-154-service-text-filter/proposal.md create mode 100644 openspec/changes/pep-154-service-text-filter/specs/agent-hooks/spec.md create mode 100644 openspec/changes/pep-154-service-text-filter/specs/project-chats/spec.md create mode 100644 openspec/changes/pep-154-service-text-filter/specs/service-monitoring/spec.md create mode 100644 openspec/changes/pep-154-service-text-filter/tasks.md diff --git a/openspec/changes/pep-154-service-text-filter/design.md b/openspec/changes/pep-154-service-text-filter/design.md new file mode 100644 index 00000000..16e70fd8 --- /dev/null +++ b/openspec/changes/pep-154-service-text-filter/design.md @@ -0,0 +1,42 @@ +## Context + +Вопрос пользователю (`questions`) создают три функции ядра; чат, Telegram, push и карточки +читают `questions.text` / `questions.answer`. Поэтому фильтр ставится на запись — одно место +вместо шести мест показа — и дублируется в рендере бота как страховка. + +## Decisions + +- **Два уровня фильтра.** `stripServiceBlocks` — только известные служебные блоки Claude Code и + ANSI: безопасно для текста человека (ответ, ввод в терминал). `userText` — полный фильтр для + текста агента: ещё любые парные блоки с дефисом/подчёркиванием в имени тега, одиночные теги, + блоки ``` ``` ```, строки приглашения оболочки, трассировки (JS `at …`, Python `File "…"`), + абсолютные пути (`/Users/…`, `~/…`, `C:\…`, любой путь из двух и более сегментов; адреса + `https://…` не трогаются). Фильтр идемпотентен. +- **Запрос разрешения не фильтруется**: команда — его содержание; в «Продакте» она уже под + «Подробнее» (PEP-120). +- **Пустой текст.** `raiseSessionQuestion`/`askPm`/`askPmProject` бросают `PeppaError` — сообщение + не создаётся (агент в `ask_pm` получает подсказку переформулировать). Исключение — конец хода: + агент ждёт человека, и это состояние реально, поэтому вместо пустой реплики уходит прежняя + общая фраза «Агент закончил ход и ждёт вашего ответа» (она и раньше шла, когда реплики нет). +- **Исходный текст** — `settings` `question.details:` (без миграции), только если фильтр + что-то убрал; `QuestionCard` показывает под «Подробнее» суперадмину и в «Инженере». +- **Ответ из терминала.** Хук `prompt`: после `stripServiceBlocks` пусто — это не человек, вопросы + остаются открытыми, счётчик подталкиваний не сбрасывается. Ввод, который напечатала сама + Peppa (`input_sent`), закрывает более ранние сообщения как `system` «(неактуально: агент + продолжил работу)». Человек в терминале — по-прежнему ответ `terminal`. `answerQuestion` + чистит служебные блоки из любого ответа; пустой ответ отклоняется. +- **Ошибки платформы** — `platformFailure(db, e, ctx)` в core: `PeppaError` → возвращает его текст + (понятный отказ, показываем как раньше); иное → `reportPlatformError` + `alertAdmins` с ключом + от места и текста ошибки на сутки (одно сообщение) → `null`, владельцу ничего. Фоновые места: + диспетчер, автозакрытие, автоперезапуск. Ответ на нажатие кнопки («Обновить рабочую версию», + «Взять») — сообщение из двух фраз без текста исключения: молчание на действие человека хуже. + Исключение в самом хуке — `reportPlatformError` (раньше только `hook.log`). +- **Шаги в «Продакте»** — подпись по виду шага (`STEP_PLAIN` в `core/steps.ts`), `AgentSteps plain`. +- **`tmux attach` в Telegram** — `renderQuestion(…, { engineer })`, режим получателя (`getUiMode`). + +## Risks + +- Фильтр может вырезать лишнее из реплики агента (путь посреди фразы) — исходник остаётся под + «Подробнее» у инженера и в журнале (`turn_end`). +- Сообщения Peppa с логом выкладки фильтр не чистит целиком (строки лога без признаков вывода) — + это задача соседней стори эпика «сбои не идут пользователю». diff --git a/openspec/changes/pep-154-service-text-filter/proposal.md b/openspec/changes/pep-154-service-text-filter/proposal.md new file mode 100644 index 00000000..6b907c10 --- /dev/null +++ b/openspec/changes/pep-154-service-text-filter/proposal.md @@ -0,0 +1,47 @@ +## Why + +В переписку с пользователем попадает служебный текст. У вопроса #373 (PEP-134) «ответом» +записан блок `…` с путём к файлу: Claude Code прислал в сессию служебное +уведомление, а хук посчитал любой ввод в терминал ответом человека. Реплики агента уходят +владельцу как есть — с выводом команд, путями `/Users/…`, трассировками. Текст исключения +платформы («не смог запустить агента — no such column…») приходит владельцу проекта, который +ничего с ним сделать не может. + +## What Changes + +- Один модуль `core/user-text.ts` — фильтр всего, что показывается пользователю из уст агента + или из терминала: служебные блоки (``, `` и любые + XML/HTML-подобные теги), ANSI-последовательности, блоки кода и вывода, строки приглашения + оболочки, трассировки, абсолютные пути. После фильтра текст пуст — сообщение не создаётся. +- Фильтр стоит там, где сообщение рождается: `raiseSessionQuestion`, `askPm`, `askPmProject` + (кроме запроса разрешения — там команда и есть суть), `addChatMessage` для сообщений не от + людей; бот и карточки получают уже чистый текст, а бот дополнительно чистит его при выводе. + Исходный текст хранится отдельно (`question.details:`) и виден под «Подробнее» только + суперадмину и в виде «Инженер». +- Ответом на вопрос считается только то, что ввёл человек: служебное уведомление в терминале + ничего не закрывает; текст, который в терминал напечатала сама Peppa FACTORY (сбой проверок, + «лимит сброшен»), закрывает прежние сообщения как устаревшие, а не как «Ответ: …». +- Лента шагов в виде «Продакт» показывает, что делает агент, словами («Запускает проверки»), + без команд и имён файлов. +- Ошибки платформы (исключение, а не понятный отказ `PeppaError`) в фоновой обработке не создают + сообщения владельцу проекта: запись в учёт ошибок (`reportPlatformError`) и одно сообщение + суперадминам. На прямое действие пользователя — короткое сообщение без текста исключения. +- Строка с командой `tmux attach` в сообщении Telegram — только получателю в виде «Инженер». +- Старые сообщения не переписываются. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `project-chats`: служебный текст не попадает в сообщения и ответы. +- `agent-hooks`: ответом вопроса считается только ввод человека. +- `service-monitoring`: ошибки платформы уходят суперадмину и в учёт ошибок, не владельцу. + +## Impact + +- `packages/core`: новый `user-text.ts`, `platform-failure.ts`; `sessions.ts`, `tasks.ts`, + `chats.ts`, `steps.ts`. +- `packages/runner`: `hook.ts`, `autonomy.ts`, `recovery.ts`, `deploy.ts`. +- `apps/bot`: `render.ts`, `bot.ts`; `apps/web`: `cards.tsx`, `AgentSteps.tsx`, страница задачи. +- Переводы en/kk новых строк. Миграций нет. diff --git a/openspec/changes/pep-154-service-text-filter/specs/agent-hooks/spec.md b/openspec/changes/pep-154-service-text-filter/specs/agent-hooks/spec.md new file mode 100644 index 00000000..625f60ef --- /dev/null +++ b/openspec/changes/pep-154-service-text-filter/specs/agent-hooks/spec.md @@ -0,0 +1,25 @@ +## ADDED Requirements + +### Requirement: Ответом вопроса считается только ввод человека +Пеппа SHALL записывать ответом на вопрос только то, что ввёл человек (веб, Telegram, MCP PM, +набор в терминале). Служебное уведомление, пришедшее в сессию агента, SHALL NOT закрывать +вопросы. Текст, который в терминал напечатала сама Пеппа, SHALL закрывать более ранние +сообщения сессии как устаревшие (без поля «Ответ» с этим текстом). Служебные блоки SHALL +убираться из любого ответа. + +#### Scenario: Служебное уведомление в терминале +- **GIVEN** по задаче PAY-7 открыт вопрос агента «Какой цвет кнопки?» +- **WHEN** в сессию агента приходит блок `…` с путём к файлу +- **THEN** вопрос остаётся открытым +- **AND** ни в чате, ни в Telegram нет «Ответ: …» + +#### Scenario: Человек печатает в терминале +- **GIVEN** по задаче PAY-7 открыт вопрос агента «Какой цвет кнопки?» +- **WHEN** человек набирает в терминале сессии «Синий» +- **THEN** вопрос закрыт ответом «Синий» + +#### Scenario: Peppa сама пишет агенту +- **GIVEN** по задаче PAY-7 открыто сообщение «Агент закончил ход и ждёт вашего ответа» +- **WHEN** Пеппа печатает агенту в терминал отчёт о красных проверках +- **THEN** сообщение закрыто как устаревшее +- **AND** текст отчёта не показан как ответ diff --git a/openspec/changes/pep-154-service-text-filter/specs/project-chats/spec.md b/openspec/changes/pep-154-service-text-filter/specs/project-chats/spec.md new file mode 100644 index 00000000..4192a441 --- /dev/null +++ b/openspec/changes/pep-154-service-text-filter/specs/project-chats/spec.md @@ -0,0 +1,41 @@ +## ADDED Requirements + +### Requirement: Служебный текст не попадает в переписку +Пеппа SHALL убирать из текста сообщений пользователю, пришедших от агента или из терминала, +служебные блоки (``, `` и другие XML/HTML-подобные теги), +ANSI-последовательности, блоки кода и вывода команд, строки приглашения оболочки, трассировки +и абсолютные пути. Если после этого текст пуст, сообщение SHALL NOT создаваться. Исходный текст +SHALL быть доступен под «Подробнее» только суперадмину и в виде «Инженер». Сообщения, созданные +до этого правила, SHALL оставаться как есть. + +#### Scenario: Реплика агента с выводом терминала и путём +- **GIVEN** задача PAY-7 в работе +- **WHEN** агент заканчивает ход репликой «Проверки не прошли, нужен ваш ответ.», за которой идут строка `$ pnpm test`, вывод команды в блоке кода и путь `/Users/telecom/Dev/pay/src/app.ts` +- **THEN** владелец видит сообщение «Проверки не прошли, нужен ваш ответ.» +- **AND** в нём нет ни команды, ни вывода, ни пути + +#### Scenario: От реплики ничего не осталось +- **GIVEN** задача PAY-7 в работе +- **WHEN** агент задаёт вопрос, состоящий только из блока `…` +- **THEN** вопрос пользователю не создаётся + +#### Scenario: Исходный текст для инженера +- **GIVEN** сообщение по PAY-7, из которого убран путь `/Users/telecom/Dev/pay/src/app.ts` +- **WHEN** карточку сообщения открывает пользователь в виде «Продакт», не суперадмин +- **THEN** исходного текста с путём он не видит +- **BUT** в виде «Инженер» исходный текст показан под «Подробнее» + +### Requirement: Шаги агента в виде «Продакт» — словами +В виде «Продакт» лента шагов агента SHALL показывать, что делает агент, словами по виду шага, +без команд, имён файлов и путей. + +#### Scenario: Агент запускает проверки +- **GIVEN** агент по PAY-7 выполнил команду `pnpm test --filter web` +- **WHEN** пользователь в виде «Продакт» открывает «Подробнее» на странице задачи +- **THEN** в ленте шагов строка «Запускает проверки» +- **AND** текста команды в ленте нет + +#### Scenario: Вид «Инженер» +- **GIVEN** тот же шаг +- **WHEN** страницу открывает пользователь в виде «Инженер» +- **THEN** в ленте видна команда `pnpm test --filter web` diff --git a/openspec/changes/pep-154-service-text-filter/specs/service-monitoring/spec.md b/openspec/changes/pep-154-service-text-filter/specs/service-monitoring/spec.md new file mode 100644 index 00000000..0ad2c48e --- /dev/null +++ b/openspec/changes/pep-154-service-text-filter/specs/service-monitoring/spec.md @@ -0,0 +1,24 @@ +## ADDED Requirements + +### Requirement: Ошибки платформы не идут владельцу проекта +Исключение в фоновой обработке Пеппы (не понятный отказ с текстом для человека) SHALL NOT +создавать сообщение владельцу проекта: оно SHALL записываться в систему учёта ошибок и +приходить суперадминам одним сообщением на одну ошибку в сутки. Понятный отказ (например, +«подписка не выбрана») SHALL по-прежнему приходить владельцу. + +#### Scenario: Диспетчер упал с исключением +- **GIVEN** проект PAY с автономностью «сам берёт» и задачей в бэклоге +- **WHEN** запуск агента падает с исключением «no such column: x» +- **THEN** владелец проекта не получает сообщения +- **AND** суперадмин получает одно сообщение о сбое +- **AND** в системе учёта ошибок появляется запись с этим исключением + +#### Scenario: Та же ошибка повторяется +- **GIVEN** суперадмин уже получил сообщение о сбое диспетчера «no such column: x» +- **WHEN** через 10 минут диспетчер падает с той же ошибкой +- **THEN** второе сообщение суперадмину не приходит + +#### Scenario: Понятный отказ +- **GIVEN** проект PAY без выбранной подписки +- **WHEN** диспетчер не может запустить агента +- **THEN** владелец получает сообщение с причиной простыми словами diff --git a/openspec/changes/pep-154-service-text-filter/tasks.md b/openspec/changes/pep-154-service-text-filter/tasks.md new file mode 100644 index 00000000..51e2cf3d --- /dev/null +++ b/openspec/changes/pep-154-service-text-filter/tasks.md @@ -0,0 +1,15 @@ +## 1. Фильтр +- [ ] 1.1 `core/user-text.ts`: `stripServiceBlocks`, `userText`, хранение исходного текста; экспорт из core +- [ ] 1.2 Применить в `raiseSessionQuestion`, `askPm`, `askPmProject`, `addChatMessage` +- [ ] 1.3 `answerQuestion` чистит служебные блоки; хук `prompt` — только ввод человека; `turnEnd` — пустая реплика + +## 2. Показ +- [ ] 2.1 Бот: `render.ts` чистит текст и ответ, `tmux attach` — только «Инженеру» +- [ ] 2.2 Веб: `QuestionCard` — исходный текст под «Подробнее» (инженер/суперадмин); шаги словами в «Продакте» + +## 3. Ошибки платформы +- [ ] 3.1 `core/platform-failure.ts` и замена текста исключения в сообщениях владельцу (autonomy, recovery, deploy), хук → учёт ошибок + +## 4. Проверка +- [ ] 4.1 Тест `service-text.test.ts` по сценариям спек; переводы en/kk +- [ ] 4.2 lint, typecheck, test, build; память, архив, PR -- 2.45.2 From ea3515d31c0e57e77fb6a9e1dfb5e1b1339b9d2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:20:32 +0500 Subject: [PATCH 006/185] =?UTF-8?q?PEP-155:=20project=20chat=20list=20?= =?UTF-8?q?=E2=80=94=20groups,=20status,=20agent,=20unread,=20search?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/web/app/(app)/chats/[chat]/page.tsx | 72 ++++---- apps/web/components/ChatThreadList.tsx | 162 ++++++++++++++++++ packages/core/src/chat-threads.ts | 203 +++++++++++++++++++++++ packages/core/src/index.ts | 1 + packages/core/src/story-product.ts | 5 +- packages/shared/src/i18n/en/story.ts | 10 ++ packages/shared/src/i18n/kk/story.ts | 10 ++ packages/testkit/test/chats.test.ts | 117 ++++++++++++- 8 files changed, 538 insertions(+), 42 deletions(-) create mode 100644 apps/web/components/ChatThreadList.tsx create mode 100644 packages/core/src/chat-threads.ts diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 3250b222..718db789 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -1,14 +1,15 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react"; -import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core"; +import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core"; import { projects, questions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { PRODUCT_NAME } from "@peppa/shared/i18n"; import { eq, inArray } from "drizzle-orm"; import { LiveRefresh } from "@/components/LiveRefresh"; import { AgentBadge } from "@/components/AgentBadge"; -import { ago, Empty, Flash, PageHeader } from "@/components/common"; +import { ChatThreadList } from "@/components/ChatThreadList"; +import { ago, Empty, Flash, PageHeader, StatusBadge } from "@/components/common"; import { Hidden, QuestionCard } from "@/components/cards"; import { Dictate } from "@/components/Dictate"; import { Workspace } from "@/components/Workspace"; @@ -20,7 +21,7 @@ import { getT } from "@/lib/i18n"; import { cn } from "@/lib/utils"; import { linkChatAction, postChatAction, unlinkChatAction } from "../actions"; -type Params = { error?: string; thread?: string; link?: string }; +type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string }; const CHANNEL = "channel"; /** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */ @@ -32,7 +33,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi const t = await getT(); const w = await words(); const { chat: slug } = await params; - const { error, thread: rawThread, link } = await searchParams; + const { error, thread: rawThread, link, q, list: rawList } = await searchParams; // Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too). await syncChats(db).catch((e) => console.error("syncChats", e)); const list = await listChats(db, user); @@ -43,17 +44,21 @@ export default async function ChatPage({ params, searchParams }: { params: Promi // A project chat opens on the discussion: people talking to each other, no agents or events. const discussion = !master && rawThread === undefined; const unread = await discussionUnread(db, user.id); - if (discussion) await markDiscussionRead(db, user.id, chat.id); + // PEP-155: on a phone it is either the list (`?list=1`) or the open conversation, full screen. + const showList = !master && rawList === "1"; + if (discussion && !showList) await markDiscussionRead(db, user.id, chat.id); + if (thread && !master && !showList) await markThreadRead(db, user.id, chat.id, thread); // PEP-110: a person's message the analyst has not answered yet — «печатает…». const typing = discussion && (await analystPending(db, chat.id)); - const threads = master ? [] : await chatThreads(db, chat.id); + const threads = master ? null : await projectThreadList(db, user, chat, { q }); + const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : []; const messages = master ? await masterFeed(db, user, { limit: 150 }) : discussion ? await discussionMessages(db, chat.id) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 }); - const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null; + const current = thread ? ((await threadTitle(db, thread)) ?? thread) : null; // Live state of the questions in view (answer buttons, «отвечено» marks). const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null); @@ -62,10 +67,15 @@ export default async function ChatPage({ params, searchParams }: { params: Promi : []; const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }])); - const url = (p: { thread?: string | null }) => { - const base = `/chats/${chat.slug}`; - return p.thread ? `${base}?thread=${encodeURIComponent(p.thread)}` : base; + const base = `/chats/${chat.slug}`; + const url = (p: { thread?: string | null; list?: boolean }) => { + const params = new URLSearchParams(); + if (p.thread) params.set("thread", p.thread); + if (threads?.q) params.set("q", threads.q); + if (p.list) params.set("list", "1"); + return params.size ? `${base}?${params}` : base; }; + const openRow = thread ? rows.find((r) => r.key === thread) : undefined; const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) }); // PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's // (users never see it) and links groups only for a superadmin without a bot of their own. @@ -215,23 +225,24 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ))} -
- {!master && ( - +
+ {threads && ( +
+ +
)} -
+
+ {!master && ( + + {t("← К списку")} + + )} {current && (
🧵 {t.text(current)} + {openRow?.status && } + {openRow?.agentName && } {taskThread && }
)} @@ -276,23 +287,6 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ); } -async function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) { - const t = await getT(); - return ( - - - {title} - {open > 0 && {open}} - - {meta && {meta}} - - ); -} - function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) { const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0]; return key ? {label} : null; diff --git a/apps/web/components/ChatThreadList.tsx b/apps/web/components/ChatThreadList.tsx new file mode 100644 index 00000000..9ff610c4 --- /dev/null +++ b/apps/web/components/ChatThreadList.tsx @@ -0,0 +1,162 @@ +import Link from "next/link"; +import { Search, X } from "lucide-react"; +import type { ThreadList, ThreadRow } from "@peppa/core"; +import { AgentBadge } from "@/components/AgentBadge"; +import { ago, StatusBadge } from "@/components/common"; +import { Hidden } from "@/components/cards"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { getT } from "@/lib/i18n"; +import { words } from "@/lib/auth"; +import { cn } from "@/lib/utils"; + +const COUNT = "rounded-full px-1.5 font-mono text-[11px] leading-4 font-semibold tabular-nums"; + +/** + * PEP-155: the conversations of a project chat — the chat with the analyst and the agents' events + * on top, then story threads in groups «Ждут вас», «В работе», «Готово» (folded), with a search. + */ +export async function ChatThreadList({ + base, + list, + active, + discussion, + feed, + raw, +}: { + /** `/chats/` */ + base: string; + list: ThreadList; + /** The open thread's key, if a thread is open. */ + active: string | null; + discussion: boolean; + feed: boolean; + /** The `thread` parameter as it is in the URL: the search keeps the open conversation. */ + raw: string | null; +}) { + const t = await getT(); + const w = await words(); + const q = list.q; + const href = (thread: string | null) => { + const p = new URLSearchParams(); + if (thread) p.set("thread", thread); + if (q) p.set("q", q); + return p.size ? `${base}?${p}` : base; + }; + const total = list.waiting.length + list.working.length + list.done.length; + const rows = (items: ThreadRow[]) => items.map((r) => ); + return ( + + ); +} + +function GroupTitle({ children, count, tone = "bg-muted text-muted-foreground" }: { children: React.ReactNode; count: number; tone?: string }) { + return ( +

+ {children} + {count > 0 && {count}} +

+ ); +} + +function Plain({ href, active, title, meta }: { href: string; active: boolean; title: string; meta: string }) { + return ( + + {title} + {meta} + + ); +} + +async function Row({ r, href, active }: { r: ThreadRow; href: string; active: boolean }) { + const t = await getT(); + const title = r.taskKey ? r.title : t.text(r.title); + return ( + + + {r.taskKey && {r.taskKey}} + 0) && "font-medium")} title={title}> + {title} + + {r.open > 0 && ( + + ? + + )} + {r.unread > 0 && ( + + {r.unread > 99 ? "99+" : r.unread} + + )} + + {(r.status || r.agentName || r.lastAt) && ( + + {r.status && } + {r.agentName && } + {r.lastAt && {ago(r.lastAt, t)}} + + )} + {r.last && ( + + {r.last.mine && t("вы") + ": "} + {r.last.system ? t.text(r.last.text) : r.last.text} + + )} + + ); +} diff --git a/packages/core/src/chat-threads.ts b/packages/core/src/chat-threads.ts new file mode 100644 index 00000000..c5acfc71 --- /dev/null +++ b/packages/core/src/chat-threads.ts @@ -0,0 +1,203 @@ +// PEP-155: the list of a project chat's conversations for a product manager — story threads in +// three groups («Ждут вас», «В работе», «Готово»), each with the story's status, its agent, the +// last message in one plain line, the unread count; and a search over keys, titles and texts. +// Data only: group names and status labels are the web's (lib/status.ts). +import { agents, chatMessages, projects, questions, sessions, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, asc, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm"; +import { listPendingAccepts } from "./accept-pending.ts"; +import { threadTitle, type Chat } from "./chats.ts"; +import { getSetting, setSetting } from "./settings.ts"; +import { TECHNICAL_TEXT } from "./story-product.ts"; +import type { User } from "./users.ts"; + +export type ThreadGroup = "waiting" | "working" | "done"; + +export interface ThreadRow { + /** Thread key: `task:` (or `release:` / `incident:` with an open question). */ + key: string; + /** "PAY-7"; null — not a story thread. */ + taskKey: string | null; + title: string; + /** Story status; null — not a story thread. */ + status: string | null; + archived: boolean; + /** PEP-127: «Принять» is pressed already, the factory finishes by itself. */ + accepted: boolean; + agentName: string | null; + /** The last message in one plain line (or the found one, when searching); null — nothing readable. */ + last: { text: string; /** Written by the factory itself: a translatable text. */ system: boolean; mine: boolean } | null; + lastAt: Date | null; + unread: number; + /** Open questions that need the person's answer. */ + open: number; + group: ThreadGroup; +} + +export interface ThreadList { + waiting: ThreadRow[]; + working: ThreadRow[]; + done: ThreadRow[]; + /** The search the list is narrowed by; null — the whole list. */ + q: string | null; +} + +/** Question kinds a person has to answer; `attention` is a notice («готово» is the `review` status). */ +const ASKS = ["question", "approval", "permission"] as const; +const ACTIVE = new Set(["proposing", "awaiting_approval", "in_progress", "review", "blocked"]); +const SCAN = 3000; +const SCAN_SEARCH = 20_000; +const LINE = 140; + +/** Which group a story thread belongs to. */ +export function threadGroup(t: { status: string | null; archived?: boolean; accepted?: boolean; open: number }): ThreadGroup { + if (t.open > 0) return "waiting"; + if (t.status === "done" || t.archived) return "done"; + if (t.status === "awaiting_approval" || (t.status === "review" && !t.accepted)) return "waiting"; + return "working"; +} + +const cut = (s: string, n = LINE) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s); + +/** + * A message as one line a product manager can read: its first meaningful line without markup; + * null when that line is technical (code, paths, identifiers). + */ +export function plainLine(text: string | null | undefined): string | null { + for (const raw of (text ?? "").split("\n")) { + const line = raw.replace(/^[\s>#*\-•]+/, "").replace(/\*\*|__/g, "").replace(/\s+/g, " ").trim(); + if (line.length < 2) continue; + if (line.includes("`") || TECHNICAL_TEXT.test(line)) return null; + return cut(line); + } + return null; +} + +/** The piece of a message around the found word, in one line. */ +function snippet(text: string, at: number, len: number): string { + const start = Math.max(0, text.lastIndexOf("\n", at) + 1, at - 60); + const s = text.slice(start, Math.max(at + len, start + LINE)).split("\n")[0]!.replace(/\s+/g, " ").trim(); + return `${start > 0 && text[start - 1] !== "\n" ? "…" : ""}${cut(s)}`; +} + +interface ThreadRead { + /** Messages up to this id were there before the user first saw the list — never «new». */ + base: number; + seen: Record; +} +const readKey = (userId: number, chatId: number) => `chat.threads.read:${userId}:${chatId}`; + +/** The user has opened the thread: its messages so far are read. */ +export async function markThreadRead(db: Db, userId: number, chatId: number, threadKey: string): Promise { + const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(and(eq(chatMessages.chatId, chatId), eq(chatMessages.threadKey, threadKey))); + const id = Number(last?.id ?? 0); + const st = (await getSetting(db, readKey(userId, chatId))) ?? { base: 0, seen: {} }; + if (!id || id <= Math.max(st.base, st.seen[threadKey] ?? 0)) return; + await setSetting(db, readKey(userId, chatId), { ...st, seen: { ...st.seen, [threadKey]: id } } satisfies ThreadRead); +} + +/** + * The conversations of a project chat in groups, most recent first. With `q` — only the threads + * whose story key, title or message text has it (case-insensitive; in JS: SQLite does not fold + * Cyrillic), archived stories included. + */ +export async function projectThreadList(db: Db, user: Pick, chat: Pick, o: { q?: string | null } = {}): Promise { + const q = (o.q ?? "").trim().toLocaleLowerCase().slice(0, 100) || null; + const empty: ThreadList = { waiting: [], working: [], done: [], q }; + if (!chat.projectId) return empty; + const [project] = await db.select({ id: projects.id, key: projects.key }).from(projects).where(eq(projects.id, chat.projectId)); + if (!project) return empty; + + const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(eq(chatMessages.chatId, chat.id)); + let read = await getSetting(db, readKey(user.id, chat.id)); + if (!read) { + // First look at the list: what is already there does not become «unread» all at once. + read = { base: Number(last?.id ?? 0), seen: {} }; + await setSetting(db, readKey(user.id, chat.id), read); + } + + const taskRows = await db.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status, archivedAt: tasks.archivedAt, updatedAt: tasks.updatedAt }).from(tasks).where(eq(tasks.projectId, project.id)); + const stats = new Map( + ( + await db + .select({ key: chatMessages.threadKey, lastAt: sql`max(${chatMessages.createdAt})` }) + .from(chatMessages) + .where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey))) + .groupBy(chatMessages.threadKey) + ).map((r) => [r.key!, new Date(Number(r.lastAt))]), + ); + const openRows = await db.select({ taskId: questions.taskId, id: questions.id }).from(questions).where(and(eq(questions.projectId, project.id), isNull(questions.answeredAt), inArray(questions.kind, [...ASKS]))); + const openByTask = new Map(); + for (const r of openRows) if (r.taskId != null) openByTask.set(r.taskId, (openByTask.get(r.taskId) ?? 0) + 1); + // Questions without a story (a version, a product error) live in their own threads. + const loose = openRows.filter((r) => r.taskId == null).map((r) => r.id); + const looseThreads = new Map(); + if (loose.length) { + const rows = await db.select({ key: chatMessages.threadKey }).from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey), inArray(chatMessages.questionId, loose))); + for (const r of rows) if (!r.key!.startsWith("task:")) looseThreads.set(r.key!, (looseThreads.get(r.key!) ?? 0) + 1); + } + + // The agent of a story: the one working now, else the one of its last run. + const agentByTask = new Map(); + const runs = await db.select({ taskId: sessions.taskId, status: sessions.status, name: agents.name }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).where(and(eq(sessions.projectId, project.id), isNotNull(sessions.taskId))).orderBy(asc(sessions.id)); + for (const r of runs) { + const live = r.status !== "done" && r.status !== "failed"; + if (live || !agentByTask.get(r.taskId!)?.live) agentByTask.set(r.taskId!, { name: r.name, live }); + } + const accepted = await listPendingAccepts(db); + + // The newest messages of the threads: the last readable line, the unread count, the search. + const msgs = await db + .select({ id: chatMessages.id, key: chatMessages.threadKey, text: chatMessages.text, authorKind: chatMessages.authorKind, authorUserId: chatMessages.authorUserId }) + .from(chatMessages) + .where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey))) + .orderBy(desc(chatMessages.id)) + .limit(q ? SCAN_SEARCH : SCAN); + const lastLine = new Map(); + const found = new Map(); + const unread = new Map(); + for (const m of msgs) { + const key = m.key!; + const mine = m.authorUserId === user.id; + const said = (text: string) => ({ text, system: m.authorKind === "system", mine }); + if (!mine && m.id > Math.max(read.base, read.seen[key] ?? 0)) unread.set(key, (unread.get(key) ?? 0) + 1); + if (!lastLine.has(key)) { + const line = plainLine(m.text); + if (line) lastLine.set(key, said(line)); + } + if (q && !found.has(key)) { + const at = m.text.toLocaleLowerCase().indexOf(q); + if (at >= 0) found.set(key, said(snippet(m.text, at, q.length))); + } + } + + const out: ThreadList = { ...empty }; + const sortAt = new Map(); + const add = (row: Omit, at: number) => { + const full = { ...row, group: threadGroup(row) }; + out[full.group].push(full); + sortAt.set(full, at); + }; + for (const t of taskRows) { + const key = `task:${t.id}`; + const taskKey = formatTaskKey(project.key, t.number); + const open = openByTask.get(t.id) ?? 0; + const archived = t.archivedAt != null; + const lastAt = stats.get(key) ?? null; + if (q) { + if (!found.has(key) && !taskKey.toLocaleLowerCase().includes(q) && !t.title.toLocaleLowerCase().includes(q)) continue; + } else if (open === 0 && (archived || (!lastAt && !ACTIVE.has(t.status)))) continue; + add( + { key, taskKey, title: t.title, status: t.status, archived, accepted: accepted.has(t.id), agentName: agentByTask.get(t.id)?.name ?? null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open }, + (lastAt ?? t.updatedAt).getTime(), + ); + } + for (const [key, open] of looseThreads) { + const title = (await threadTitle(db, key)) ?? key; + if (q && !found.has(key) && !title.toLocaleLowerCase().includes(q)) continue; + const lastAt = stats.get(key) ?? null; + add({ key, taskKey: null, title, status: null, archived: false, accepted: false, agentName: null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open }, lastAt?.getTime() ?? 0); + } + for (const g of ["waiting", "working", "done"] as const) out[g].sort((a, b) => sortAt.get(b)! - sortAt.get(a)!); + return out; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d32cfffe..b0ead52a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -65,6 +65,7 @@ export * from "./memory.ts"; export * from "./agent-model.ts"; export * from "./onboarding.ts"; export * from "./chats.ts"; +export * from "./chat-threads.ts"; export * from "./subscription-care.ts"; export * from "./subscription-names.ts"; export * from "./transcribe.ts"; diff --git a/packages/core/src/story-product.ts b/packages/core/src/story-product.ts index 40a51c92..13e9424a 100644 --- a/packages/core/src/story-product.ts +++ b/packages/core/src/story-product.ts @@ -57,7 +57,8 @@ export const STORY_PRODUCT_TEXT = { }; /** File names, paths, identifiers and commands — not for a product manager's screen. */ -const TECHNICAL = /[/\\_$<>{}=]|\w\.\w|\w\(|[a-z][A-Z]|--\w|\b(?:tmux|git|npm|pnpm|sql|api|json|mcp|ci|pr|cli|env)\b/i; +/** Code, paths, identifiers — text a product manager cannot read. */ +export const TECHNICAL_TEXT = /[/\\_$<>{}=]|\w\.\w|\w\(|[a-z][A-Z]|--\w|\b(?:tmux|git|npm|pnpm|sql|api|json|mcp|ci|pr|cli|env)\b/i; /** * The current tasks.md item for the product view: the leading «1.2», code in backticks and @@ -67,7 +68,7 @@ export function plainStep(text: string | null | undefined): string | null { if (!text) return null; if (text.includes("`")) return null; const s = text.replace(/^\s*\d+(?:\.\d+)*\.?\s+/, "").replace(/\s+/g, " ").trim(); - if (s.length < 3 || s.length > 140 || TECHNICAL.test(s)) return null; + if (s.length < 3 || s.length > 140 || TECHNICAL_TEXT.test(s)) return null; return s; } diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..de599143 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -416,4 +416,14 @@ export const story: Dict = { "ждёт сброса лимита": "waiting for the limit reset", закончил: "finished", "остановился с ошибкой": "stopped with an error", + // PEP-155: the list of a project chat's conversations + "Ждут вас": "Waiting for you", + "Сейчас от вас ничего не нужно.": "Nothing is needed from you right now.", + "Найти в переписке…": "Search the conversations…", + "Поиск по переписке": "Search the conversations", + "Найти": "Search", + "Сбросить поиск": "Clear the search", + "Ничего не нашлось. Попробуйте другое слово.": "Nothing found. Try another word.", + "← К списку": "← Back to the list", + "Новых сообщений: {n}": "New messages: {n}", }; diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..0cd45266 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -381,4 +381,14 @@ export const story: Dict = { "ждёт сброса лимита": "лимит тасталуын күтуде", "закончил": "аяқтады", "остановился с ошибкой": "қатемен тоқтады", + // PEP-155: the list of a project chat's conversations + "Ждут вас": "Сізді күтуде", + "Сейчас от вас ничего не нужно.": "Қазір сізден ештеңе қажет емес.", + "Найти в переписке…": "Хат алмасудан іздеу…", + "Поиск по переписке": "Хат алмасудан іздеу", + "Найти": "Іздеу", + "Сбросить поиск": "Іздеуді тазарту", + "Ничего не нашлось. Попробуйте другое слово.": "Ештеңе табылмады. Басқа сөзді қолданып көріңіз.", + "← К списку": "← Тізімге", + "Новых сообщений: {n}": "Жаңа хабарлар: {n}", }; diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts index 38f8562b..f45ff3e4 100644 --- a/packages/testkit/test/chats.test.ts +++ b/packages/testkit/test/chats.test.ts @@ -6,7 +6,7 @@ import { after, before, describe, test } from "node:test"; // helpers must load first: it sets the isolated test env that runner modules read on load. import { core, db, runner, teardown, waitFor } from "./helpers.ts"; import { MockTelegram } from "../src/mock-telegram.ts"; -import { chatMessages, users } from "@peppa/db"; +import { chatMessages, tasks, users } from "@peppa/db"; import { eq } from "drizzle-orm"; import type { Bot } from "@peppa/bot"; @@ -126,6 +126,121 @@ describe("project chat", () => { }); }); +// PEP-155: the list of a project chat's conversations. +describe("Список переписки проекта", () => { + const setStatus = (taskId: number, status: "in_progress" | "review" | "done" | "backlog") => db.update(tasks).set({ status }).where(eq(tasks.id, taskId)); + const say = (chatId: number, taskId: number, text: string, authorKind: "agent" | "system" = "agent") => core.addChatMessage(db, { chatId, threadKey: threadOf(taskId), kind: "event", authorKind, text }); + const keys = (rows: Array<{ taskKey: string | null }>) => rows.map((r) => r.taskKey); + + test("Три группы", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const asked = await newTask(p, "Формат даты"); + const working = await newTask(p, "Экспорт в CSV"); + const review = await newTask(p, "Отчёт"); + const done = await newTask(p, "Вход"); + const idle = await newTask(p, "Ещё не начата"); + await core.askPm(db, asked, { kind: "question", text: "Какой формат даты?" }); + await setStatus(working.task.id, "in_progress"); + await setStatus(review.task.id, "review"); + await setStatus(done.task.id, "done"); + await core.syncChats(db); + await say(chat.id, done.task.id, "Вход работает"); + const list = await core.projectThreadList(db, pm, chat); + assert.deepEqual(keys(list.waiting).sort(), [asked.key, review.key].sort()); + assert.deepEqual(keys(list.working), [working.key]); + assert.deepEqual(keys(list.done), [done.key]); + assert.ok(![...list.waiting, ...list.working, ...list.done].some((r) => r.taskKey === idle.key), "a backlog story nobody wrote about is not in the list"); + assert.equal(list.waiting.find((r) => r.taskKey === asked.key)!.open, 1); + }); + + test("Уведомление не делает тред ждущим", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + await core.askPm(db, ref, { kind: "attention", text: "Агент перезапущен после сбоя" }); + await core.syncChats(db); + const list = await core.projectThreadList(db, pm, chat); + assert.deepEqual(keys(list.working), [ref.key]); + assert.equal(list.waiting.length, 0); + // PEP-127: «Принять» is pressed already — nothing is waited from the person. + await setStatus(ref.task.id, "review"); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat)).waiting), [ref.key]); + await core.setPendingAccept(db, ref.task.id, { at: Date.now(), via: "web", rebases: 0 } as Parameters[2]); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat)).working), [ref.key]); + await core.clearPendingAccept(db, ref.task.id); + }); + + test("Статус и агент; техническое сообщение не показывается", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + const session = await core.createSession(db, { projectId: p.id, taskId: ref.task.id }); + const agent = await core.ensureSessionAgent(db, session.id); + await say(chat.id, ref.task.id, "Экспорт готов наполовину"); + await say(chat.id, ref.task.id, "Поправил `src/export.ts`, запустил pnpm test"); + const [row] = (await core.projectThreadList(db, pm, chat)).working; + assert.equal(row!.taskKey, ref.key); + assert.equal(row!.title, "Экспорт в CSV"); + assert.equal(row!.status, "in_progress"); + assert.equal(row!.agentName, agent!.name); + assert.equal(row!.last!.text, "Экспорт готов наполовину"); + assert.equal(core.plainLine("**Готово:** проверил вход\nвторая строка"), "Готово: проверил вход"); + assert.equal(core.plainLine("update_task(status: review)"), null); + }); + + test("Непрочитанное", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + await say(chat.id, ref.task.id, "Старое сообщение"); + // The first look: what was there before is not «new». + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 0); + await say(chat.id, ref.task.id, "Первое новое"); + await say(chat.id, ref.task.id, "Второе новое"); + await core.addChatMessage(db, { chatId: chat.id, threadKey: threadOf(ref.task.id), kind: "user", authorKind: "user", authorUserId: pm.id, authorLogin: pm.login, text: "моё сообщение" }); + const mine = (await core.projectThreadList(db, pm, chat)).working[0]!; + assert.equal(mine.unread, 2, "own messages are not «new»"); + assert.equal(mine.last!.mine, true); + await core.markThreadRead(db, pm.id, chat.id, threadOf(ref.task.id)); + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 0); + // Bob has his own marks. + await core.projectThreadList(db, bob, chat); + await say(chat.id, ref.task.id, "Третье новое"); + assert.equal((await core.projectThreadList(db, bob, chat)).working[0]!.unread, 1); + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 1); + assert.equal((await core.projectThreadList(db, eve, chat)).working[0]!.unread, 0); + }); + + test("Поиск: слово из сообщения, ключ, название; чужой проект", async () => { + const p = await newProject(); + const other = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const otherChat = await core.ensureProjectChat(db, other.id); + const done = await newTask(p, "Отчёты"); + const working = await newTask(p, "Оплата картой"); + const foreign = await newTask(other, "Склад"); + await setStatus(done.task.id, "done"); + await setStatus(working.task.id, "in_progress"); + await say(chat.id, done.task.id, "Проверил вход\nДобавил выгрузку в Эксель"); + await say(chat.id, working.task.id, "Подключаю оплату"); + await say(otherChat.id, foreign.task.id, "Самолёт и Эксель"); + + const byText = await core.projectThreadList(db, pm, chat, { q: "эксель" }); + assert.equal(byText.q, "эксель"); + assert.deepEqual(keys(byText.done), [done.key]); + assert.equal(byText.done[0]!.last!.text, "Добавил выгрузку в Эксель"); + assert.equal(byText.working.length + byText.waiting.length, 0); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat, { q: "ОПЛАТА" })).working), [working.key]); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat, { q: done.key.toLowerCase() })).done), [done.key]); + const none = await core.projectThreadList(db, pm, chat, { q: "самолёт" }); + assert.equal(none.waiting.length + none.working.length + none.done.length, 0); + }); +}); + describe("master chat", () => { test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => { const p = await newProject(); -- 2.45.2 From c80a31f5cb93fb2892f055ea4cf9a6c421c1193a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:23:45 +0500 Subject: [PATCH 007/185] =?UTF-8?q?PEP-154:=20=D1=84=D0=B8=D0=BB=D1=8C?= =?UTF-8?q?=D1=82=D1=80=20=D1=81=D0=BB=D1=83=D0=B6=D0=B5=D0=B1=D0=BD=D0=BE?= =?UTF-8?q?=D0=B3=D0=BE=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0,=20=D0=BE?= =?UTF-8?q?=D1=82=D0=B2=D0=B5=D1=82=20=E2=80=94=20=D1=82=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=BA=D0=BE=20=D0=B2=D0=B2=D0=BE=D0=B4=20=D1=87=D0=B5=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D0=BA=D0=B0,=20=D0=BE=D1=88=D0=B8=D0=B1?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=BF=D0=BB=D0=B0=D1=82=D1=84=D0=BE=D1=80=D0=BC?= =?UTF-8?q?=D1=8B=20=E2=80=94=20=D1=81=D1=83=D0=BF=D0=B5=D1=80=D0=B0=D0=B4?= =?UTF-8?q?=D0=BC=D0=B8=D0=BD=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/bot/package.json | 2 +- apps/bot/src/bot.ts | 5 +- apps/bot/src/render.ts | 12 +- apps/web/app/(app)/t/[key]/page.tsx | 2 +- apps/web/components/AgentSteps.tsx | 27 ++- apps/web/components/cards.tsx | 15 +- packages/core/src/chats.ts | 11 + packages/core/src/index.ts | 2 + packages/core/src/platform-failure.ts | 39 ++++ packages/core/src/sessions.ts | 5 + packages/core/src/tasks.ts | 15 +- packages/core/src/user-text.ts | 142 +++++++++++++ packages/runner/src/autonomy.ts | 20 +- packages/runner/src/deploy.ts | 6 +- packages/runner/src/hook.ts | 18 +- packages/runner/src/recovery.ts | 5 +- packages/shared/src/i18n/en/runner.ts | 4 + packages/shared/src/i18n/en/story.ts | 11 + packages/shared/src/i18n/kk/runner.ts | 4 + packages/shared/src/i18n/kk/story.ts | 11 + packages/testkit/test/service-text.test.ts | 229 +++++++++++++++++++++ 21 files changed, 558 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/platform-failure.ts create mode 100644 packages/core/src/user-text.ts create mode 100644 packages/testkit/test/service-text.test.ts diff --git a/apps/bot/package.json b/apps/bot/package.json index 5e87285a..1313b8b1 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "type": "module", - "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, + "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" }, "bin": { "peppa-bot": "./bin/peppa-bot" }, "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 6f0f0cad..b98f7456 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -39,6 +39,7 @@ import { markOutboxRetry, markOutboxSent, pendingQuestions, + getUiMode, questionByTelegramMessage, setOffset, setSetting, @@ -312,11 +313,12 @@ export function createBot(o: BotOptions) { if (!audience.length) continue; const ctx = await context(q); const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status }); - const r = renderQuestion(q, ctx); // A push is a "now" signal: questions older than this don't pop up on a fresh subscription. const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS; const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`; for (const u of audience) { + // PEP-154: the terminal command is for the «Инженер» view only. + const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" }); await deliverToUser(db, u, { event, projectId: q.projectId, @@ -331,6 +333,7 @@ export function createBot(o: BotOptions) { // fresh text and its buttons back, at most once in `repeatEditMs`. const repeats = states.get(q.id)?.repeats ?? 0; if (!repeats) continue; + const r = renderQuestion(q, ctx); for (const sent of await sentQuestionMessages(db, q.id)) { const key = repeatEditKey(sent.id, repeats); if (await getOutbox(db, key)) continue; diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 5536a560..cb2df129 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -1,5 +1,5 @@ // Telegram message texts and buttons for PM questions. HTML parse mode. -import type { Question, SessionView } from "@peppa/core"; +import { stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core"; import type { InlineButton } from "./telegram.ts"; import { m as tr } from "@peppa/shared/i18n"; @@ -22,12 +22,13 @@ export interface Rendered { // callback_data (≤64 bytes): "q::", "s::" or "i::" (core/incidents.ts) export function renderQuestion( q: Question, - ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, + ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean }, ): Rendered { const head = ["" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "", ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); - const body = esc(clip(q.text, 3300)); + // PEP-154: no service text in the message (a permission request keeps its command). + const body = esc(clip(q.kind === "permission" ? q.text : userText(q.text) || q.text, 3300)); const lines = [head, KIND[q.kind], "", body]; const buttons: InlineButton[][] = []; @@ -59,7 +60,7 @@ export function renderQuestion( lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту."))); } } - if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); + if (ctx.session && ctx.engineer) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); return { text: lines.join("\n"), buttons }; } @@ -67,7 +68,8 @@ export function renderQuestion( export function renderAnswered(original: string, q: Question): string { const mark = q.answeredVia === "system" ? "⌛" : "✅"; const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"]; - const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: {answer}", { via, answer: esc(clip(q.answer ?? "", 500)) }); + const answer = stripServiceBlocks(q.answer ?? ""); + const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: {answer}", { via, answer: esc(clip(answer, 500)) }); return `${original}\n\n${mark} ${said}`; } diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index b75d6fce..7b07875c 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -309,7 +309,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom {live ? ( // PEP-9 terminal + PEP-33 step feed of the newest unfinished runner. - + ) : (
diff --git a/apps/web/components/AgentSteps.tsx b/apps/web/components/AgentSteps.tsx index 9cd8ccb6..b240cb92 100644 --- a/apps/web/components/AgentSteps.tsx +++ b/apps/web/components/AgentSteps.tsx @@ -19,6 +19,19 @@ const KIND: Record = { other: { icon: Wrench, label: m("инструмент") }, }; +// PEP-154: a step for the «Продакт» view — what the agent does, in words: no command, file name or path. +const STEP_PLAIN: Record = { + command: m("Выполняет действие в проекте"), + test: m("Запускает проверки"), + edit: m("Вносит изменения"), + read: m("Изучает проект"), + search: m("Ищет нужное в проекте"), + web: m("Смотрит в интернете"), + agent: m("Поручил часть работы помощнику"), + mcp: m("Сверяется с задачей"), + other: m("Работает над задачей"), +}; + const KEEP = 30; function since(iso: string, now: number, t: Translator): string { @@ -32,7 +45,7 @@ function since(iso: string, now: number, t: Translator): string { * What the agent is doing now (PEP-33): its latest tool calls, newest first. Initial steps * come from the server, new ones from the live channel (PEP-37, `steps:`). */ -export function AgentSteps({ sessionId, initial, live, hooks = true }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean }) { +export function AgentSteps({ sessionId, initial, live, hooks = true, plain = false }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean; /** PEP-154: «Продакт» — what the agent does in words, no commands, file names or paths. */ plain?: boolean }) { const [steps, setSteps] = useState(initial); const [now, setNow] = useState(() => Date.now()); const t = useT(); @@ -59,7 +72,7 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session if (!steps.length) return (

- {hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")} + {hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : plain ? t("Этот агент не сообщает о шагах.") : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}

); return ( @@ -70,9 +83,13 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session return (
  • - - {s.text} - + {plain ? ( + {t(STEP_PLAIN[s.kind] ?? STEP_PLAIN.other)} + ) : ( + + {s.text} + + )} {!s.ok && {t("ошибка")}} {since(s.at, now, t)}
  • diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index ac09bb01..1f271405 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -1,7 +1,7 @@ // Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; -import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; +import { questionDetails, questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { db } from "@/lib/db"; import { SubscriptionName } from "@/components/SubscriptionName"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; @@ -15,6 +15,7 @@ import { RunnerTerminal } from "@/components/RunnerTerminal"; import { SessionUsageLine } from "@/components/Accounting"; import { cn } from "@/lib/utils"; import { getT } from "@/lib/i18n"; +import { subscriptionNamesVisible, uiMode } from "@/lib/auth"; import { m } from "@peppa/shared/i18n"; const KIND = { @@ -42,6 +43,8 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal // PEP-151: the same state came again — one message with the time it was last refreshed. const state = await questionState(db, q.id).catch(() => null); const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null; + // PEP-154: what the filter removed (command output, paths) — for «Инженер» and a superadmin only. + const original = (await uiMode()) === "engineer" || (await subscriptionNamesVisible()) ? await questionDetails(db, q.id).catch(() => null) : null; return (
    @@ -70,6 +73,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal

    {t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

    )} + {original && ( +
    + {t("Подробнее: исходный текст")} +
    {original}
    +
    + )} {answered ? (

    {q.answeredVia === "system" ? : } @@ -152,7 +161,7 @@ export function AttachCommand({ name }: { name: string }) { } /** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */ -export async function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) { +export async function SessionCard({ s, back, showTitle = false, terminal = false, steps, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) { const t = await getT(); return (

    @@ -179,7 +188,7 @@ export async function SessionCard({ s, back, showTitle = false, terminal = false )} - {steps && } + {steps && } {terminal && }
    ); diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index c9d1bc4e..77067015 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -13,6 +13,7 @@ import { notify } from "./notify.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { projectForUser, userProjectIds, type User } from "./users.ts"; import type { OutboxRow } from "./telegram.ts"; +import { pruneQuestionDetails, userText } from "./user-text.ts"; import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts"; export type Chat = typeof chats.$inferSelect; @@ -101,6 +102,13 @@ export async function listChats(db: Db, user: Pick): Promise { + // PEP-154: what an agent or Peppa says goes through the service-text filter; nothing left — no message. + // A question's text was filtered when it was asked (a permission request keeps its command). + if (m.authorKind !== "user" && !m.questionId) { + const text = userText(m.text); + if (!text) return null; + m = { ...m, text }; + } if (m.threadKey && m.threadTitle == null) { const [prev] = await db .select({ t: chatMessages.threadTitle }) @@ -462,6 +470,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise let repeated = 0; const add = async (m: NewChatMessage) => { // PEP-151: the same event of a story again in a row is a counter on the line already there. + if (m.authorKind !== "user" && !m.questionId) m.text = userText(m.text); // PEP-154: compared and stored without service text + if (!m.text) return; if (await repeatsLastEvent(db, m)) return void repeated++; if (m.threadKey) m.threadTitle = await titleOf(m.threadKey); if (await addChatMessage(db, m)) added++; @@ -570,6 +580,7 @@ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise void; + now?: Date; +} + +/** + * What to tell the project owner about a failure: the text of a clear refusal, or null — it is + * a platform error (reported to the error tracker and to the superadmins, one message per error + * a day) and the owner gets nothing. Never throws. + */ +export async function platformFailure(db: Db, e: unknown, ctx: FailureContext): Promise { + if (e instanceof PeppaError) return e.message; + const message = (e as Error)?.message ?? String(e); + try { + await reportPlatformError(db, e, { service: ctx.service, where: ctx.where }); + // The same error of the same part (numbers aside) is one message a day. + const fp = createHash("sha1").update(`${ctx.service}|${normalizeMessage(ctx.where)}|${normalizeMessage(message)}`).digest("hex").slice(0, 12); + const day = (ctx.now ?? new Date()).toISOString().slice(0, 10); + // glossary-ignore: read by superadmins only + const text = tr("⚠️ Сбой в Peppa FACTORY ({where}): {error}", { where: ctx.where, error: message.length > 300 ? `${message.slice(0, 300)}…` : message }); + await alertAdmins(db, `fail:${fp}:${day}`, text, ctx.log ?? (() => {})); + } catch {} + return null; +} diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ec796bea..47309f95 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -7,6 +7,7 @@ import { actorColumns } from "./actor.ts"; import type { Question, QuestionKind } from "./tasks.ts"; import { userProjectIds } from "./users.ts"; import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts"; +import { keepQuestionDetails, messageText } from "./user-text.ts"; export type Session = typeof sessions.$inferSelect; export type SessionStatus = (typeof sessionStatus.enumValues)[number]; @@ -182,6 +183,9 @@ export async function raiseSessionQuestion( awaitingHook = false, o: { topic?: MessageTopic; head?: string | null } = {}, ): Promise { + // PEP-154: no service text (tags, command output, paths) in what the person reads. + const original = text; + text = messageText(kind, text); const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => { const [created] = await db .insert(questions) @@ -189,6 +193,7 @@ export async function raiseSessionQuestion( .returning(); return created!; }); + await keepQuestionDetails(db, row.id, original, text).catch(() => {}); await notify(db, { type: "question", questionId: row.id }); return row; } diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index aeba839e..f4d551a1 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -15,6 +15,7 @@ import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; import { taskBudgetView, type TaskBudgetView } from "./budgets.ts"; import { productNeeds, type ProductNeedView } from "./product-needs.ts"; import { raiseOnce, type MessageTopic } from "./message-state.ts"; +import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -310,6 +311,9 @@ export interface NewQuestion { /** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQuestion): Promise { + // PEP-154: no service text (tags, command output, paths) in what the person reads. + const original = q.text; + q = { ...q, text: messageText(q.kind, q.text) }; // PEP-151: the same state of the story again refreshes the earlier message instead of adding one. const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => { const [created] = await db @@ -318,6 +322,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues .returning(); return created!; }); + await keepQuestionDetails(db, row.id, original, q.text).catch(() => {}); if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId); await notify(db, { type: "question", questionId: row.id }); return row; @@ -325,7 +330,9 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues /** A message for the PM about the project as a whole (releases), not about a task. */ export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise { - const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); + const text = messageText(q.kind, q.text); + const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text }).returning(); + await keepQuestionDetails(db, row!.id, q.text, text).catch(() => {}); await notify(db, { type: "question", questionId: row!.id }); return row!; } @@ -344,6 +351,12 @@ export async function answerQuestion( answer: string, via: NonNullable, ): Promise { + // PEP-154: an answer is a person's words — service blocks never land in it. + if (via !== "system") { + const said = stripServiceBlocks(answer); + if (!said && answer.trim()) throw new PeppaError(`Question #${questionId}: the answer is service text only`); + answer = said; + } const [row] = await db .update(questions) .set({ answer, answeredVia: via, answeredAt: new Date() }) diff --git a/packages/core/src/user-text.ts b/packages/core/src/user-text.ts new file mode 100644 index 00000000..1f6cbe19 --- /dev/null +++ b/packages/core/src/user-text.ts @@ -0,0 +1,142 @@ +// PEP-154: what a person reads must not carry service text. One filter for everything shown to +// the user from an agent's mouth or from a terminal: service blocks (, +// , any XML/HTML-like tag), ANSI sequences, code and command output, shell +// prompt lines, stack traces, absolute paths. The original stays under «Подробнее» for a +// superadmin and the «Инженер» view (`question.details:`), never in the main text. +import { settings, type Db } from "@peppa/db"; +import { and, like, lt } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +/** Blocks Claude Code and Peppa put into a conversation for the model, never for a person. */ +const SERVICE_TAGS = [ + "task-notification", + "system-reminder", + "local-command-stdout", + "local-command-stderr", + "local-command-caveat", + "command-name", + "command-message", + "command-args", + "command-contents", + "bash-input", + "bash-stdout", + "bash-stderr", + "user-prompt-submit-hook", + "user-memory-input", + "persisted-output", + "tool_use_error", + "function_calls", + "function_results", + "new-diagnostics", + "ide_opened_file", + "ide_selection", + "pasted_content", +].join("|"); + +// CSI / OSC / two-byte escapes, then the other control characters (tab, \n and \r stay). +const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; +const SERVICE_BLOCK_RE = new RegExp(`<(${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*?`, "gi"); +/** A service block cut off before its closing tag (clipped text): everything after it is its body. */ +const SERVICE_OPEN_RE = new RegExp(`<(?:${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*$`, "i"); + +/** + * Removes only what is certainly not a person's words: known service blocks and terminal + * escape sequences. Safe for a person's own text (an answer, input typed into a terminal). + */ +export function stripServiceBlocks(text: string): string { + return text.replace(/\r\n?/g, "\n").replace(ANSI_RE, "").replace(SERVICE_BLOCK_RE, "").replace(SERVICE_OPEN_RE, "").trim(); +} + +/** Input that reached a session but was not typed by anyone: nothing is left without service blocks. */ +export const isServiceInput = (text: string) => !!text.trim() && !stripServiceBlocks(text); + +// Where a removed block stood (private-use character: never in real text). +const CUT = ""; +// Any paired block whose tag name has a hyphen or an underscore — nobody writes prose like that. +const CUSTOM_BLOCK_RE = /<([a-z][\w.]*[-_][\w.-]*)\b[^>]*>[\s\S]*?<\/\1\s*>/gi; +const FENCE_RE = /^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?(?:^[ \t]*\1[ \t]*$|(?![\s\S]))/gm; +const TAG_RE = /<\/?[a-zA-Z][\w:.-]*(?:\s[^<>]*)?\/?>/g; +const PROMPT_LINE_RE = /^\s*(?:[\w.-]+@[\w.-]+[^\n$#%]*[$#%]|\$|❯|➜|>>>|PS [A-Za-z]:\\[^>\n]*>)\s+\S.*$/; +const TRACE_LINE_RE = /^\s*(?:at\s.+(?::\d+:\d+\)?|\))\s*$|File ".+", line \d+.*$|Traceback \(most recent call last\):?\s*$|\.{3} \d+ more\s*$|Caused by: .+$)/; +const ERROR_HEAD_RE = /^\s*(?:Uncaught\s+)?(?:[\w$]+\.)*[\w$]*(?:Error|Exception)\b.*$/; +const PATH_SRC = String.raw`(?()\[\],;]*`; +const PATH_RE = new RegExp(PATH_SRC, "g"); +const HAS_PATH_RE = new RegExp(PATH_SRC); +const INLINE_CODE_RE = /`[^`\n]*`/g; +const HAS_WORD_RE = /[\p{L}\p{N}]/u; + +/** + * Text of an agent or a terminal, as a person may read it: without service blocks, tags, code + * and command output, shell prompts, stack traces and absolute paths. Idempotent. An empty + * result means there was nothing for a person in it. + */ +export function userText(text: string): string { + const src = stripServiceBlocks(text); + let s = src.replace(CUSTOM_BLOCK_RE, "").replace(FENCE_RE, `${CUT}\n`); + const lines = s.split("\n"); + const kept: string[] = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!; + const cutLine = PROMPT_LINE_RE.test(line) || TRACE_LINE_RE.test(line) || (ERROR_HEAD_RE.test(line) && TRACE_LINE_RE.test(lines[i + 1] ?? "")); + kept.push(cutLine ? CUT : line); + } + s = kept.join("\n"); + s = s.replace(INLINE_CODE_RE, (code) => (HAS_PATH_RE.test(code) ? "" : code)).replace(PATH_RE, (path) => /[.!?]$/.test(path) ? path.slice(-1) : "").replace(TAG_RE, ""); + const out: string[] = []; + const srcLines = new Set(src.split("\n").map((l) => l.trim())); + for (const raw of s.split("\n")) { + if (raw.includes(CUT)) { + // «Вот вывод:» before a removed block: the colon promises what is no longer there. + for (let j = out.length - 1; j >= 0; j--) { + if (!out[j]) continue; + if (/[::]$/.test(out[j]!)) out[j] = `${out[j]!.slice(0, -1)}.`; + break; + } + out.push(""); + continue; + } + const line = raw + .replace(/[ \t]+$/g, "") + .replace(/(\S)[ \t]{2,}/g, "$1 ") + .replace(/\(\s*[,;:]?\s*\)|\[\s*\]|«\s*»|"\s*"|``/g, "") + .replace(/[ \t]+([.,;:!?)»])/g, "$1") + .replace(/([(«])[ \t]+/g, "$1") + .replace(/[ \t]+$/g, ""); + // A line the filter emptied (a bullet with only a path) goes away; an untouched one stays. + if (line.trim() && !HAS_WORD_RE.test(line) && !srcLines.has(raw.trim())) continue; + out.push(line); + } + return out.join("\n").replace(/\n{3,}/g, "\n\n").trim(); +} + +/** + * The text of a message for the user as it is stored. A permission request keeps its command + * (that is what the person allows; «Продакт» has it under «Подробнее», PEP-120). Nothing left + * after the filter — no message: PeppaError (an agent's `ask_pm` gets it as a hint). + */ +export function messageText(kind: string, text: string): string { + if (kind === "permission") return text; + const shown = userText(text); + // i18n-ignore: read by the agent (ask_pm) or the log, not by the user + if (!shown) throw new PeppaError("В сообщении только служебный текст (теги, вывод команд, пути) — показать пользователю нечего. Напиши его простыми словами."); + return shown; +} + +const DETAILS_PREFIX = "question.details:"; +const detailsKey = (questionId: number) => `${DETAILS_PREFIX}${questionId}`; + +/** Keeps the original of a filtered message for «Подробнее» (superadmin, «Инженер»); none when nothing was cut. */ +export async function keepQuestionDetails(db: Db, questionId: number, original: string, shown: string): Promise { + if (original.trim() === shown.trim()) await deleteSetting(db, detailsKey(questionId)); + else await setSetting(db, detailsKey(questionId), { text: original.slice(0, 8000) }); +} + +/** The unfiltered text of a message, if the filter removed something. Show only to a superadmin or in «Инженер». */ +export async function questionDetails(db: Db, questionId: number): Promise { + return (await getSetting<{ text: string }>(db, detailsKey(questionId)))?.text ?? null; +} + +export async function pruneQuestionDetails(db: Db, before: Date): Promise { + await db.delete(settings).where(and(like(settings.key, `${DETAILS_PREFIX}%`), lt(settings.updatedAt, before))); +} diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index f28aca66..86599800 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -24,6 +24,7 @@ import { projectPoolExhausted, questionRecipients, raiseSessionQuestion, + platformFailure, setSetting, taskPrNumber, type AutonomySettings, @@ -213,7 +214,9 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n const key = `auto:closefail:${q.id}`; if (!(await getSetting(db, key))) { await setSetting(db, key, true); - await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: (e as Error).message }) }); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `auto-close ${ref.key}`, log }); + if (why) await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: why }) }); } log(`${ref.key}: auto-close failed — ${(e as Error).message}`); } @@ -268,10 +271,13 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date const fresh = await resolveTaskById(db, task.id).catch(() => null); if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {}); await setIdle(db, project.id, { ...state, failUntil: now.getTime() + DISPATCH_RETRY_MS }); - await askPmProject(db, project, { - kind: "attention", - text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: (e as Error).message })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`, - }); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `dispatch ${ref.key}`, log, now }); + if (why) + await askPmProject(db, project, { + kind: "attention", + text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: why })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`, + }); log(`${ref.key}: dispatch failed — ${(e as Error).message}`); return; } @@ -374,7 +380,9 @@ export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise try { await moveTask(db, ref, "in_progress"); } catch (e) { - await askPmProject(db, ref.project, { kind: "attention", text: m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }) }); + // PEP-154: the person pressed a button and gets an answer, but never the text of an exception. + const why = await platformFailure(db, e, { service: "runner", where: `start ${ref.key}` }); + await askPmProject(db, ref.project, { kind: "attention", text: why ? m("⚠️ {key} не запущена: {error}", { key: ref.key, error: why }) : m("⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.", { key: ref.key }) }); } return true; } diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 5f781a13..e9dfc265 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -3,7 +3,7 @@ // here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a // `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). import { m } from "@peppa/shared/i18n"; -import { answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { answerQuestion, askPmProject, platformFailure, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; import { projects, questions, releases, settings, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; import { deployPlatform, isPlatform } from "./platform-release.ts"; @@ -288,7 +288,9 @@ export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: s try { await deployProd(db, project, by); } catch (e) { - await askPmProject(db, project, { kind: "attention", text: m("Обновление рабочей версии не запущено: {error}", { error: (e as Error).message }) }); + // PEP-154: the person pressed a button and gets an answer, but never the text of an exception. + const why = await platformFailure(db, e, { service: "runner", where: `deploy prod ${project.key}` }); + await askPmProject(db, project, { kind: "attention", text: why ? m("Обновление рабочей версии не запущено: {error}", { error: why }) : m("Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.") }); } return true; } diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index c355aaa6..68f87e46 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -34,6 +34,9 @@ import { logSessionEvent, peppaInputSentAt, pendingSessionQuestions, + isServiceInput, + userText, + reportPlatformError, raiseSessionQuestion, releaseHookQuestion, updateSession, @@ -197,6 +200,8 @@ 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-154: a reply that is service text only (a tag block, command output) says nothing to a person. + if (text && !userText(text)) text = null; // PEP-43: the story's budget is spent — the PM was asked; don't push the agent further. if (s.taskId && (await getBudgetState(db, s.taskId))) { await logSessionEvent(db, s, "budget_hold", {}); @@ -326,9 +331,17 @@ async function handle(event: string, input: HookInput): Promise { // pending for this session is now answered — except hook-held questions, and, // when Peppa typed this text itself, questions raised after it did (e.g. a CI // failure pasted while the PM is being asked about the next one). + // PEP-154: a service notification of the CLI (…) is nobody's answer — + // the questions stay open and the nudge counter keeps counting. + if (isServiceInput(input.prompt ?? "")) { + await updateSession(db, s.id, { status: "running", lastActivityAt: now }); + break; + } const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null; for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) { - await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); + // What Peppa typed itself (a red check, «лимит сброшен») makes earlier messages stale; it is not an answer. + if (sentAt) await answerQuestion(db, q.id, m("(неактуально: агент продолжил работу)"), "system").catch(() => {}); + else await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); } await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now }); break; @@ -425,5 +438,8 @@ try { else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {}); } catch (e) { log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`); + // PEP-154: the hook's own failure goes to the error tracker, never to the project owner. + // A clear refusal (PeppaError) is not a failure of the platform. + if ((e as Error)?.name !== "PeppaError") await reportPlatformError(createDb(), e, { service: "hook", where: event }).catch(() => {}); } process.exit(0); diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 61a699a8..d3cff078 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -16,6 +16,7 @@ import { PeppaError, projectAudience, raiseSessionQuestion, + platformFailure, touchQuestion, sendProjectMessage, setSetting, @@ -184,7 +185,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`); } catch (e) { await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message }); - await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message })); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `restart ${s.taskKey ?? `#${s.id}`}`, log: o.log, now: o.now }); + if (why) await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: why })); } } } diff --git a/packages/shared/src/i18n/en/runner.ts b/packages/shared/src/i18n/en/runner.ts index 09db54cf..a26831fb 100644 --- a/packages/shared/src/i18n/en/runner.ts +++ b/packages/shared/src/i18n/en/runner.ts @@ -329,6 +329,10 @@ export const runner: Dict = { "Не удалось подготовить рабочую копию для агента: {error}": "Could not prepare a working copy for the agent: {error}", "(неактуально: агент перезапущен)": "(no longer relevant: the agent was restarted)", "(неактуально: агент остановлен)": "(no longer relevant: the agent was stopped)", + "(неактуально: агент продолжил работу)": "(no longer relevant: the agent went on working)", + "Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "The update of the live version did not start. We are already looking into it — please try again later.", + "⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} was not started. We are already looking into it — please try again later.", + "⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Failure in Peppa FACTORY ({where}): {error}", // Sharing and visibility "Участниками управляет только владелец проекта": "Only the project owner manages members", diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..53e4fe96 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -236,6 +236,17 @@ export const story: Dict = { инструмент: "tool", "Агент ещё ничего не сделал — шаги появятся здесь.": "The agent hasn't done anything yet — steps will appear here.", "Шагов не записано.": "No steps recorded.", + "Этот агент не сообщает о шагах.": "This agent does not report its steps.", + "Выполняет действие в проекте": "Doing something in the project", + "Запускает проверки": "Running the checks", + "Вносит изменения": "Making changes", + "Изучает проект": "Studying the project", + "Ищет нужное в проекте": "Searching the project", + "Смотрит в интернете": "Looking it up on the web", + "Поручил часть работы помощнику": "Handed part of the work to a helper", + "Сверяется с задачей": "Checking against the task", + "Работает над задачей": "Working on the task", + "Подробнее: исходный текст": "Details: the original text", "Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "This agent doesn't report steps (no hooks) — watch the terminal.", "Шаги агента": "Agent steps", ошибка: "error", diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts index 07de1745..c6c329cd 100644 --- a/packages/shared/src/i18n/kk/runner.ts +++ b/packages/shared/src/i18n/kk/runner.ts @@ -252,6 +252,10 @@ export const runner: Dict = { "Не удалось подготовить рабочую копию для агента: {error}": "Агентке жұмыс көшірмесін дайындау мүмкін болмады: {error}", "(неактуально: агент перезапущен)": "(өзекті емес: агент қайта іске қосылды)", "(неактуально: агент остановлен)": "(өзекті емес: агент тоқтатылды)", + "(неактуально: агент продолжил работу)": "(өзекті емес: агент жұмысын жалғастырды)", + "Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "Жұмыс нұсқасын жаңарту іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.", + "⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.", + "⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Peppa FACTORY жүйесінде ақау ({where}): {error}", "Участниками управляет только владелец проекта": "Қатысушыларды тек жоба иесі басқарады", "Укажите логин участника": "Қатысушының логинін көрсетіңіз", "Нет доступа к коду проекта — войдите заново": "Жоба кодына қолжетімділік жоқ — қайта кіріңіз", diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..57b9a8ea 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -220,6 +220,17 @@ export const story: Dict = { "инструмент": "құрал", "Агент ещё ничего не сделал — шаги появятся здесь.": "Агент әлі ештеңе жасаған жоқ — қадамдар осында пайда болады.", "Шагов не записано.": "Қадамдар жазылмаған.", + "Этот агент не сообщает о шагах.": "Бұл агент қадамдары туралы хабарламайды.", + "Выполняет действие в проекте": "Жобада әрекет орындап жатыр", + "Запускает проверки": "Тексерулерді іске қосып жатыр", + "Вносит изменения": "Өзгерістер енгізіп жатыр", + "Изучает проект": "Жобаны зерттеп жатыр", + "Ищет нужное в проекте": "Жобадан керегін іздеп жатыр", + "Смотрит в интернете": "Интернеттен қарап жатыр", + "Поручил часть работы помощнику": "Жұмыстың бір бөлігін көмекшіге тапсырды", + "Сверяется с задачей": "Тапсырмамен салыстырып жатыр", + "Работает над задачей": "Тапсырмамен жұмыс істеп жатыр", + "Подробнее: исходный текст": "Толығырақ: бастапқы мәтін", "Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "Бұл агент қадамдарын хабарламайды (хуктар жоқ) — терминалды қараңыз.", "Шаги агента": "Агент қадамдары", "ошибка": "қате", diff --git a/packages/testkit/test/service-text.test.ts b/packages/testkit/test/service-text.test.ts new file mode 100644 index 00000000..2f761c0b --- /dev/null +++ b/packages/testkit/test/service-text.test.ts @@ -0,0 +1,229 @@ +// PEP-154: service text never reaches the person. Blocks like , command +// output, shell prompts, stack traces and absolute paths are cut out of messages and answers; +// an exception inside Peppa goes to the superadmins and the error tracker, not to the owner. +// Tests are named after the spec scenarios. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { projects, questions, sessions, telegramOutbox, users } from "@peppa/db"; +import { and, eq, isNull, sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); +const { renderQuestion, renderAnswered } = await import("@peppa/bot/render"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../.."); +const bugsink = await new MockBugsink().start(); +process.env.BUGSINK_URL = bugsink.url; + +const NOTIFICATION = "\nb7f3\n/private/tmp/claude-501/tasks/b7f3.output\ncompleted\nBackground command finished\n"; +const TERMINAL_REPLY = [ + "Проверки не прошли, нужен ваш ответ.", + "", + "$ pnpm test", + "```", + "FAIL src/app.test.ts", + " ● оплата › считает сумму", + "```", + "TypeError: total is not a function", + " at sum (/Users/telecom/Dev/pay/src/app.ts:12:5)", + " at async run (node:internal/process/task_queues:95:5)", + "Файл: /Users/telecom/Dev/pay/src/app.ts", + "\x1b[31mЧто выбрать: чинить сейчас или отложить?\x1b[0m", +].join("\n"); + +let owner: Awaited>; +let admin: Awaited>; +let seq = 0; + +/** A story at work with its agent's session (no tmux: messages are raised as the hook does). */ +async function story() { + const key = `F${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: owner.id }); + const created = await core.createTask(db, { projectId: p.id, title: "Оплата картой" }); + await core.updateTask(db, await core.resolveTask(db, created.key), { status: "in_progress" }); + const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning(); + return { + project: p, + key: created.key, + taskId: created.task.id, + sessionId: s!.id, + session: () => core.getSession(db, s!.id), + ref: () => core.resolveTask(db, created.key), + asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id), + thread: async () => { + await core.syncChats(db); + return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); + }, + }; +} + +/** Runs the real peppa-hook like Claude Code does: payload on stdin. */ +function hook(event: string, payload: unknown, sessionId: number): Promise { + return new Promise((done) => { + const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: "0" }, stdio: ["pipe", "ignore", "inherit"] }); + p.on("close", (code) => { + assert.equal(code, 0); + done(); + }); + p.stdin.end(JSON.stringify(payload)); + }); +} + +const outboxTo = async (chatId: number) => + (await db.select().from(telegramOutbox).where(sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`).orderBy(telegramOutbox.id)).map((r) => String(r.params.text)); +const openOf = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt))); + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 541, login: "mock-owner" }, { access_token: "x" }); + admin = await core.upsertUserFromGitea(db, { id: 542, login: "mock-admin" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 5410, telegramUserId: 5410 }).where(eq(users.id, owner.id)); + await db.update(users).set({ telegramChatId: 5420, telegramUserId: 5420 }).where(eq(users.id, admin.id)); + await core.setPlatformAdmins(db, [admin.login]); +}); +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-154: фильтр служебного текста", () => { + test("userText: блоки, ANSI, вывод команд, приглашение оболочки, трассировка и пути убираются; адреса остаются", () => { + const out = core.userText(TERMINAL_REPLY); + assert.equal(out, "Проверки не прошли, нужен ваш ответ.\n\nФайл:\nЧто выбрать: чинить сейчас или отложить?"); + assert.equal(core.userText(out), out, "idempotent"); + assert.equal(core.userText(NOTIFICATION), ""); + assert.equal(core.userText("Готово. не для людей Результат: https://git.example.com/pay/pulls/7"), "Готово. Результат: https://git.example.com/pay/pulls/7"); + assert.equal(core.userText("Поправил `packages/core/src/chats.ts` и C:\\Users\\pm\\app.ts, проверил."), "Поправил и, проверил."); + // A person's own words are not rewritten: only what is certainly service text. + assert.equal(core.stripServiceBlocks("Синий, как в /Users/me/макет.png"), "Синий, как в /Users/me/макет.png"); + assert.equal(core.isServiceInput(NOTIFICATION), true); + assert.equal(core.isServiceInput("Синий"), false); + }); + + test("Реплика агента с выводом терминала и путём", async () => { + const st = await story(); + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + // Two automatic nudges first (the story is at work), then the message for the person. + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + const [q] = await st.asked(); + assert.ok(q, "the owner got a message"); + assert.match(q.text, /Проверки не прошли, нужен ваш ответ\./); + assert.match(q.text, /чинить сейчас или отложить/); + for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!q.text.includes(bad), `no «${bad}» in the message`); + const thread = await st.thread(); + assert.ok(thread.some((m) => m.text.includes("Проверки не прошли"))); + assert.ok(!thread.some((m) => m.text.includes("/Users/") || m.text.includes("pnpm test"))); + const tg = renderQuestion(q, { taskKey: st.key, taskTitle: "Оплата картой", taskStatus: "in_progress", session: await st.session(), webUrl: "http://peppa.test" }); + assert.ok(!tg.text.includes("/Users/") && !tg.text.includes("tmux attach"), "Telegram: no path, no terminal command"); + assert.ok(renderQuestion(q, { taskKey: st.key, taskTitle: null, session: await st.session(), webUrl: "http://peppa.test", engineer: true }).text.includes("tmux attach"), "«Инженер» keeps the terminal command"); + }); + + test("Исходный текст для инженера", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Нужен ваш ответ. Файл /Users/telecom/Dev/pay/src/app.ts не открывается."); + assert.ok(!q.text.includes("/Users/")); + assert.match((await core.questionDetails(db, q.id)) ?? "", /\/Users\/telecom\/Dev\/pay\/src\/app\.ts/); + const clean = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"] }); + assert.equal(await core.questionDetails(db, clean.id), null, "nothing was cut — nothing to keep"); + // A permission request keeps its command: that is what the person allows. + const perm = await core.raiseSessionQuestion(db, await st.session(), "permission", "Разрешить Bash: rm /Users/telecom/Dev/pay/tmp.txt", ["allow", "deny"]); + assert.match(perm.text, /\/Users\/telecom/); + }); + + test("От реплики ничего не осталось", async () => { + const st = await story(); + await assert.rejects(core.askPm(db, await st.ref(), { kind: "question", text: "только служебное" }), /служебный текст/); + assert.equal((await st.asked()).length, 0); + // The end of a turn with nothing for a person: the plain «агент ждёт» line, not the block. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: NOTIFICATION }, st.sessionId); + const [q] = await st.asked(); + assert.equal(q?.text, "Агент закончил ход и ждёт вашего ответа."); + assert.equal(await core.addChatMessage(db, { chatId: (await core.ensureProjectChat(db, st.project.id)).id, kind: "event", authorKind: "agent", text: NOTIFICATION, dedupeKey: `mock:${st.key}` }), null); + }); +}); + +describe("PEP-154: ответом вопроса считается только ввод человека", () => { + test("Служебное уведомление в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: NOTIFICATION }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredAt, null, "the question stays open"); + assert.equal(after.answer, null); + const thread = await st.thread(); + assert.ok(!thread.some((m) => m.text.includes("task-notification") || (m.question?.answer ?? "").includes("task-notification")), "not in the chat: neither text nor answer"); + // Even if such a block came glued to a person's words, only the words are the answer. + const answered = await core.answerQuestion(db, q.id, `Синий\n${NOTIFICATION}`, "terminal"); + assert.equal(answered.answer, "Синий"); + assert.ok(!renderAnswered("Вопрос", answered).includes("task-notification")); + await assert.rejects(core.answerQuestion(db, (await core.askPm(db, await st.ref(), { kind: "question", text: "А размер?", sessionId: st.sessionId })).id, NOTIFICATION, "web")); + }); + + test("Человек печатает в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answer, "Синий"); + assert.equal(after.answeredVia, "terminal"); + }); + + test("Peppa сама пишет агенту", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Агент закончил ход и ждёт вашего ответа."); + const report = "Проверки PR красные: test\n$ pnpm test\nFAIL src/app.test.ts"; + await core.logSessionEvent(db, await st.session(), "input_sent", { text: report }); + await hook("prompt", { prompt: report }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredVia, "system", "closed as stale, not answered"); + assert.ok(!(after.answer ?? "").includes("FAIL")); + }); +}); + +describe("PEP-154: ошибки платформы не идут владельцу проекта", () => { + const NO_QUIET = { quietFrom: null, quietTo: null }; + const autonomy = (now = new Date()) => runner.autonomyTick(db, { now, log: () => {} }); + + test("Диспетчер упал с исключением; та же ошибка повторяется", async () => { + // The platform project is connected to the error tracker (mock). + const platform = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = platform.key; + core.resetErrorReporting(); + const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); + await runner.connectErrorTracking(db, await core.getProject(db, platform.key), client, "http://peppa.test"); + + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + await db.update(projects).set({ ownerId: owner.id }).where(eq(projects.id, p.id)); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + // The start blows up inside Peppa: the sessions table is gone for one tick. + const now = new Date(); + const ingested = bugsink.ingested.length; + db.run(sql`ALTER TABLE runner_tasks RENAME TO runner_tasks_x`); + try { + await autonomy(now); + assert.equal((await openOf(p.id)).length, 0, "the owner gets no message"); + assert.equal((await outboxTo(5410)).length, 0, "nothing for the owner in Telegram"); + const alerts = (await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")); + assert.equal(alerts.length, 1, "the superadmin gets one message"); + assert.ok(bugsink.ingested.length > ingested, "the error tracker has the exception"); + // Ten minutes later the same error: no second message. + await autonomy(new Date(now.getTime() + 10 * 60_000)); + assert.equal((await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")).length, 1); + assert.equal((await openOf(p.id)).length, 0); + } finally { + db.run(sql`ALTER TABLE runner_tasks_x RENAME TO runner_tasks`); + } + }); + + test("Понятный отказ", async () => { + assert.equal(await core.platformFailure(db, new core.PeppaError("Подписка не выбрана — выберите её в настройках проекта."), { service: "watchdog", where: "dispatch PAY-7" }), "Подписка не выбрана — выберите её в настройках проекта."); + assert.equal(await core.platformFailure(db, new Error("SQLITE_ERROR: no such column: x"), { service: "watchdog", where: "dispatch PAY-7" }), null); + }); +}); -- 2.45.2 From dc6eb424a9894ec1ad96266cb76cfbee7332d845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:24:37 +0500 Subject: [PATCH 008/185] PEP-155: plain last line, phone layout, AGENTS.md Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 1 + AGENTS.md | 1 + apps/web/app/(app)/chats/[chat]/page.tsx | 4 ++-- apps/web/components/ChatThreadList.tsx | 2 +- .../changes/pep-155-chat-thread-list/tasks.md | 16 ++++++++-------- packages/core/src/chat-threads.ts | 13 ++++++++----- packages/testkit/test/chats.test.ts | 3 ++- 7 files changed, 23 insertions(+), 17 deletions(-) diff --git a/.peppa/memory.md b/.peppa/memory.md index aedf6b99..9c3d4814 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -44,3 +44,4 @@ - Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй или `glossary-ignore`; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ). - Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`. Состояние — settings `question.state:`, `chat.repeat:`. В тесте нужен второй вопрос — меняй статус, коммит в check_runs или текст. - Продукт по ссылке (PEP-145): ссылка и её статус — только через `projectProduct` (`fix`/`broken`/`preparing`) и `productUrls`/`productLookLine`; системную стори заводит `productLinkTick` (в тестах выключен в helpers.ts, свой тест делает `delete process.env.PEPPA_PRODUCT_LINK`); «Показывать всем» — `getPublishMode`/`autoPublish` (вернул true — вопрос с кнопкой не слать). Менял `template/` — после мержа `scripts/push-template.sh`. +- Список переписки проекта (PEP-155): группы и строка треда — только `projectThreadList`/`threadGroup`/`plainLine` (core/chat-threads.ts); непрочитанное — `chat.threads.read::`; поиск по кириллице — в JS, не LIKE; телефон — `?list=1`. diff --git a/AGENTS.md b/AGENTS.md index 577e31f0..ae2b255e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ - **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts` - **Группы чатов через свой бот (PEP-109)**: «Связать с Telegram» в чате — через собственного бота пользователя (PEP-85): `chats.tg_bot_user_id` (миграция 0018; null — общий бот, им связывает только суперадмин без своего бота: `createChatLinkCode(…, { sharedBot })`, остальным без бота — отказ с подсказкой). Код привязан к боту (`botUserId` в настройке кода): `acceptChatLink` принимает только от него и чужим ботом не сжигается; на `/link` без `@бота` с чужим кодом бот молчит (`chatLinkCodeBot`). Бот: `ownByChat` дополняется группами (`chatGroupBots` в `syncOwnBots`) — исходящие в группу идут через бота связки; входящие сообщения и кнопки группы обрабатывает только он (`linkedHere`). `clearUserBot` / `setUserBot` с другим ботом отвязывают его группы. Тест `chats-own-bot.test.ts` - **Обсуждение проекта (PEP-106)**: чат проекта открывается на «Обсуждении» — только сообщения людей в канале (`discussionMessages`: `thread_key` null, `kind` user, не команда); события агентов — `/chats/KEY?thread=feed`. `markDiscussionRead`/`discussionUnread` (`chat.read::`) → счётчик `navCounts.chats`, плашки чатов, ссылка «Обсуждение» после «Доски» на странице проекта. `postToChat` в канал проекта уведомляет остальных (`projectAudience`) событием уведомлений `chat`. `pruneChats` обсуждение не удаляет. Агентам обсуждение не уходит. Тест `discussion.test.ts` +- **Список переписки проекта (PEP-155)**: `/chats/KEY` слева — `components/ChatThreadList.tsx` из `projectThreadList(db, user, chat, { q })` (`core/chat-threads.ts`; `chatThreads` остался для прочих): «Чат с аналитиком» и «События агентов» сверху, ниже треды задач группами «Ждут вас» (открытый вопрос вида question/approval/permission, `review` без отложенного «Принять», `awaiting_approval`; `attention` сам тред ждущим не делает) · «В работе» · «Готово» (`
    `, свёрнуто; архивные — только в поиске) — правило в `threadGroup`. Строка: ключ, название, `StatusBadge`, `AgentBadge` (живой агент задачи, иначе агент последнего запуска), последнее сообщение одной строкой (`plainLine`: без значка события, код/пути/идентификаторы пропускаются — берётся сообщение раньше; у вопроса — сам вопрос), время, непрочитанное. Непрочитанное по тредам — `settings` `chat.threads.read::` `{base, seen}` (первый взгляд на список ставит `base`, `markThreadRead` при открытии треда; свои сообщения не считаются). Поиск `?q=` — ключ, название, текст сообщений чата (в JS: SQLite не сворачивает регистр кириллицы; последние 20 000 сообщений), в строке — найденный кусок. Телефон: `?list=1` — список вместо сообщений, без него — открытая переписка и «← К списку» (на широком экране обе колонки). Тест `chats.test.ts` - **Чат с аналитиком (PEP-110)**: сообщение человека в обсуждении проекта (PEP-106) → `analystChatTick` в тике вачдога (`runner/analyst-chat.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`, `PEPPA_ANALYST_CHAT_MODEL`), контекст `core/analyst-chat.ts` (`intakeContext` + `projectStatusBlock` со ссылками «где что смотреть»), ответ `{reply, create[]}` → сообщение `kind: user, authorKind: agent, authorLogin: «Аналитик»` в то же обсуждение + событие уведомлений `chat`; стори из `create` — только по явной просьбе, intake у них `done`. Курсор `chat.analyst:`, `analystPending` («печатает…»), сообщения старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) пропускаются, сбой — одна заметка без повторов, `PEPPA_ANALYST_CHAT=off`. Мок — роль `chat` в `mock-intake`; тест `analyst-chat.test.ts` - **Без повторов (PEP-151)**: одно состояние задачи — одно сообщение. `core/message-state.ts`: отпечаток (`messageFingerprint`: задача · вид вопроса · тип · статус · адрес результата · головной коммит и состояние проверок из `check_runs` · нормализованный текст без чисел и хэшей), `raiseOnce` внутри `raiseSessionQuestion` и `askPm`: отпечаток совпал с открытым сообщением задачи или с её последним — новый вопрос не создаётся, прежний получает свежий текст, снова открывается и считает повторы (`settings` `question.state:` `{fp, repeats, updatedAt}`; без миграции; вопросы без такой строки — старые, не сравниваются; окно 7 дней). Тип сообщения — `topic` у вызова: `turn` (конец хода агента, Stop-хук) и `review` («готово», `sendReviewCard` с головой PR — ищется среди всех сообщений задачи): с ним текст в отпечаток не входит. Виды `question`/`permission`/`approval` совпадают только с открытым. Новое место, которое шлёт пользователю свободный текст агента, — передавай `topic`. Чат: `syncChats` не вставляет событие с тем же текстом, что последняя строка треда задачи, а считает его на ней (`chat.repeat:`); виды сообщений отдают `repeats`/`updatedAt`. Telegram: `reconcile` бота правит уже отправленное сообщение (`qe::<повтор>`, не чаще `repeatEditMs` = 5 мин), «отвечено» после повтора — ключ `qa::r<повтор>:<чат>`. `remindTick` обновляет время сообщения (`touchQuestion`). Веб: `QuestionCard` — «обновлено …», «Повторов: N» под «Подробнее»; в чате у события «×N». Тест `no-repeats.test.ts` - **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики» diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 718db789..f1a8874b 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -225,9 +225,9 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ))} -
    +
    {threads && ( -
    +
    )} diff --git a/apps/web/components/ChatThreadList.tsx b/apps/web/components/ChatThreadList.tsx index 9ff610c4..6bf2a195 100644 --- a/apps/web/components/ChatThreadList.tsx +++ b/apps/web/components/ChatThreadList.tsx @@ -46,7 +46,7 @@ export async function ChatThreadList({ const total = list.waiting.length + list.working.length + list.done.length; const rows = (items: ThreadRow[]) => items.map((r) => ); return ( -
    ); @@ -497,6 +512,15 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr + {p.deletedAt && ( +
    + {t("Проект удалён владельцем. Он хранится ещё {days} дн., потом исчезнет насовсем.", { days: trashDaysLeft(p) })} +
    + + + +
    + )} {created && !error && !engineer && {t("Проект создан. Напишите первую задачу — кнопка «Задача» справа вверху.")}} {created && !error && engineer && ( diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 24a97699..05ac17ac 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -1,7 +1,7 @@ // Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; -import { questionIsFreeText, questionState, questionText, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; +import { questionIsFreeText, trashDaysLeft, questionState, questionText, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { db } from "@/lib/db"; import { SubscriptionName } from "@/components/SubscriptionName"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; @@ -263,7 +263,8 @@ export async function ProjectList({ projects, userId, engineer = false }: { proj {p.key} {p.name} - {p.ownerId !== userId && {p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}} + {p.deletedAt && {t("удалён, ещё {days} дн.", { days: trashDaysLeft(p) })}} + {!p.deletedAt && p.ownerId !== userId && {p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}} {engineer && ( diff --git a/openspec/changes/archive/2026-11-16-pep-163-delete-project/design.md b/openspec/changes/archive/2026-11-16-pep-163-delete-project/design.md new file mode 100644 index 00000000..71ffa9f2 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-163-delete-project/design.md @@ -0,0 +1,6 @@ +## Решения +- Мягкое удаление: колонки `projects.deleted_at`, `deleted_by` (миграция 0021). Ссылки каскадные, поэтому окончательное удаление — обычный `DELETE` строки проекта. +- Доступ: `userProjectIds` и `listProjects` скрывают удалённые; `projectForUser` пускает к удалённому только суперадмина. Вся остальная логика (вопросы, уведомления, палитра) идёт через `userProjectIds`. +- `deleteProject` (runner) останавливает активные сессии; вачдог-диспетчеры идут через `listProjects` и `intakeTick` и пропускают удалённые. +- Срок — `PEPPA_PROJECT_TRASH_DAYS` (7). Платформенный проект (`PEPPA_PLATFORM_KEY`) удалить нельзя. Репозиторий Gitea и рабочая копия остаются на диске — их чистка вне scope. +- Возврат — только суперадмин (кнопка на странице проекта). diff --git a/openspec/changes/archive/2026-11-16-pep-163-delete-project/proposal.md b/openspec/changes/archive/2026-11-16-pep-163-delete-project/proposal.md new file mode 100644 index 00000000..1bb8c4eb --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-163-delete-project/proposal.md @@ -0,0 +1,8 @@ +## Why +Пользователь не может убрать ненужный проект. Удаление сразу и навсегда страшно, поэтому проект ещё неделю хранится у суперадмина. + +## What Changes +- Владелец удаляет проект кнопкой «Удалить проект» в настройках (с отметкой-подтверждением). +- Проект пропадает у владельца и участников, агенты проекта останавливаются, диспетчеры его не трогают. +- Суперадмин видит проект в «Проектах других» с пометкой «удалён, ещё N дн.» и может его вернуть. +- Через 7 дней вачдог удаляет запись проекта навсегда (репозиторий в Gitea не трогаем). diff --git a/openspec/changes/archive/2026-11-16-pep-163-delete-project/specs/project-sharing/spec.md b/openspec/changes/archive/2026-11-16-pep-163-delete-project/specs/project-sharing/spec.md new file mode 100644 index 00000000..8b693a23 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-163-delete-project/specs/project-sharing/spec.md @@ -0,0 +1,29 @@ +## ADDED Requirements + +### Requirement: Удаление проекта с неделей хранения +Владелец проекта SHALL удалять проект; удалённый проект скрыт у владельца и участников, его агенты остановлены, а суперадмин видит его ещё 7 дней и может вернуть. По истечении срока проект удаляется навсегда. + +#### Scenario: Владелец удаляет проект +- **GIVEN** проект «Demo» с владельцем «anna» и участником «boris» +- **WHEN** «anna» удаляет проект +- **THEN** проекта нет в списках «anna» и «boris», его страница даёт «Не найдено» +- **AND** суперадмин видит «Demo» в «Проектах других» с пометкой «удалён, ещё 7 дн.» + +#### Scenario: Участник пытается удалить +- **GIVEN** проект «Demo», «boris» — участник +- **WHEN** «boris» пытается удалить проект +- **THEN** ошибка, проект на месте + +#### Scenario: Суперадмин возвращает проект +- **GIVEN** удалённый проект «Demo» +- **WHEN** суперадмин нажимает «Вернуть проект» +- **THEN** проект снова в списках владельца и участников + +#### Scenario: Неделя прошла +- **GIVEN** проект удалён 8 дней назад +- **WHEN** вачдог делает очередной тик +- **THEN** проект удалён навсегда, даже суперадмин его не находит + +#### Scenario: Платформенный проект +- **WHEN** владелец пытается удалить платформенный проект +- **THEN** ошибка «Этот проект удалить нельзя» diff --git a/openspec/changes/archive/2026-11-16-pep-163-delete-project/tasks.md b/openspec/changes/archive/2026-11-16-pep-163-delete-project/tasks.md new file mode 100644 index 00000000..2ae9bbab --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-163-delete-project/tasks.md @@ -0,0 +1,11 @@ +## 1. Данные и ядро +- [x] 1.1 Колонки `deleted_at`/`deleted_by`, миграция +- [x] 1.2 Доступ: `userProjectIds`, `listProjects`, `projectForUser`, intake +- [x] 1.3 `core/project-trash.ts`, `runner/project-trash.ts`, тик вачдога +## 2. Веб +- [x] 2.1 Кнопка «Удалить проект», плашка и «Вернуть проект», пометка в списке, переводы en/kk +## 3. Проверка +- [x] 3.1 Тест `project-trash.test.ts` по сценариям +- [x] 3.2 lint, typecheck, i18n, тесты +## 4. Завершение +- [x] 4.1 AGENTS.md, память, archive, PR diff --git a/openspec/specs/project-sharing/spec.md b/openspec/specs/project-sharing/spec.md index b14417e9..a86fa8a5 100644 --- a/openspec/specs/project-sharing/spec.md +++ b/openspec/specs/project-sharing/spec.md @@ -50,3 +50,31 @@ #### Scenario: Соавтор - **WHEN** владелец добавляет участника в проект, репозиторий которого он администрирует - **THEN** участник — соавтор репозитория с правом write + +### Requirement: Удаление проекта с неделей хранения +Владелец проекта SHALL удалять проект; удалённый проект скрыт у владельца и участников, его агенты остановлены, а суперадмин видит его ещё 7 дней и может вернуть. По истечении срока проект удаляется навсегда. + +#### Scenario: Владелец удаляет проект +- **GIVEN** проект «Demo» с владельцем «anna» и участником «boris» +- **WHEN** «anna» удаляет проект +- **THEN** проекта нет в списках «anna» и «boris», его страница даёт «Не найдено» +- **AND** суперадмин видит «Demo» в «Проектах других» с пометкой «удалён, ещё 7 дн.» + +#### Scenario: Участник пытается удалить +- **GIVEN** проект «Demo», «boris» — участник +- **WHEN** «boris» пытается удалить проект +- **THEN** ошибка, проект на месте + +#### Scenario: Суперадмин возвращает проект +- **GIVEN** удалённый проект «Demo» +- **WHEN** суперадмин нажимает «Вернуть проект» +- **THEN** проект снова в списках владельца и участников + +#### Scenario: Неделя прошла +- **GIVEN** проект удалён 8 дней назад +- **WHEN** вачдог делает очередной тик +- **THEN** проект удалён навсегда, даже суперадмин его не находит + +#### Scenario: Платформенный проект +- **WHEN** владелец пытается удалить платформенный проект +- **THEN** ошибка «Этот проект удалить нельзя» diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index efa518ee..65546b85 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,6 +2,7 @@ export * from "./errors.ts"; export * from "./notify.ts"; export * from "./project-file.ts"; export * from "./projects.ts"; +export * from "./project-trash.ts"; export * from "./tasks.ts"; export * from "./questions.ts"; export * from "./sessions.ts"; diff --git a/packages/core/src/project-trash.ts b/packages/core/src/project-trash.ts new file mode 100644 index 00000000..72442548 --- /dev/null +++ b/packages/core/src/project-trash.ts @@ -0,0 +1,47 @@ +import { m as tr } from "@peppa/shared/i18n"; +import { projects, type Db } from "@peppa/db"; +import { and, eq, isNotNull, lt } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { logEvent } from "./audit.ts"; +import { isSuperadmin } from "./monitor.ts"; +import { getUser } from "./users.ts"; +import type { Project } from "./projects.ts"; + +/** PEP-163: a deleted project stays with the superadmin this many days, then goes for good. */ +export function projectTrashDays(): number { + const n = Number(process.env.PEPPA_PROJECT_TRASH_DAYS); + return Number.isFinite(n) && n > 0 ? n : 7; +} + +const DAY_MS = 86_400_000; + +/** Whole days left before the purge (0 — the next watchdog tick takes it). */ +export function trashDaysLeft(p: Pick, now = new Date()): number { + if (!p.deletedAt) return projectTrashDays(); + return Math.max(0, Math.ceil((p.deletedAt.getTime() + projectTrashDays() * DAY_MS - now.getTime()) / DAY_MS)); +} + +/** Marks the project deleted: only its owner or a superadmin; the platform project never. */ +export async function markProjectDeleted(db: Db, project: Project, userId: number): Promise { + if (project.key === (process.env.PEPPA_PLATFORM_KEY || "PEP")) throw new PeppaError(tr("Этот проект удалить нельзя")); + const user = await getUser(db, userId); + if (project.ownerId !== userId && !(await isSuperadmin(db, user))) throw new PeppaError(tr("Удалить проект может только его владелец")); + if (project.deletedAt) return; + await db.update(projects).set({ deletedAt: new Date(), deletedBy: userId }).where(eq(projects.id, project.id)); + await logEvent(db, { projectId: project.id, type: "project_deleted", payload: { by: userId } }); +} + +/** Superadmin brings a deleted project back. */ +export async function restoreProject(db: Db, projectId: number, userId: number): Promise { + if (!(await isSuperadmin(db, await getUser(db, userId)))) throw new PeppaError(tr("Не найдено")); + const [p] = await db.update(projects).set({ deletedAt: null, deletedBy: null }).where(and(eq(projects.id, projectId), isNotNull(projects.deletedAt))).returning(); + if (!p) throw new PeppaError(tr("Не найдено")); + await logEvent(db, { projectId, type: "project_restored", payload: { by: userId } }); +} + +/** Removes projects deleted longer than the trash period ago. Returns their keys. */ +export async function purgeDeletedProjects(db: Db, now = new Date()): Promise { + const cutoff = new Date(now.getTime() - projectTrashDays() * DAY_MS); + const rows = await db.delete(projects).where(and(isNotNull(projects.deletedAt), lt(projects.deletedAt, cutoff))).returning({ key: projects.key }); + return rows.map((r) => r.key); +} diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts index 8bd03813..d8077ab0 100644 --- a/packages/core/src/projects.ts +++ b/packages/core/src/projects.ts @@ -1,5 +1,5 @@ import { chats, goals, projects, type Db } from "@peppa/db"; -import { and, asc, eq, or } from "drizzle-orm"; +import { and, asc, eq, isNull, or } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; export type Project = typeof projects.$inferSelect; @@ -29,8 +29,9 @@ export async function createProject(db: Db, p: NewProject): Promise { return row!; } -export async function listProjects(db: Db): Promise { - return db.select().from(projects).orderBy(asc(projects.key)); +/** Live projects (PEP-163: deleted ones only with `withDeleted`). */ +export async function listProjects(db: Db, opts: { withDeleted?: boolean } = {}): Promise { + return db.select().from(projects).where(opts.withDeleted ? undefined : isNull(projects.deletedAt)).orderBy(asc(projects.key)); } /** Finds a project by task key prefix ("PEP") or slug ("peppa"). */ diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index e68ddf73..9b901842 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -1,7 +1,7 @@ import { m as tr } from "@peppa/shared/i18n"; import { projectInvites, projectMembers, projects, users, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; -import { and, asc, eq, inArray, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm"; import { decrypt, encrypt, hashToken } from "./crypto.ts"; import { randomBytes } from "node:crypto"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; @@ -77,8 +77,12 @@ export function giteaForBot(): GiteaClient { /** Ids of the projects a user owns or is a member of. */ export async function userProjectIds(db: Db, userId: number): Promise { - const owned = await db.select({ id: projects.id }).from(projects).where(eq(projects.ownerId, userId)); - const shared = await db.select({ id: projectMembers.projectId }).from(projectMembers).where(eq(projectMembers.userId, userId)); + const owned = await db.select({ id: projects.id }).from(projects).where(and(eq(projects.ownerId, userId), isNull(projects.deletedAt))); + const shared = await db + .select({ id: projectMembers.projectId }) + .from(projectMembers) + .innerJoin(projects, eq(projects.id, projectMembers.projectId)) + .where(and(eq(projectMembers.userId, userId), isNull(projects.deletedAt))); return [...new Set([...owned, ...shared].map((r) => r.id))]; } @@ -92,6 +96,8 @@ export async function listUserProjects(db: Db, userId: number): Promise { const [row] = await db.select().from(projects).where(eq(projects.id, projectId)); + // PEP-163: a deleted project is only for the superadmin. + if (row?.deletedAt && !(await isSuperadminId(db, userId))) throw new PeppaError(tr("Не найдено")); if (row && row.ownerId !== userId) { const [m] = await db .select() diff --git a/packages/db/migrations/0021_bitter_ares.sql b/packages/db/migrations/0021_bitter_ares.sql new file mode 100644 index 00000000..865cf874 --- /dev/null +++ b/packages/db/migrations/0021_bitter_ares.sql @@ -0,0 +1,2 @@ +ALTER TABLE `projects` ADD `deleted_at` integer;--> statement-breakpoint +ALTER TABLE `projects` ADD `deleted_by` integer REFERENCES users(id); \ No newline at end of file diff --git a/packages/db/migrations/meta/0021_snapshot.json b/packages/db/migrations/meta/0021_snapshot.json new file mode 100644 index 00000000..f00e83b9 --- /dev/null +++ b/packages/db/migrations/meta/0021_snapshot.json @@ -0,0 +1,4399 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "5009efb5-1c75-4e64-a2e2-e70b95ff799c", + "prevId": "53ced319-040c-444d-8e11-97e95c7b2821", + "tables": { + "agents": { + "name": "agents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "character": { + "name": "character", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "agents_name_unique": { + "name": "agents_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_messages": { + "name": "chat_messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "chat_id": { + "name": "chat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "thread_key": { + "name": "thread_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thread_title": { + "name": "thread_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "important": { + "name": "important", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "author_kind": { + "name": "author_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'system'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_message_id": { + "name": "tg_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chat_messages_dedupe_key_unique": { + "name": "chat_messages_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "chat_messages_chat": { + "name": "chat_messages_chat", + "columns": [ + "chat_id", + "id" + ], + "isUnique": false + }, + "chat_messages_created_at": { + "name": "chat_messages_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "chat_messages_tg": { + "name": "chat_messages_tg", + "columns": [ + "tg_chat_id", + "tg_message_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "chat_messages_chat_id_chats_id_fk": { + "name": "chat_messages_chat_id_chats_id_fk", + "tableFrom": "chat_messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_messages_author_user_id_users_id_fk": { + "name": "chat_messages_author_user_id_users_id_fk", + "tableFrom": "chat_messages", + "tableTo": "users", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_question_id_questions_id_fk": { + "name": "chat_messages_question_id_questions_id_fk", + "tableFrom": "chat_messages", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_task_id_tasks_id_fk": { + "name": "chat_messages_task_id_tasks_id_fk", + "tableFrom": "chat_messages", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_title": { + "name": "tg_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_at": { + "name": "tg_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_by": { + "name": "tg_linked_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_bot_user_id": { + "name": "tg_bot_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chats_user_id_unique": { + "name": "chats_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + }, + "chats_project_id_unique": { + "name": "chats_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + }, + "chats_tg_chat_id_unique": { + "name": "chats_tg_chat_id_unique", + "columns": [ + "tg_chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chats_user_id_users_id_fk": { + "name": "chats_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_project_id_projects_id_fk": { + "name": "chats_project_id_projects_id_fk", + "tableFrom": "chats", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_tg_linked_by_users_id_fk": { + "name": "chats_tg_linked_by_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_linked_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chats_tg_bot_user_id_users_id_fk": { + "name": "chats_tg_bot_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_bot_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "feedback": { + "name": "feedback", + "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 + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'received'" + }, + "analysis": { + "name": "analysis", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_error": { + "name": "analysis_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_started_at": { + "name": "analysis_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "option_index": { + "name": "option_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reject_reason": { + "name": "reject_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_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": { + "feedback_user": { + "name": "feedback_user", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + }, + "feedback_status": { + "name": "feedback_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "feedback_user_id_users_id_fk": { + "name": "feedback_user_id_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "feedback_task_id_tasks_id_fk": { + "name": "feedback_task_id_tasks_id_fk", + "tableFrom": "feedback", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "feedback_decided_by_users_id_fk": { + "name": "feedback_decided_by_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "decided_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "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" + }, + "projects_deleted_by_users_id_fk": { + "name": "projects_deleted_by_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "deleted_by" + ], + "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 + }, + "msg_type": { + "name": "msg_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_option": { + "name": "default_option", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_agent_id_agents_id_fk": { + "name": "sessions_agent_id_agents_id_fk", + "tableFrom": "sessions", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "telegram_outbox_chat_message_id_chat_messages_id_fk": { + "name": "telegram_outbox_chat_message_id_chat_messages_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_token_enc": { + "name": "telegram_bot_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_username": { + "name": "telegram_bot_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_sub": { + "name": "google_sub", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_email": { + "name": "google_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_linked_at": { + "name": "google_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 + }, + "users_google_sub_unique": { + "name": "users_google_sub_unique", + "columns": [ + "google_sub" + ], + "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 ca475679..fe28648a 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -148,6 +148,13 @@ "when": 1794812739508, "tag": "0020_fuzzy_plazm", "breakpoints": true + }, + { + "idx": 21, + "version": "6", + "when": 1794821166866, + "tag": "0021_bitter_ares", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 666b1fe1..60692e3e 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -68,6 +68,9 @@ export const projects = sqliteTable("projects", { nextTaskNumber: integer("next_task_number").notNull().default(1), // PEP-67: default subscription pool for the project's runners (set by a superadmin). subscriptionPoolId: integer("subscription_pool_id").references((): AnySQLiteColumn => subscriptionPools.id, { onDelete: "set null" }), + // PEP-163: deleted by the owner — hidden from users, kept for the superadmin until purged. + deletedAt: integer("deleted_at", { mode: "timestamp_ms" }), + deletedBy: integer("deleted_by").references((): AnySQLiteColumn => users.id, { onDelete: "set null" }), createdAt: createdAt(), updatedAt: updatedAt(), }); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 64bb5f6d..42a7dad1 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -27,6 +27,7 @@ export * from "./code.ts"; export * from "./agents-md.ts"; export * from "./project-subscription.ts"; export * from "./intake.ts"; +export * from "./project-trash.ts"; export * from "./story-refine.ts"; export * from "./terminal.ts"; export * from "./claude-print.ts"; diff --git a/packages/runner/src/intake.ts b/packages/runner/src/intake.ts index 52f1375a..fbfc7279 100644 --- a/packages/runner/src/intake.ts +++ b/packages/runner/src/intake.ts @@ -33,6 +33,7 @@ import { } from "@peppa/core"; import type { Db } from "@peppa/db"; import { projects } from "@peppa/db"; +import { isNull } from "drizzle-orm"; import { claudePrint } from "./claude-print.ts"; import { onAnswer, resolveTaskById } from "./sessions.ts"; @@ -151,7 +152,7 @@ export async function intakeTick(db: Db, opts: IntakeTickOptions = {}): Promise< const now = opts.now ?? new Date(); const log = opts.log ?? (() => {}); const jobs: Promise[] = []; - for (const { id } of await db.select({ id: projects.id }).from(projects)) { + for (const { id } of await db.select({ id: projects.id }).from(projects).where(isNull(projects.deletedAt))) { const settings = await getIntakeSettings(db, id); if (!settings.enabled) continue; for (const t of await listTasks(db, { projectId: id, statuses: ["backlog"] })) { diff --git a/packages/runner/src/project-trash.ts b/packages/runner/src/project-trash.ts new file mode 100644 index 00000000..abbe3bb8 --- /dev/null +++ b/packages/runner/src/project-trash.ts @@ -0,0 +1,25 @@ +import { m } from "@peppa/shared/i18n"; +import type { Db } from "@peppa/db"; +import { listSessions, markProjectDeleted, projectForUser, purgeDeletedProjects, type Project } from "@peppa/core"; +import { stopSession } from "./sessions.ts"; + +/** + * PEP-163: the owner deletes a project — its agents stop, it disappears from the people's lists + * and stays with the superadmin for PEPPA_PROJECT_TRASH_DAYS (7). The repository is not touched. + */ +export async function deleteProject(db: Db, userId: number, projectId: number): Promise<{ stopped: number }> { + const project: Project = await projectForUser(db, userId, projectId); + await markProjectDeleted(db, project, userId); + let stopped = 0; + for (const s of await listSessions(db, { active: true, projectId })) { + await stopSession(db, s.id).catch(() => {}); + stopped++; + } + return { stopped }; +} + +/** Watchdog: projects whose week is over go for good. */ +export async function projectTrashTick(db: Db, opts: { now?: Date; log?: (line: string) => void } = {}): Promise { + const keys = await purgeDeletedProjects(db, opts.now ?? new Date()); + for (const key of keys) opts.log?.(m("Проект {key} удалён навсегда: срок хранения вышел", { key })); +} diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index da3d840e..1f4715ba 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -2,6 +2,7 @@ // session dies, stalls, or hits a usage limit. Run under launchd with caffeinate. import { asIs, m } from "@peppa/shared/i18n"; import { runnerTick } from "./runners.ts"; +import { projectTrashTick } from "./project-trash.ts"; import { createHash } from "node:crypto"; import { backupDb, @@ -100,6 +101,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { await subscriptionWarnTick(db, opts.now ?? new Date()).catch(failed(db, log, "subscription warnings")); // Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher. // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them. + // PEP-163: deleted projects leave for good after their week. + await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash")); await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake")); // PEP-115: a comment on a backlog story — the analyst reworks the story. await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine")); diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts index 91408982..c0f6982e 100644 --- a/packages/shared/src/i18n/en/project.ts +++ b/packages/shared/src/i18n/en/project.ts @@ -421,4 +421,14 @@ export const project: Dict = { "Изменить выбор можно в настройках проекта.": "You can change this in the project settings.", "Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (Dockerfile, product/, готовый deploy) и сразу выкладывается на slug-staging.telecom.quest. Нет здоровой версии для проверки при принятых стори или выкладка упала — Peppa FACTORY сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше.": "A product link from day one: a new project is created with the «Product is being built» placeholder (Dockerfile, product/, a ready deploy) and is deployed to slug-staging.telecom.quest right away. No healthy staging while stories are accepted, or a deploy failed — Peppa FACTORY files the story «Продукт должен открываться по ссылке» first in the backlog by itself (one open per project, at most once a day). «⋯ Project settings → Show to everyone»: «Automatically» — a healthy staging whose stories are all accepted goes to prod without the button; «By the button» — as before.", + "Удалить проект": "Delete project", + "Проект пропадёт из вашего списка, а агенты остановятся. Ещё неделю он хранится у администратора Peppa FACTORY — если передумаете, попросите вернуть его. Потом проект удаляется насовсем.": "The project will disappear from your list and the agents will stop. The Peppa FACTORY administrator keeps it for another week — if you change your mind, ask them to bring it back. After that the project is deleted for good.", + "Да, удалить проект {name}": "Yes, delete the project {name}", + "Проект удалён владельцем. Он хранится ещё {days} дн., потом исчезнет насовсем.": "The owner deleted this project. It is kept for {days} more days, then it disappears for good.", + "Вернуть проект": "Bring the project back", + "удалён, ещё {days} дн.": "deleted, {days} days left", + "Отметьте, что хотите удалить проект": "Tick the box to confirm you want to delete the project", + "Этот проект удалить нельзя": "This project cannot be deleted", + "Удалить проект может только его владелец": "Only the project's owner can delete it", + "Проект {key} удалён навсегда: срок хранения вышел": "Project {key} deleted for good: the storage period is over", }; diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts index 97f53c64..fda3a368 100644 --- a/packages/shared/src/i18n/kk/project.ts +++ b/packages/shared/src/i18n/kk/project.ts @@ -366,4 +366,14 @@ export const project: Dict = { "Изменить выбор можно в настройках проекта.": "Таңдауды жоба баптауларында өзгертуге болады.", "Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (Dockerfile, product/, готовый deploy) и сразу выкладывается на slug-staging.telecom.quest. Нет здоровой версии для проверки при принятых стори или выкладка упала — Peppa FACTORY сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше.": "Өнім бірінші күннен сілтеме бойынша ашылады: жаңа жоба «Өнім жасалып жатыр» бітеуішімен (Dockerfile, product/, дайын deploy) құрылады және бірден slug-staging.telecom.quest мекенжайына шығарылады. Сторилер қабылданған, бірақ сау staging жоқ немесе шығару құлады — Peppa FACTORY «Продукт должен открываться по ссылке» сторисін бэклогтың басына өзі қосады (жобаға бір ашық стори, тәулігіне бір реттен жиі емес). «⋯ Жоба баптаулары → Барлығына көрсету»: «Өзі» — барлық сторилері қабылданған сау staging батырмасыз prod-қа шығады; «Батырмамен» — бұрынғыдай.", + "Удалить проект": "Жобаны жою", + "Проект пропадёт из вашего списка, а агенты остановятся. Ещё неделю он хранится у администратора Peppa FACTORY — если передумаете, попросите вернуть его. Потом проект удаляется насовсем.": "Жоба тізімнен жоғалады, агенттер тоқтайды. Peppa FACTORY әкімшісінде ол тағы бір апта сақталады — ойыңыз өзгерсе, қайтаруын сұраңыз. Содан кейін жоба біржола жойылады.", + "Да, удалить проект {name}": "Иә, {name} жобасын жою", + "Проект удалён владельцем. Он хранится ещё {days} дн., потом исчезнет насовсем.": "Жобаны иесі жойды. Ол тағы {days} күн сақталады, содан кейін біржола жоғалады.", + "Вернуть проект": "Жобаны қайтару", + "удалён, ещё {days} дн.": "жойылған, тағы {days} күн", + "Отметьте, что хотите удалить проект": "Жобаны жойғыңыз келетінін белгілеңіз", + "Этот проект удалить нельзя": "Бұл жобаны жоюға болмайды", + "Удалить проект может только его владелец": "Жобаны тек оның иесі жоя алады", + "Проект {key} удалён навсегда: срок хранения вышел": "{key} жобасы біржола жойылды: сақтау мерзімі аяқталды", }; diff --git a/packages/testkit/test/project-trash.test.ts b/packages/testkit/test/project-trash.test.ts new file mode 100644 index 00000000..0e622661 --- /dev/null +++ b/packages/testkit/test/project-trash.test.ts @@ -0,0 +1,69 @@ +// PEP-163: the owner deletes a project — it disappears for people, stays a week with the +// superadmin (who may restore it), then goes for good. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { core, db, runner, setDefaultOwner, project, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +let owner: Awaited>; +let member: typeof owner; +let admin: typeof owner; + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 9601, login: "owner163" }, { access_token: "x" }); + member = await core.upsertUserFromGitea(db, { id: 9602, login: "member163" }, { access_token: "x" }); + admin = await core.upsertUserFromGitea(db, { id: 9603, login: "admin163" }, { access_token: "x" }); + await core.setSetting(db, "platform.admins", ["admin163"]); + setDefaultOwner(owner.id); +}); +after(teardown); + +describe("удаление проекта", () => { + test("владелец удаляет: проект пропал у него и у участника, суперадмин видит", async () => { + const tp = await project({}); + const p = await core.getProject(db, tp.key); + await core.addMember(db, p, "member163", owner.id); + assert.ok((await core.userProjectIds(db, member.id)).includes(p.id)); + await runner.deleteProject(db, owner.id, p.id); + assert.ok(!(await core.userProjectIds(db, owner.id)).includes(p.id)); + assert.ok(!(await core.userProjectIds(db, member.id)).includes(p.id)); + await assert.rejects(core.projectForUser(db, owner.id, p.id)); + await assert.rejects(core.projectForUser(db, member.id, p.id)); + assert.equal((await core.projectForUser(db, admin.id, p.id)).id, p.id); + assert.ok((await core.listOtherProjects(db, admin.id)).some((x) => x.id === p.id && x.deletedAt)); + assert.ok(!(await core.listProjects(db)).some((x) => x.id === p.id)); + }); + + test("участник удалить не может", async () => { + const tp = await project({}); + const p = await core.getProject(db, tp.key); + await core.addMember(db, p, "member163", owner.id); + await assert.rejects(runner.deleteProject(db, member.id, p.id)); + assert.ok((await core.userProjectIds(db, owner.id)).includes(p.id)); + }); + + test("суперадмин возвращает проект", async () => { + const tp = await project({}); + const p = await core.getProject(db, tp.key); + await runner.deleteProject(db, owner.id, p.id); + await assert.rejects(core.restoreProject(db, p.id, owner.id)); + await core.restoreProject(db, p.id, admin.id); + assert.ok((await core.userProjectIds(db, owner.id)).includes(p.id)); + }); + + test("через неделю проект удаляется насовсем, раньше — нет", async () => { + const tp = await project({}); + const p = await core.getProject(db, tp.key); + await runner.deleteProject(db, owner.id, p.id); + const day = 86_400_000; + await runner.projectTrashTick(db, { now: new Date(Date.now() + 6 * day) }); + assert.equal(core.trashDaysLeft((await core.projectForUser(db, admin.id, p.id)), new Date(Date.now() + 6 * day)), 1); + await runner.projectTrashTick(db, { now: new Date(Date.now() + 8 * day) }); + await assert.rejects(core.projectForUser(db, admin.id, p.id)); + }); + + test("платформенный проект не удаляется", async () => { + const p = await core.createProject(db, { slug: "peppa163", key: "PEP", name: "Peppa", giteaOwner: "t", workspacePath: "/tmp/x163", ownerId: owner.id }); + await assert.rejects(runner.deleteProject(db, owner.id, p.id)); + }); +}); -- 2.45.2 From b1c13e739e76af98ae4e3bd628c3d1b8e9119443 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 14:02:24 +0500 Subject: [PATCH 017/185] PEP-165: the live site runs next start; deploy builds before restarting web Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- scripts/install-launchd.sh | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f0517e39..2e565053 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -97,7 +97,7 @@ - **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта - `template/` — содержимое репо `peppa/template` в Gitea (`GITEA_TEMPLATE_REPO`) (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), организация `peppa` (PEP-4; владелец — `peppa-bot`): репо `peppa/peppa` (эта платформа, `GITEA_PLATFORM_REPO` — футер, `scripts/ci.sh --pr`, `peppa-release.sh`) и `peppa/template`; старые адреса `peppa-bot/peppa|template` редиректит Gitea, пока репозитории с такими именами не созданы заново — не создавать; проекты пользователей без Gitea остаются в пространстве `peppa-bot`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем -- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Всё, что вкладка браузера заставляет dev-сервер писать под `.next`, он видит как изменение и обновляет страницы по кругу — в `next.config.ts` выключены `logging.browserToTerminal` (PEP-119) и `experimental.mcpServer` (PEP-144: файл `.next/dev/logs/next-development.log`); тест `dev-server-config.test.ts` Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже +- **До официального запуска (сейчас)**: `peppa.telecom.quest` — **`next start` (рабочий режим, PEP-165)** из рабочей копии `/Users/telecom/Dev/Peppa`; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. **Выкатка**: `git pull` → новые миграции — `peppa db backup && peppa db migrate` (до кода) → `(set -a; . .env; set +a; cd apps/web && ./node_modules/.bin/next build)` → `launchctl kickstart -k` web, watchdog, bot → `/api/health` с новым коммитом → проверка в браузере. Без сборки веб показывает старую версию. Установка: `scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh` (режим `start` по умолчанию). `next dev` на живом сайте больше не запускать: 16.11 у всех пользователей страницы перезагружались по кругу — dev-сервер пересобирал страницы и рассылал всем вкладкам «обновиться». Заметки про dev ниже — для локальной разработки и стендов. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Всё, что вкладка браузера заставляет dev-сервер писать под `.next`, он видит как изменение и обновляет страницы по кругу — в `next.config.ts` выключены `logging.browserToTerminal` (PEP-119) и `experimental.mcpServer` (PEP-144: файл `.next/dev/logs/next-development.log`); тест `dev-server-config.test.ts` Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже - **Прод Пеппы (PEP-18, для будущего официального прода)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh `: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index 763f7b40..e3111fb7 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -9,8 +9,9 @@ # ~/.peppa/release-queue has requests (the PM's button) # Prod runs from the release directory: ~/peppa/current/scripts/install-launchd.sh, so every # path below (and PEPPA_ROOT for hooks and git config) is ~/peppa/current, not a release. -# Pre-launch (everything is dev): PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot -# from the working copy — no release agent, so nothing replaces what this checkout serves. +# Pre-launch (PEP-165): scripts/install-launchd.sh watchdog web bot from the working copy — web in +# `start` mode (build first: `next build` in apps/web), no release agent. Never `next dev` on the live +# site: its rebuilds made every open tab reload in a loop (16.11). # Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [release] (default: all) # Remove: launchctl bootout gui/$(id -u)/