From 2f924ac6b3d22fa23320ce3867b0a8e128f898fc 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:38:43 +0500 Subject: [PATCH 1/3] =?UTF-8?q?PEP-163:=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?= =?UTF-8?q?=20=E2=80=94=20=D0=BD=D0=B5=D0=B4=D0=B5=D0=BB=D1=8F=20=D1=83=20?= =?UTF-8?q?=D1=81=D1=83=D0=BF=D0=B5=D1=80=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD?= =?UTF-8?q?=D0=B0,=20=D0=BF=D0=BE=D1=82=D0=BE=D0=BC=20=D0=BD=D0=B0=D1=81?= =?UTF-8?q?=D0=BE=D0=B2=D1=81=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .peppa/memory.md | 11 +- AGENTS.md | 1 + apps/web/app/(app)/actions.ts | 19 + apps/web/app/(app)/p/[key]/page.tsx | 24 + apps/web/components/cards.tsx | 5 +- .../design.md | 6 + .../proposal.md | 8 + .../specs/project-sharing/spec.md | 29 + .../tasks.md | 11 + openspec/specs/project-sharing/spec.md | 28 + packages/core/src/index.ts | 1 + packages/core/src/project-trash.ts | 47 + packages/core/src/projects.ts | 7 +- packages/core/src/users.ts | 12 +- packages/db/migrations/0021_bitter_ares.sql | 2 + .../db/migrations/meta/0021_snapshot.json | 4399 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 3 + packages/runner/src/index.ts | 1 + packages/runner/src/intake.ts | 3 +- packages/runner/src/project-trash.ts | 25 + packages/runner/src/watchdog.ts | 3 + packages/shared/src/i18n/en/project.ts | 10 + packages/shared/src/i18n/kk/project.ts | 10 + packages/testkit/test/project-trash.test.ts | 69 + 25 files changed, 4727 insertions(+), 14 deletions(-) create mode 100644 openspec/changes/archive/2026-11-16-pep-163-delete-project/design.md create mode 100644 openspec/changes/archive/2026-11-16-pep-163-delete-project/proposal.md create mode 100644 openspec/changes/archive/2026-11-16-pep-163-delete-project/specs/project-sharing/spec.md create mode 100644 openspec/changes/archive/2026-11-16-pep-163-delete-project/tasks.md create mode 100644 packages/core/src/project-trash.ts create mode 100644 packages/db/migrations/0021_bitter_ares.sql create mode 100644 packages/db/migrations/meta/0021_snapshot.json create mode 100644 packages/runner/src/project-trash.ts create mode 100644 packages/testkit/test/project-trash.test.ts diff --git a/.peppa/memory.md b/.peppa/memory.md index b9cad87b..352390aa 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -12,11 +12,11 @@ - Общая рабочая копия может стоять на чужой ветке — работай в `git worktree`; CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `/packages/cli/bin/peppa …`. - Шаблонная строка с t()/m() внутри (`` `${t("…")}` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`. - Gitea 1.22 `GET /compare/...` принимает только имена веток (SHA → 404, PEP-101; mock-gitea так же) — сравнение подсказка, не гейт. -- Homebrew на Mac Пеппы чужой — brew install из сессии не проходит. Headless Chrome на macOS игнорирует --use-file-for-fake-audio-capture: подменяй getUserMedia через Page.addScriptToEvaluateOnNewDocument. +- Homebrew на Mac Пеппы чужой — brew install из сессии не проходит. - localizeText выбирает вариант по числу НЕпереведённых русских букв (Rendered.left), не по кириллице: казахский тоже кириллица. Эвристика «есть кириллица = не переведено» ломает kk. -- Безопасность (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-133): git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`; заголовки — headers() в next.config.ts, script-CSP не строгий. +- Экраны на `next dev`: открывай `http://localhost:<порт>`, не 127.0.0.1 (иначе без гидрации); `PEPPA_WEB_URL` для login-link тот же, ссылка одноразовая. +- `next dev`: всё, что вкладка пишет под `.next`, гонит обновления по кругу — в next.config.ts выключены `logging.browserToTerminal` и `experimental.mcpServer` (PEP-144). Тест testkit не импортирует apps/web статически — грузить через `import(new URL(…).href)`. - Раннер проверок (PEP-157): `capacity` в infra/act-runner/config.yaml — на регистрацию, применяется только перезапуском `peppa-act-runner` (убивает идущие проверки); конфиг смонтирован файлом из живой рабочей копии и после git checkout пропадает в контейнере (PEP-162). - mock-gitea `POST /tags` ставит настоящий git-тег: репозиторию нужны коммиты (`addRepo(…, { files })`), а target — существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Новое слово в «Нельзя» docs/glossary.md проверяй `pnpm lint` сразу: оно может уже стоять в чужих текстах («хост», «эндпоинт»). @@ -26,8 +26,9 @@ - Чаты (PEP-62) — проекция: новое событие = строка в EVENT_TEXT (core/chats.ts); сообщения с TTL, правда — events/questions/releases/incidents. - tmux-сервер по умолчанию: newSession чистит глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69); агенту — только через new-session -e. - Вход через Google (PEP-90): идентичность — google_sub, по почте не склеиваем; без GOOGLE_CLIENT_ID/SECRET кнопки нет; в тестах GOOGLE_OAUTH_BASE (mock-google). `pnpm typecheck` в apps/web может падать на устаревших .next/types. -- Распознавание речи (PEP-108): faster-whisper на 127.0.0.1:8178 (launchd quest.telecom.peppa.whisper, infra/whisper/); клиент core/transcribe.ts, включено = PEPPA_TRANSCRIBE_URL; кнопка — `` (MediaRecorder), не Web Speech API. +- Речь (PEP-108): faster-whisper 127.0.0.1:8178 (infra/whisper/), клиент core/transcribe.ts, включено = PEPPA_TRANSCRIBE_URL; ``. - Тексты режима «Продакт» (PEP-125): новый текст или экран режима — в списки TEXTS/SCREENS теста `i18n-product-mode.test.ts` (три языка, слово вида, i18n-check по экранам). +- Удаление проекта (PEP-163): мягкое, `projects.deleted_at`; перечисляй проекты через `listProjects(db)`/`userProjectIds`, в тиках прямой `from(projects)` — с `isNull(projects.deletedAt)`. ## Соглашения - i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en/<раздел>.ts` и `i18n/kk/<раздел>.ts` (PEP-99, те же разделы; тесты i18n-check и i18n-kk падают без перевода). Ключ-шаблон, кончающийся плейсхолдером, — специфичный. Название — «Peppa FACTORY» на всех языках, не склоняется по-русски; в kk окончание через дефис (Peppa FACTORY-нің/-ге/-де); к {плейсхолдеру} kk-окончание не клеить — фраза вокруг именительного («Жаңа {task}»); `wording(mode,"kk")` отдаёт именительный. Тексты для агентов (RULES.md, промпты, хук) говорят «Пеппа» — не трогаем. diff --git a/AGENTS.md b/AGENTS.md index f0517e39..84d0720a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,6 +61,7 @@ - **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула - **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:` {enabled, waitMin, since}, состояние `intake.task:`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`) - **Свой Telegram-бот (PEP-85)**: `users.telegram_bot_token_enc` (в `encryptedColumns`) + `telegram_bot_username` (миграция 0016). core/telegram.ts: `verifyBotToken`, `setUserBot`/`clearUserBot`, `userBots`; `acceptPairing(…, { botUserId })` — свой бот привязывает только владельца, общий не привязывает того, у кого есть свой; `getOffset`/`claimUpdate` принимают `botUserId` (ключ обновления `userId·2^36 + update_id`). apps/bot: `syncOwnBots` (раз в `userBotsIntervalMs`), `ownPollLoop`, обработка внутри `via.run(bot)`, объект `api` маршрутизирует вызов: бот текущего обновления → бот владельца `chat_id` → общий. Группы и каналы — только общий бот. Веб «Настройки → Telegram»: три шага. Тест `own-bot.test.ts` — два `MockTelegram` (`userApi` в опциях бота) +- **Удаление проекта (PEP-163)**: `projects.deleted_at`/`deleted_by` (миграция 0021). Владелец — «⋯ Настройки проекта → Удалить проект» (`deleteProjectAction` → `deleteProject` в runner/project-trash.ts: `markProjectDeleted` + остановка сессий). Удалённый скрыт: `userProjectIds`, `listProjects(db)` (диспетчеры, intake) его не отдают, `projectForUser` пускает только суперадмина; он видит его в «Проектах других» («удалён, ещё N дн.») и жмёт «Вернуть проект» (`restoreProject`). `projectTrashTick` в вачдоге после `PEPPA_PROJECT_TRASH_DAYS` (7) делает `DELETE` строки (FK каскадные); репозиторий в Gitea и рабочая копия остаются. Платформенный проект не удаляется. Тест `project-trash.test.ts` - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member - **Перенос репозитория проекта (PEP-4)**: `peppa project transfer ` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo---`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно - **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 3def96ff..1172625a 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -63,6 +63,8 @@ import { setUiMode, } from "@peppa/core"; import { fixFeedback, linkFeedback, rejectFeedback } from "@peppa/core"; +import { restoreProject } from "@peppa/core"; +import { deleteProject } from "@peppa/runner"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; import { acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner"; @@ -405,6 +407,23 @@ export async function grantRepoAccessToMembers(f: FormData) { }); } +/** PEP-163: the owner deletes the project; it stays with the superadmin for a week. */ +export async function deleteProjectAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + if (str(f, "confirm") !== "yes") throw new PeppaError(m("Отметьте, что хотите удалить проект")); + await deleteProject(db, user.id, Number(str(f, "projectId"))); + return "/projects"; + }); +} + +export async function restoreProjectAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + await restoreProject(db, Number(str(f, "projectId")), user.id); + }); +} + export async function setProjectVisibilityAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 50f4c153..45eb660f 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -37,6 +37,8 @@ import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/c import { saveProjectBudgetAction } from "../../actions"; // PEP-127: on its own line — the long @peppa/core import above is edited by every story. import { listPendingAccepts, PENDING_ACCEPT_LABEL } from "@peppa/core"; +import { trashDaysLeft } from "@peppa/core"; +import { deleteProjectAction, restoreProjectAction } from "../../actions"; const RELEASE_STATUS: Record = { deploying: { label: m("выкатывается"), tone: "info" }, @@ -470,6 +472,19 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr )} {engineer &&

{t("Раннеры проекта стартуют на свободной подписке пула.")} {superadmin ? {t("Пулы и подписки")} : t("Выбирает владелец проекта.")}

} + {p.ownerId === user.id && !p.deletedAt && p.key !== (process.env.PEPPA_PLATFORM_KEY || "PEP") && ( + +

{t("Проект пропадёт из вашего списка, а агенты остановятся. Ещё неделю он хранится у администратора Peppa FACTORY — если передумаете, попросите вернуть его. Потом проект удаляется насовсем.")}

+
+ + + + +
+ )} {!engineer &&

{t("Настройки для разработчиков — код проекта, настройки и расход агентов — открываются в виде «Инженер»:")} {t("Настройки → Вид Peppa FACTORY")}.

} ); @@ -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)); + }); +}); From 228b0fc75825cd029258715cc046ebdad0904dce 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 15:00:58 +0500 Subject: [PATCH 2/3] PEP-163: test scenario typed Co-Authored-By: Claude Sonnet 5.5 --- packages/testkit/test/project-trash.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/testkit/test/project-trash.test.ts b/packages/testkit/test/project-trash.test.ts index 0e622661..872bbf30 100644 --- a/packages/testkit/test/project-trash.test.ts +++ b/packages/testkit/test/project-trash.test.ts @@ -20,7 +20,7 @@ after(teardown); describe("удаление проекта", () => { test("владелец удаляет: проект пропал у него и у участника, суперадмин видит", async () => { - const tp = await project({}); + const tp = await project({ turns: [] }); 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)); @@ -35,7 +35,7 @@ describe("удаление проекта", () => { }); test("участник удалить не может", async () => { - const tp = await project({}); + const tp = await project({ turns: [] }); 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)); @@ -43,7 +43,7 @@ describe("удаление проекта", () => { }); test("суперадмин возвращает проект", async () => { - const tp = await project({}); + const tp = await project({ turns: [] }); 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)); @@ -52,7 +52,7 @@ describe("удаление проекта", () => { }); test("через неделю проект удаляется насовсем, раньше — нет", async () => { - const tp = await project({}); + const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); await runner.deleteProject(db, owner.id, p.id); const day = 86_400_000; From 8bf12f392e9e35c37dc4ac65caad90beeed7c279 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 19:08:02 +0500 Subject: [PATCH 3/3] PEP-173: one reminder about an unanswered question, after 4 hours and only in working time; no escalation by default Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- packages/runner/src/recovery.ts | 33 +++++++++++++++---- packages/testkit/test/no-repeats.test.ts | 2 +- packages/testkit/test/recovery.test.ts | 42 +++++++++++++++++++++++- 4 files changed, 70 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 319de7a3..30c86a89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,7 +20,7 @@ - Шаги агента (PEP-33): хуки `PostToolUse`/`PostToolUseFailure` с `async: true` → `peppa-hook tool-use` → `recordStep` (core/steps.ts: событие `step` `{tool, kind, text, ok}`, последние 200 на сессию, `last_activity_at` без `notify()`); шаги исключены из журнала стори, `get_task` и «Событий» раннера; лента — `components/AgentSteps.tsx` (у живой сессии на странице стори и в панели раннера, новые шаги — событием `step` из `/api/live?scope=steps:`); прогресс tasks.md («7/12» и текущий пункт) — на карточках доски «В работе» и в шапке стори. Codex/OpenCode шагов не шлют - **Раннеры (PEP-10/27/53)**: настройки `core/runners.ts` с наследованием `platform.runner` → `project.runner:` → `task.runner:` (строки `settings`): `mode` story (по умолчанию, один раннер на стори) / queue, `context` fresh / continue, `workspace` shared / worktree, `maxRunners`. История и очередь — таблица `runner_tasks`, имя — `sessions.name`. `moveTask` → `startTaskOnRunner` (runner/runners.ts); переход к следующей стори и переезд очереди упавшего раннера — `runnerTick` в вачдоге; queue: «Готово» освобождает раннер (`releaseRunner`), fresh = `relaunchFresh` (тот же tmux, новое поколение без resume). Worktree — runner/worktree.ts (`$PEPPA_HOME/worktrees//s`, `sessions.workspace_path`, ветка `task/`, уборка когда чисто и всё запушено). Свободный раннер — `startFreeRunner` (без стори; хук не пингует), `promoteRunner` («Оформить стори»), `renameRunner`; CLI `peppa runner new|rename|promote|queue|show|settings` - **Раннер-сервис (PEP-21)**: процессы агентов запускает только вачдог (`peppa watchdog` = раннер-сервис, `serveRunnerCommands` в runner/runner-service.ts). Веб (`instrumentation.ts`) и бот (`apps/bot/src/index.ts`) — клиенты (`setRunnerClient`, флаг в `globalThis`): функции жизненного цикла (`startSession`, `startFreeRunner`, `startTaskOnRunner`, `resumeSession`, `stopSession`, `sendToSession`, `moveTask`, `archiveTask`, `acceptTask`, `acceptStory`, `answerAndDeliver`, `queueTaskOnRunner`, `promoteRunner`) первой строкой уходят в `runnerCall` (runner/runner-client.ts): строка в `runner_commands` (payload — id, автор PEP-48 → `runAsActor` в сервисе) + пинок в `$PEPPA_HOME/runner.sock`, ожидание результата; изменяющие tmux-операции (`newSession`/`killSession`/`sendText`/`sendKeys`/`sendHex`) из прочих путей — командой `tmux` (payload стирается после выполнения). Ключ `task:`/`session:` — одна стори по очереди. Нет сокета → сразу ошибка «Агенты сейчас не запускаются: служба запуска не работает…» (PEP-137; админу — `peppa status` и launchd-агент `quest.telecom.peppa.watchdog`), не взял за 15 с (`PEPPA_RUNNER_PICKUP_SEC`) → `expired` и ошибка, поздно не выполняется; рестарт сервиса → `running` → `failed`. Тесты по умолчанию «на месте» (флаг ставят только бинари); `runAsRunnerService` — контекст сервиса в одном процессе с клиентом. `PEPPA_RUNNER_MODE=inline` — аварийный откат. CLI `session start|send|resume|stop`, `runner new|promote|queue`, `q answer` — через сервис, если он жив; `peppa runner commands`, `peppa status` - - **Вачдог 2.0 (PEP-28, runner/recovery.ts)**: пороги `platform.watchdog` ← env `PEPPA_WATCHDOG_*` ← умолчания (`peppa platform watchdog key=value|reset`: restartMax 3, restartWindowMin 1440, restartDelaysMin 1,5,15, stallRestartMin 60, remindMin 30, escalateMin 120, idleStopHours 24; 0 = выкл). Упал/пропал раннер стори в `proposing`/`in_progress` (не лимит, не пауза бюджета) → `failed` + `watch_state.restartAt` вместо вопроса, `restartTick` делает `resumeSession` (`auto_restarted`); предел исчерпан — вопрос PM с причиной. Зависший без ответа `stallRestartMin` после алерта — kill + перезапуск. `remindTick`: вопросы question/permission/approval моложе суток — напоминания аудитории (`questions.reminders` 1,2; событие `questions`), затем `alertAdmins` (3); claim атомарный. `idleStopTick`: `waiting_input` без открытых вопросов дольше `idleStopHours` → `stopSession` + сообщение. Память вачдога (хэш экрана, `limitGen`, `thresholdGen`, перезапуски, `stallAlertAt`) — `sessions.watch_state`, переживает рестарт + - **Вачдог 2.0 (PEP-28, runner/recovery.ts)**: пороги `platform.watchdog` ← env `PEPPA_WATCHDOG_*` ← умолчания (`peppa platform watchdog key=value|reset`: restartMax 3, restartWindowMin 1440, restartDelaysMin 1,5,15, stallRestartMin 60, remindMin 240, remindMax 1, workFrom 9, workTo 19, workDays 1,2,3,4,5, escalateMin 0, idleStopHours 24; 0 = выкл). Упал/пропал раннер стори в `proposing`/`in_progress` (не лимит, не пауза бюджета) → `failed` + `watch_state.restartAt` вместо вопроса, `restartTick` делает `resumeSession` (`auto_restarted`); предел исчерпан — вопрос PM с причиной. Зависший без ответа `stallRestartMin` после алерта — kill + перезапуск. `remindTick`: вопросы question/permission/approval моложе суток — **одно** напоминание аудитории через 4 ч и только в рабочее время (пн–пт 9–19, часовой пояс платформы `PEPPA_TZ`; вне — ждёт утра) (PEP-173, `questions.reminders`; событие `questions`); эскалация `alertAdmins` выключена по умолчанию — зависшие вопросы на дашборде суперадмина; claim атомарный. `idleStopTick`: `waiting_input` без открытых вопросов дольше `idleStopHours` → `stopSession` + сообщение. Память вачдога (хэш экрана, `limitGen`, `thresholdGen`, перезапуски, `stallAlertAt`) — `sessions.watch_state`, переживает рестарт - **Песочница и хосты (PEP-17/40)**: настройки раннеров `isolation` none (по умолчанию, как раньше) / container и `hosts` (id хостов; пусто — Mac Пеппы; хост → всегда контейнер). Все вызовы tmux — по адресу pane `{name, host}` (`tmux.sessionPane(s)`, `runner/exec.ts`: локально или `ssh` ключом `$PEPPA_HOME/ssh/id_ed25519`, ControlMaster; код 255 → `HostUnreachable`, `hasSession` его не глотает — вачдог не объявит раннер пропавшим). Контейнер (`runner/sandbox.ts`): tmux снаружи, `docker run --rm -it --init --name peppa-s` образа `PEPPA_RUNNER_IMAGE` (`infra/runner/Dockerfile`, `scripts/runner-image.sh`), монтируются только рабочая копия (+ `.git` проекта для worktree, `CODEX_HOME` подписки), каталог запуска → `/peppa/run:ro`, свой HOME → `/peppa/home`; env — только сессии/релея/подписки (значения в tmux, в launch.sh только имена); без подписки не стартует; остановка — `killRunner` (tmux + `docker rm -f`). Релей агента (`runner/agent-relay.ts`, веб `/api/agent/[...path]`, токен `agentRelayToken` = HMAC сессии+поколения): `hook` (настоящий `peppa-hook` в Пеппе; ответ ≤25 с, дальше `{wait, rid}`; транскрипт прикладывает шим), `mcp` (`@peppa/mcp/relay`: сервер агента с `lockProject`), `git/…` (прокси в Gitea с токеном бота, только `owner/repo` проекта; в контейнере `GIT_CONFIG_*` insteadOf). Шимы в образе — `infra/runner/peppa-agent.mjs` (`peppa-hook`, `peppa-mcp`). Хосты: таблица `runner_hosts`, `sessions.host_id`/`container` (миграция 0013), `runner/hosts.ts` (`checkHost`, `hostTick` в вачдоге раз в минуту, клон `/ws//s` одноразовым контейнером через релей, каталог запуска tar по SSH), выбор — `pickHost` (наименее занятый онлайн). Веб `/hosts` (суперадмин), «⋯ Настройки проекта → Раннеры»; CLI `peppa host list|key|add|set|check|disable|enable|rm|push-image`. Моки: `mock-docker run` (исполняет команду образа локально, env только из `-e`, `runs.jsonl`), `mock-ssh` (`MOCK_SSH_ROOT/`, свой tmux, `MOCK_SSH_DOWN`) - хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s-g/settings.json` (`claude --settings`) - `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 25c65721..0e1a1c3d 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -38,8 +38,14 @@ export interface WatchdogSettings { restartDelaysMin: number[]; /** A stalled runner whose alert got no answer this long is restarted; 0 = never. */ stallRestartMin: number; - /** Reminders about an unanswered question (after 1× and 2× this); 0 = off. */ + /** A reminder about an unanswered question after this (PEP-173: 4 h); 0 = off. */ remindMin: number; + /** How many reminders one question gets (PEP-173: one — no nagging). */ + remindMax: number; + /** Reminders go only in working time (PEP-173): hours [workFrom, workTo) on workDays (1 = Mon … 7 = Sun), platform time zone. */ + workFrom: number; + workTo: number; + workDays: number[]; /** Then the platform admins hear about it; 0 = off. */ escalateMin: number; /** A story runner in waiting_input with nothing asked is stopped after this; 0 = never. */ @@ -51,8 +57,13 @@ export const WATCHDOG_DEFAULTS: WatchdogSettings = { restartWindowMin: 24 * 60, restartDelaysMin: [1, 5, 15], stallRestartMin: 60, - remindMin: 30, - escalateMin: 120, + remindMin: 240, + remindMax: 1, + workFrom: 9, + workTo: 19, + workDays: [1, 2, 3, 4, 5], + // Stuck questions are on the superadmin's dashboard (PEP-167) — no extra message by default. + escalateMin: 0, idleStopHours: 24, }; @@ -60,7 +71,7 @@ const KEY = "platform.watchdog"; const envName = (k: string) => `PEPPA_WATCHDOG_${k.replace(/[A-Z]/g, (c) => `_${c}`).toUpperCase()}`; function parseValue(k: keyof WatchdogSettings, v: string): number | number[] { - if (k === "restartDelaysMin") { + if (k === "restartDelaysMin" || k === "workDays") { const list = v.split(",").map((x) => Number(x.trim())); if (!list.length || list.some((n) => !Number.isFinite(n) || n < 0)) throw new PeppaError(m("{key}: список минут через запятую, напр. 1,5,15", { key: k })); return list; @@ -72,7 +83,7 @@ function parseValue(k: keyof WatchdogSettings, v: string): number | number[] { /** Defaults ← env `PEPPA_WATCHDOG_*` ← `platform.watchdog`. */ export async function getWatchdogSettings(db: Db): Promise { - const out: WatchdogSettings = { ...WATCHDOG_DEFAULTS, restartDelaysMin: [...WATCHDOG_DEFAULTS.restartDelaysMin] }; + const out: WatchdogSettings = { ...WATCHDOG_DEFAULTS, restartDelaysMin: [...WATCHDOG_DEFAULTS.restartDelaysMin], workDays: [...WATCHDOG_DEFAULTS.workDays] }; for (const k of Object.keys(out) as (keyof WatchdogSettings)[]) { const v = process.env[envName(k)]; if (v) (out as any)[k] = parseValue(k, v); @@ -223,6 +234,14 @@ const KIND_RU: Record = { question: m("Вопрос"), permissio * platform admins after `escalateMin`. `questions.reminders` is claimed atomically, so every * message goes out once whoever ticks. Only questions of the last day (no flood of old ones). */ +/** PEP-173: is it working time in the platform's time zone (PEPPA_TZ, else this machine's)? */ +export function inWorkingTime(now: Date, cfg: Pick): boolean { + const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now); + const hour = Number(parts.find((x) => x.type === "hour")?.value ?? 0); + const day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(parts.find((x) => x.type === "weekday")?.value ?? "") + 1; + return cfg.workDays.includes(day) && hour >= cfg.workFrom && hour < cfg.workTo; +} + export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise { const { remindMin, escalateMin } = o.cfg; if (remindMin <= 0 && escalateMin <= 0) return 0; @@ -241,7 +260,9 @@ export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; const ageMin = Math.round(age / 60_000); const n = q.reminders; const escalate = escalateMin > 0 && n < 3 && age >= escalateMin * 60_000; - const remind = !escalate && remindMin > 0 && n < 2 && age >= (n + 1) * remindMin * 60_000; + // PEP-173: one reminder (remindMax), not before remindMin, and only in working time — outside + // it the reminder waits for the morning. + const remind = !escalate && remindMin > 0 && n < o.cfg.remindMax && age >= (n + 1) * remindMin * 60_000 && inWorkingTime(o.now, o.cfg); if (!escalate && !remind) continue; const next = escalate ? 3 : n + 1; const [claimed] = await db diff --git a/packages/testkit/test/no-repeats.test.ts b/packages/testkit/test/no-repeats.test.ts index d5e4e014..154c5d09 100644 --- a/packages/testkit/test/no-repeats.test.ts +++ b/packages/testkit/test/no-repeats.test.ts @@ -225,7 +225,7 @@ describe("Напоминание обновляет сообщение", () => { const q = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой цвет кнопки?" }); const done = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой шрифт?" }); await core.answerQuestion(db, done.id, "Обычный", "web"); - await runner.remindTick(db, { now: new Date(q.createdAt.getTime() + 31 * 60_000), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} }); + await runner.remindTick(db, { now: new Date(q.createdAt.getTime() + 31 * 60_000), cfg: { ...runner.WATCHDOG_DEFAULTS, remindMin: 30, workFrom: 0, workTo: 24, workDays: [1, 2, 3, 4, 5, 6, 7] }, log: () => {} }); const msgs = (await t.thread()).filter((m) => m.kind === "question"); assert.equal(msgs.length, 2, "no new chat message"); assert.ok(msgs.find((m) => m.question?.id === q.id)!.updatedAt); diff --git a/packages/testkit/test/recovery.test.ts b/packages/testkit/test/recovery.test.ts index 94c04571..02b43899 100644 --- a/packages/testkit/test/recovery.test.ts +++ b/packages/testkit/test/recovery.test.ts @@ -141,7 +141,9 @@ describe("Напоминание и эскалация вопросов", () => const [q] = await db.insert(questions).values({ projectId: proj.id, kind: "question", text: "Какую БД берём?", createdAt: new Date(t0) }).returning(); const sent = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `%q${q!.id}%`))).map((r) => String(r.params.text)); - const at = (m: number) => ({ now: new Date(t0 + m * MIN), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} }); + // The old rhythm (two reminders, escalation) still works when configured; working time: always. + const ALWAYS = { workFrom: 0, workTo: 24, workDays: [1, 2, 3, 4, 5, 6, 7] }; + const at = (m: number) => ({ now: new Date(t0 + m * MIN), cfg: { ...runner.WATCHDOG_DEFAULTS, ...ALWAYS, remindMin: 30, remindMax: 2, escalateMin: 120 }, log: () => {} }); await runner.remindTick(db, at(10)); assert.equal((await sent()).length, 0); @@ -161,6 +163,44 @@ describe("Напоминание и эскалация вопросов", () => }); }); +describe("PEP-173: одно напоминание через 4 часа и только в рабочее время", () => { + test("по умолчанию: одно напоминание через 4 ч, без эскалации; ночью и в выходные — ждёт", async () => { + const d = runner.WATCHDOG_DEFAULTS; + assert.deepEqual({ remindMin: d.remindMin, remindMax: d.remindMax, escalateMin: d.escalateMin }, { remindMin: 240, remindMax: 1, escalateMin: 0 }); + const prev = process.env.PEPPA_TZ; + process.env.PEPPA_TZ = "Asia/Almaty"; + try { + // 2026-11-16 is a Monday. + assert.equal(runner.inWorkingTime(new Date("2026-11-16T10:00:00+05:00"), d), true); + assert.equal(runner.inWorkingTime(new Date("2026-11-16T08:59:00+05:00"), d), false, "before 9"); + assert.equal(runner.inWorkingTime(new Date("2026-11-16T19:00:00+05:00"), d), false, "from 19"); + assert.equal(runner.inWorkingTime(new Date("2026-11-21T12:00:00+05:00"), d), false, "Saturday"); + } finally { + if (prev === undefined) delete process.env.PEPPA_TZ; + else process.env.PEPPA_TZ = prev; + } + + const p = await project({ turns: [] }); + const owner = await core.upsertUserFromGitea(db, { id: 8173, login: "mock-owner-173" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 8173, telegramUserId: 8173 }).where(eq(users.id, owner.id)); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + const t0 = Date.now(); + const [q] = await db.insert(questions).values({ projectId: proj.id, kind: "question", text: "Какой цвет?", createdAt: new Date(t0) }).returning(); + const sent = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `%q${q!.id}%`))).length; + const work = { ...d, workFrom: 0, workTo: 24, workDays: [1, 2, 3, 4, 5, 6, 7] }; + const off = { ...d, workDays: [] as number[] }; + await runner.remindTick(db, { now: new Date(t0 + 60 * MIN), cfg: work, log: () => {} }); + assert.equal(await sent(), 0, "not after an hour"); + await runner.remindTick(db, { now: new Date(t0 + 241 * MIN), cfg: off, log: () => {} }); + assert.equal(await sent(), 0, "out of working time — waits"); + await runner.remindTick(db, { now: new Date(t0 + 300 * MIN), cfg: work, log: () => {} }); + assert.equal(await sent(), 1, "one reminder in working time"); + await runner.remindTick(db, { now: new Date(t0 + 900 * MIN), cfg: work, log: () => {} }); + assert.equal(await sent(), 1, "and only one"); + }); +}); + describe("Уборка давних waiting_input", () => { test("Раннер ждёт сутки", async () => { const p = await storyAtWork({ turns: [[{ say: "Готов." }]] });