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 01/11] =?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 02/11] 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 cf317bfeac1e78bb91a655be0eb0a7525eed048e 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 17:14:56 +0500 Subject: [PATCH 03/11] =?UTF-8?q?PEP-169:=20=D0=B2=D0=BA=D0=BB=D0=B0=D0=B4?= =?UTF-8?q?=D0=BA=D0=B0=20=C2=ABGitea=C2=BB=20=D0=B4=D0=BB=D1=8F=20=D1=81?= =?UTF-8?q?=D1=83=D0=BF=D0=B5=D1=80=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=D0=B0=20?= =?UTF-8?q?=E2=80=94=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=20=D0=B8=20?= =?UTF-8?q?=D1=80=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8?= =?UTF-8?q?=D0=B8,=20=D1=81=D0=B2=D1=8F=D0=B7=D1=8C=20=D1=81=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/gitea/page.tsx | 135 ++++++++++++++++++ apps/web/components/Sidebar.tsx | 3 +- .../proposal.md | 11 ++ .../specs/gitea-integration/spec.md | 16 +++ .../tasks.md | 10 ++ openspec/specs/gitea-integration/spec.md | 15 ++ packages/core/src/gitea-server.ts | 71 +++++++++ packages/core/src/index.ts | 1 + packages/shared/src/i18n/en/admin.ts | 28 ++++ 9 files changed, 289 insertions(+), 1 deletion(-) create mode 100644 apps/web/app/(app)/gitea/page.tsx create mode 100644 openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/proposal.md create mode 100644 openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/specs/gitea-integration/spec.md create mode 100644 openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/tasks.md create mode 100644 packages/core/src/gitea-server.ts diff --git a/apps/web/app/(app)/gitea/page.tsx b/apps/web/app/(app)/gitea/page.tsx new file mode 100644 index 00000000..8129866c --- /dev/null +++ b/apps/web/app/(app)/gitea/page.tsx @@ -0,0 +1,135 @@ +// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ExternalLink, GitBranch, Lock } from "lucide-react"; +import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core"; +import { ago, Empty, Notice, PageHeader, Section } from "@/components/common"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; +import type { Translator } from "@peppa/shared/i18n"; + +export async function generateMetadata() { + const t = await getT(); + return { title: t("Gitea — Peppa FACTORY") }; +} + +type Params = { q?: string; show?: string }; + +function RepoRow({ r, t }: { r: GiteaServerRepo; t: Translator }) { + return ( +
  • +
    + + {r.fullName} + + + {r.private ? ( + + + {t("приватный")} + + ) : ( + {t("публичный")} + )} + {r.empty && {t("пустой")}} + {r.archived && {t("в архиве")}} + {r.fork && {t("форк")}} + {r.project ? ( + + {t("проект {key} · {name}", { key: r.project.key, name: r.project.name })} + + ) : ( + {t("не подключён к проекту")} + )} +
    + {r.description &&
    {r.description}
    } +
    + {t("ветка {branch} · обновлён {when} · {size}", { branch: r.defaultBranch || "—", when: ago(r.updatedAt, t), size: r.sizeKb >= 1024 ? `${(r.sizeKb / 1024).toFixed(1)} MB` : `${r.sizeKb} KB` })} +
    +
  • + ); +} + +export default async function GiteaPage({ searchParams }: { searchParams: Promise }) { + const user = await requireUser(); + const t = await getT(); + if (!(await isSuperadmin(db, user))) notFound(); + const q = await searchParams; + const o = await giteaServerOverview(db); + const needle = (q.q ?? "").trim().toLowerCase(); + const show = q.show === "linked" || q.show === "unlinked" ? q.show : "all"; + const repos = o.repos.filter( + (r) => (!needle || r.fullName.toLowerCase().includes(needle) || r.description.toLowerCase().includes(needle)) && (show === "all" || (show === "linked") === !!r.project), + ); + const owners = new Map(); + for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1); + const linked = o.repos.filter((r) => r.project).length; + + return ( + +
    + Gitea}> + {t("Git-сервер платформы и репозитории на нём — как их видит бот Peppa FACTORY. Раздел видят только суперадмины.")} + + +
    + +
    + {t("Адрес")}:{" "} + {o.url ? ( + + {o.url} + + ) : ( + "—" + )} +
    +
    + {t("Бот")}: {o.bot?.login ?? "—"} + {o.bot && (o.bot.admin ? {t("админ сервера — видит все репозитории")} : {t("не админ — видит публичные и свои репозитории")})} +
    + {o.repos.length > 0 && ( +
    + {t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "} + {[...owners].sort((a, b) => b[1] - a[1]).map(([owner, n]) => `${owner} ${n}`).join(", ")} +
    + )} +
    +
    + + {o.error && {t("Gitea не ответила: {error}", { error: o.error })}} + +
    +
    + + + +
    + {repos.length === 0 ? ( + {t("Репозиториев не найдено.")} + ) : ( + +
      + {repos.map((r) => ( + + ))} +
    +
    + )} +
    +
    +
    + ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 0137c70c..57f363cd 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react"; +import { Bot, Contact, FolderKanban, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react"; import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { LanguageSwitcher } from "@/components/I18n"; @@ -35,6 +35,7 @@ const ITEMS: Item[] = [ { href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") }, { href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, { href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, + { href: "/gitea", label: m("Gitea"), icon: GitBranch, match: (p) => p.startsWith("/gitea"), admin: true }, { href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, { href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, { href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, diff --git a/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/proposal.md b/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/proposal.md new file mode 100644 index 00000000..d215c282 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/proposal.md @@ -0,0 +1,11 @@ +## Why +Суперадмину негде посмотреть, что лежит на Git-сервере платформы: какие репозитории есть, чьи они и какие из них подключены к проектам Peppa (PEP-169). + +## What Changes +- Пункт меню «Gitea» (`/gitea`) только для суперадмина; остальным — 404. +- Блок «Сервер»: адрес Gitea, учётка бота и видит ли он все репозитории (админ сервера) или только публичные и свои. +- Список репозиториев, которые видит peppa-bot (`/repos/search`, по свежести): владелец/имя со ссылкой в Gitea, приватность, пустой/архив/форк, ветка по умолчанию, когда обновлён, размер, ссылка на проект Peppa или «не подключён к проекту»; поиск и фильтр «подключённые / без проекта». +- Ядро: `giteaServerOverview(db)` в `packages/core/src/gitea-server.ts`; ошибка Gitea показывается на странице, не роняет её. + +## Impact +- `packages/core/src/gitea-server.ts`, `apps/web/app/(app)/gitea/page.tsx`, `apps/web/components/Sidebar.tsx`, `packages/shared/src/i18n/en/admin.ts`. diff --git a/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/specs/gitea-integration/spec.md b/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/specs/gitea-integration/spec.md new file mode 100644 index 00000000..557141b4 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/specs/gitea-integration/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: Суперадмин видит репозитории Gitea +Веб SHALL показывать суперадмину раздел «Gitea» со списком репозиториев сервера, видимых боту, и их связью с проектами Peppa. + +#### Scenario: Суперадмин открывает раздел +- **WHEN** суперадмин открывает `/gitea` +- **THEN** видит адрес сервера, учётку бота и список репозиториев со ссылками в Gitea и на проект Peppa, если он подключён + +#### Scenario: Не суперадмин +- **WHEN** обычный пользователь открывает `/gitea` +- **THEN** получает 404, а пункта «Gitea» в меню у него нет + +#### Scenario: Gitea недоступна +- **WHEN** Gitea не отвечает +- **THEN** страница открывается с сообщением об ошибке и пустым списком diff --git a/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/tasks.md b/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/tasks.md new file mode 100644 index 00000000..f3c84716 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-169-gitea-admin-tab/tasks.md @@ -0,0 +1,10 @@ +## 1. Ядро +- [x] 1.1 `giteaServerOverview(db)`: бот, `/repos/search` постранично, связь с `projects` по owner/repo, ошибка — в поле `error` + +## 2. Веб +- [x] 2.1 Страница `/gitea` (только суперадмин), поиск и фильтр +- [x] 2.2 Пункт меню «Gitea» (`admin: true`) +- [x] 2.3 Переводы en + +## 3. Проверка +- [x] 3.1 typecheck, словарь, i18n-check; данные с живой Gitea (76 репозиториев, 27 подключены) diff --git a/openspec/specs/gitea-integration/spec.md b/openspec/specs/gitea-integration/spec.md index c7931608..9d385242 100644 --- a/openspec/specs/gitea-integration/spec.md +++ b/openspec/specs/gitea-integration/spec.md @@ -44,3 +44,18 @@ - **GIVEN** стори PAY-7 в «Ревью» с открытым PR - **WHEN** PR смержен в интерфейсе Gitea - **THEN** PAY-7 в «Готово», сообщение «готово к ревью» закрыто + +### Requirement: Суперадмин видит репозитории Gitea +Веб SHALL показывать суперадмину раздел «Gitea» со списком репозиториев сервера, видимых боту, и их связью с проектами Peppa. + +#### Scenario: Суперадмин открывает раздел +- **WHEN** суперадмин открывает `/gitea` +- **THEN** видит адрес сервера, учётку бота и список репозиториев со ссылками в Gitea и на проект Peppa, если он подключён + +#### Scenario: Не суперадмин +- **WHEN** обычный пользователь открывает `/gitea` +- **THEN** получает 404, а пункта «Gitea» в меню у него нет + +#### Scenario: Gitea недоступна +- **WHEN** Gitea не отвечает +- **THEN** страница открывается с сообщением об ошибке и пустым списком diff --git a/packages/core/src/gitea-server.ts b/packages/core/src/gitea-server.ts new file mode 100644 index 00000000..784f40b7 --- /dev/null +++ b/packages/core/src/gitea-server.ts @@ -0,0 +1,71 @@ +// PEP-169: what the Gitea server holds, as peppa-bot sees it — for the superadmin «Gitea» page. +import { projects, type Db } from "@peppa/db"; +import type { GiteaRepo, GiteaUser } from "./gitea.ts"; +import { giteaForBot } from "./users.ts"; + +export interface GiteaServerRepo { + fullName: string; + owner: string; + name: string; + description: string; + private: boolean; + empty: boolean; + archived: boolean; + fork: boolean; + defaultBranch: string; + htmlUrl: string; + updatedAt: Date | null; + sizeKb: number; + /** The Peppa project this repository backs, if any. */ + project: { key: string; name: string } | null; +} + +export interface GiteaServerOverview { + url: string; + bot: { login: string; admin: boolean } | null; + repos: GiteaServerRepo[]; + error: string | null; +} + +type SearchRepo = GiteaRepo & { description?: string; archived?: boolean; fork?: boolean; updated_at?: string; size?: number }; + +const PAGE = 50; +const MAX_PAGES = 40; + +/** Repositories visible to peppa-bot (all of them when it is a site admin), newest first. */ +export async function giteaServerOverview(db: Db): Promise { + let client; + try { + client = giteaForBot(); + } catch (e) { + return { url: "", bot: null, repos: [], error: (e as Error).message }; + } + const linked = new Map((await db.select({ key: projects.key, name: projects.name, owner: projects.giteaOwner, repo: projects.giteaRepo }).from(projects)).map((p) => [`${p.owner}/${p.repo}`.toLowerCase(), { key: p.key, name: p.name }])); + try { + const me = await client.request("GET", "/user"); + const found: SearchRepo[] = []; + for (let page = 1; page <= MAX_PAGES; page++) { + const res = await client.request<{ ok: boolean; data: SearchRepo[] }>("GET", `/repos/search?limit=${PAGE}&page=${page}&sort=updated&order=desc`); + found.push(...res.data); + if (res.data.length < PAGE) break; + } + const repos = found.map((r) => ({ + fullName: r.full_name, + owner: r.owner.login, + name: r.name, + description: r.description ?? "", + private: r.private, + empty: r.empty, + archived: !!r.archived, + fork: !!r.fork, + defaultBranch: r.default_branch, + htmlUrl: r.html_url, + updatedAt: r.updated_at ? new Date(r.updated_at) : null, + sizeKb: r.size ?? 0, + project: linked.get(r.full_name.toLowerCase()) ?? null, + })); + return { url: client.baseUrl, bot: { login: me.login, admin: !!me.is_admin }, repos, error: null }; + } catch (e) { + return { url: client.baseUrl, bot: null, repos: [], error: (e as Error).message }; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index efa518ee..aaee18f3 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,6 +13,7 @@ export * from "./hosts.ts"; export * from "./telegram.ts"; export * from "./crypto.ts"; export * from "./gitea.ts"; +export * from "./gitea-server.ts"; export * from "./users.ts"; export * from "./oauth.ts"; export * from "./access.ts"; diff --git a/packages/shared/src/i18n/en/admin.ts b/packages/shared/src/i18n/en/admin.ts index 1f0daa27..86c9443d 100644 --- a/packages/shared/src/i18n/en/admin.ts +++ b/packages/shared/src/i18n/en/admin.ts @@ -174,6 +174,34 @@ export const admin: Dict = { "Ни в одном проекте секретов нет.": "No project has secrets.", "секретов {n} · старейший {oldest} · выдан агенту {used}": "secrets {n} · oldest {oldest} · issued to an agent {used}", + // Gitea (PEP-169) + "Gitea — Peppa FACTORY": "Gitea — Peppa FACTORY", + Gitea: "Gitea", + приватный: "private", + публичный: "public", + пустой: "empty", + "в архиве": "archived", + форк: "fork", + "проект {key} · {name}": "project {key} · {name}", + "не подключён к проекту": "not linked to a project", + "ветка {branch} · обновлён {when} · {size}": "branch {branch} · updated {when} · {size}", + "Git-сервер платформы и репозитории на нём — как их видит бот Peppa FACTORY. Раздел видят только суперадмины.": + "The platform's git server and its repositories, as the Peppa FACTORY bot sees them. Only superadmins see this section.", + Сервер: "Server", + Адрес: "Address", + Бот: "Bot", + "админ сервера — видит все репозитории": "server admin — sees every repository", + "не админ — видит публичные и свои репозитории": "not an admin — sees public and its own repositories", + "Репозиториев: {n} · подключены к проектам: {linked}": "Repositories: {n} · linked to projects: {linked}", + "Gitea не ответила: {error}": "Gitea did not respond: {error}", + Репозитории: "Repositories", + "Поиск по имени или описанию": "Search by name or description", + все: "all", + "подключённые к проектам": "linked to projects", + "без проекта": "without a project", + Показать: "Show", + "Репозиториев не найдено.": "No repositories found.", + // Hosts "Хосты — Peppa FACTORY": "Hosts — Peppa FACTORY", "не проверен": "not checked", From cc7d2284e6aff3cf0a062f4a2c221bc05e3678b2 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 17:27:17 +0500 Subject: [PATCH 04/11] =?UTF-8?q?PEP-169:=20=D0=BA=D0=B0=D0=B7=D0=B0=D1=85?= =?UTF-8?q?=D1=81=D0=BA=D0=B8=D0=B9=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D0=B2=D0=BA=D0=BB=D0=B0=D0=B4=D0=BA=D0=B8=20=C2=ABGit?= =?UTF-8?q?ea=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- packages/shared/src/i18n/kk/admin.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts index 67d38da2..39af1a4d 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -228,4 +228,25 @@ export const admin: Dict = { "Главная, стори, раннер": "Басты бет, стори, раннер", "Список сочетаний": "Пернелер тіркесімдерінің тізімі", "Закрыть палитру или окно": "Палитраны немесе терезені жабу", + // Gitea (PEP-169) + "Gitea — Peppa FACTORY": "Gitea — Peppa FACTORY", + Gitea: "Gitea", + пустой: "бос", + форк: "форк", + "проект {key} · {name}": "жоба {key} · {name}", + "не подключён к проекту": "жобаға қосылмаған", + "ветка {branch} · обновлён {when} · {size}": "тармақ {branch} · жаңартылды {when} · {size}", + "Git-сервер платформы и репозитории на нём — как их видит бот Peppa FACTORY. Раздел видят только суперадмины.": + "Платформаның git-сервері және ондағы репозиторийлер — Peppa FACTORY боты көретіндей. Бөлімді тек суперадминдер көреді.", + Сервер: "Сервер", + Адрес: "Мекенжай", + Бот: "Бот", + "админ сервера — видит все репозитории": "сервер админі — барлық репозиторийлерді көреді", + "не админ — видит публичные и свои репозитории": "админ емес — жария және өз репозиторийлерін көреді", + "Репозиториев: {n} · подключены к проектам: {linked}": "Репозиторийлер: {n} · жобаларға қосылған: {linked}", + Репозитории: "Репозиторийлер", + "Поиск по имени или описанию": "Атауы немесе сипаттамасы бойынша іздеу", + "подключённые к проектам": "жобаларға қосылғандар", + "без проекта": "жобасыз", + "Репозиториев не найдено.": "Репозиторий табылмады.", }; From 3d70d0e48105adda93309bdf993db22b313d27c9 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 17:27:38 +0500 Subject: [PATCH 05/11] =?UTF-8?q?PEP-169:=20=D0=BA=D0=B0=D0=B7=D0=B0=D1=85?= =?UTF-8?q?=D1=81=D0=BA=D0=B8=D0=B5=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=D1=8B=20=D0=B2=D0=BA=D0=BB=D0=B0=D0=B4=D0=BA=D0=B8=20?= =?UTF-8?q?=C2=ABGitea=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/i18n/kk/admin.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts index 67d38da2..2550d31e 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -152,6 +152,26 @@ export const admin: Dict = { "Секреты проектов": "Жобалар құпиялары", "Ни в одном проекте секретов нет.": "Бірде-бір жобада құпия жоқ.", "секретов {n} · старейший {oldest} · выдан агенту {used}": "құпиялар {n} · ең ескісі {oldest} · агентке берілді {used}", + // Gitea (PEP-169) + "Gitea — Peppa FACTORY": "Gitea — Peppa FACTORY", + "Gitea": "Gitea", + "пустой": "бос", + "форк": "форк", + "проект {key} · {name}": "жоба {key} · {name}", + "не подключён к проекту": "жобаға қосылмаған", + "ветка {branch} · обновлён {when} · {size}": "тармақ {branch} · жаңартылды {when} · {size}", + "Git-сервер платформы и репозитории на нём — как их видит бот Peppa FACTORY. Раздел видят только суперадмины.": "Платформаның Git-сервері және ондағы репозиторийлер — Peppa FACTORY боты көретіндей. Бөлімді тек суперәкімшілер көреді.", + "Сервер": "Сервер", + "Адрес": "Мекенжай", + "Бот": "Бот", + "админ сервера — видит все репозитории": "сервер әкімшісі — барлық репозиторийлерді көреді", + "не админ — видит публичные и свои репозитории": "әкімші емес — ашық және өз репозиторийлерін көреді", + "Репозиториев: {n} · подключены к проектам: {linked}": "Репозиторийлер: {n} · жобаларға қосылған: {linked}", + "Репозитории": "Репозиторийлер", + "Поиск по имени или описанию": "Аты немесе сипаттамасы бойынша іздеу", + "подключённые к проектам": "жобаларға қосылғандар", + "без проекта": "жобасыз", + "Репозиториев не найдено.": "Репозиторийлер табылмады.", "Хосты — Peppa FACTORY": "Хосттар — Peppa FACTORY", "не проверен": "тексерілмеген", "онлайн": "онлайн", From d03586d2bc1a0056b9866ecbff4434c093e75889 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 17:31:38 +0500 Subject: [PATCH 06/11] =?UTF-8?q?PEP-169:=20=D1=83=D0=B1=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B7=D0=B0=D0=B4=D0=B2=D0=BE=D0=B5=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D0=BA=D0=B0=D0=B7=D0=B0=D1=85=D1=81=D0=BA=D0=B8=D0=B5?= =?UTF-8?q?=20=D0=BA=D0=BB=D1=8E=D1=87=D0=B8=20=D0=BF=D0=BE=D1=81=D0=BB?= =?UTF-8?q?=D0=B5=20=D1=81=D0=BB=D0=B8=D1=8F=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- infra/act-runner/config.yaml | 4 ++-- packages/shared/src/i18n/kk/admin.ts | 20 -------------------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/infra/act-runner/config.yaml b/infra/act-runner/config.yaml index 03fe7506..1bb93df3 100644 --- a/infra/act-runner/config.yaml +++ b/infra/act-runner/config.yaml @@ -3,8 +3,8 @@ log: level: info runner: file: .runner - # Mac — и сборка, и стенды: не больше 2 job одновременно на регистрацию. - capacity: 2 + # Mac (24 ядра, 64 ГБ) — и сборка, и стенды. Было 2: при 13 открытых PR очередь проверок росла на часы (PEP-157). + capacity: 4 timeout: 1h fetch_timeout: 5s fetch_interval: 2s diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts index d3866aac..39af1a4d 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -152,26 +152,6 @@ export const admin: Dict = { "Секреты проектов": "Жобалар құпиялары", "Ни в одном проекте секретов нет.": "Бірде-бір жобада құпия жоқ.", "секретов {n} · старейший {oldest} · выдан агенту {used}": "құпиялар {n} · ең ескісі {oldest} · агентке берілді {used}", - // Gitea (PEP-169) - "Gitea — Peppa FACTORY": "Gitea — Peppa FACTORY", - "Gitea": "Gitea", - "пустой": "бос", - "форк": "форк", - "проект {key} · {name}": "жоба {key} · {name}", - "не подключён к проекту": "жобаға қосылмаған", - "ветка {branch} · обновлён {when} · {size}": "тармақ {branch} · жаңартылды {when} · {size}", - "Git-сервер платформы и репозитории на нём — как их видит бот Peppa FACTORY. Раздел видят только суперадмины.": "Платформаның Git-сервері және ондағы репозиторийлер — Peppa FACTORY боты көретіндей. Бөлімді тек суперәкімшілер көреді.", - "Сервер": "Сервер", - "Адрес": "Мекенжай", - "Бот": "Бот", - "админ сервера — видит все репозитории": "сервер әкімшісі — барлық репозиторийлерді көреді", - "не админ — видит публичные и свои репозитории": "әкімші емес — ашық және өз репозиторийлерін көреді", - "Репозиториев: {n} · подключены к проектам: {linked}": "Репозиторийлер: {n} · жобаларға қосылған: {linked}", - "Репозитории": "Репозиторийлер", - "Поиск по имени или описанию": "Аты немесе сипаттамасы бойынша іздеу", - "подключённые к проектам": "жобаларға қосылғандар", - "без проекта": "жобасыз", - "Репозиториев не найдено.": "Репозиторийлер табылмады.", "Хосты — Peppa FACTORY": "Хосттар — Peppa FACTORY", "не проверен": "тексерілмеген", "онлайн": "онлайн", From 094ab632cc75c6937e415cdbe2206d1d5b969c0e 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 16:48:19 +0500 Subject: [PATCH 07/11] =?UTF-8?q?PEP-152:=20=D1=84=D0=BE=D1=80=D0=BC=D0=B0?= =?UTF-8?q?=D1=82=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=B0=20=E2=80=94=20=D1=81?= =?UTF-8?q?=D1=83=D1=82=D1=8C,=20=D1=87=D1=82=D0=BE=20=D0=BD=D1=83=D0=B6?= =?UTF-8?q?=D0=BD=D0=BE=20=D0=BE=D1=82=20=D0=B2=D0=B0=D1=81,=20=D0=B3?= =?UTF-8?q?=D0=B4=D0=B5=20=D0=BF=D0=BE=D1=81=D0=BC=D0=BE=D1=82=D1=80=D0=B5?= =?UTF-8?q?=D1=82=D1=8C,=20=D0=BF=D0=BE=D0=B4=D1=80=D0=BE=D0=B1=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B8=20=D0=BF=D0=BE=D0=B4=20=C2=AB=D0=9F?= =?UTF-8?q?=D0=BE=D0=B4=D1=80=D0=BE=D0=B1=D0=BD=D0=B5=D0=B5=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Сообщение агента пользователю собирается из полей summary / need / link / details (core/agent-message.ts); основной текст проверяется при приёме (длина, словарь, файлы, ветки, команды, номера PR, статусы из кода) — нарушение возвращается агенту, после трёх отказов подряд сообщение уходит с нейтральной первой строкой. Разбор словаря — общий модуль @peppa/shared/glossary. Сайт и Telegram показывают основной текст, details — под «Подробнее». Карточка «готово» и реплика конца хода — в том же формате. Правила агентам, переводы en/kk, тесты по сценариям, change pep-152-agent-message-format в архиве. Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 39 ++- AGENTS.md | 1 + apps/bot/src/bot.ts | 6 +- apps/bot/src/render.ts | 15 +- apps/web/app/(app)/chats/[chat]/page.tsx | 27 +- apps/web/components/cards.tsx | 17 +- apps/web/components/common.tsx | 13 + apps/web/next-env.d.ts | 4 +- .../design.md | 26 ++ .../proposal.md | 26 ++ .../specs/agent-messages/spec.md | 91 ++++++ .../tasks.md | 20 ++ openspec/specs/agent-messages/spec.md | 90 ++++++ packages/core/src/agent-message.ts | 216 +++++++++++++ packages/core/src/chats.ts | 22 +- packages/core/src/index.ts | 2 + packages/core/src/message-details.ts | 47 +++ packages/core/src/review-card.ts | 61 +++- packages/core/src/sessions.ts | 4 +- packages/core/src/tasks.ts | 30 +- packages/mcp/src/agent.ts | 79 +++-- packages/runner/src/hook.ts | 19 +- packages/runner/src/review-card.ts | 7 +- packages/runner/src/reviewer.ts | 6 +- packages/shared/package.json | 3 +- packages/shared/src/glossary.ts | 117 +++++++ packages/shared/src/i18n/en/story.ts | 11 + packages/shared/src/i18n/index.ts | 3 + packages/shared/src/i18n/kk/story.ts | 11 + packages/testkit/src/glossary-check.ts | 116 +------ .../testkit/test/agent-message-format.test.ts | 306 ++++++++++++++++++ packages/testkit/test/agent-messages.test.ts | 9 +- packages/testkit/test/autonomy.test.ts | 4 +- packages/testkit/test/cjm.test.ts | 4 +- packages/testkit/test/claude-live.test.ts | 5 +- .../test/factory-messages-verbatim.test.ts | 7 +- packages/testkit/test/reviewer.test.ts | 10 +- template/RULES.md | 50 ++- 38 files changed, 1301 insertions(+), 223 deletions(-) create mode 100644 openspec/changes/archive/2026-11-16-pep-152-agent-message-format/design.md create mode 100644 openspec/changes/archive/2026-11-16-pep-152-agent-message-format/proposal.md create mode 100644 openspec/changes/archive/2026-11-16-pep-152-agent-message-format/specs/agent-messages/spec.md create mode 100644 openspec/changes/archive/2026-11-16-pep-152-agent-message-format/tasks.md create mode 100644 packages/core/src/agent-message.ts create mode 100644 packages/core/src/message-details.ts create mode 100644 packages/shared/src/glossary.ts create mode 100644 packages/testkit/test/agent-message-format.test.ts diff --git a/.peppa/memory.md b/.peppa/memory.md index a071132f..cdba6092 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -3,52 +3,51 @@ Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения. ## Команды -- Экраны без живых данных: `PEPPA_HOME= PEPPA_DB=/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm` (принимает путь SQLite, шапка про Postgres устарела), `next dev -p <порт>` в apps/web с тем же env и `PEPPA_WEB_URL`, `peppa web login-link mock-pm`; страницы — curl с cookie (текст без `